From e1966ebc0ca6d8c2b5f42647af8902234bd403e0 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 14:09:02 +0800 Subject: [PATCH] Validate JavaScript native wrapper identity with N-API type tags Pin the matched upstream type-tag implementation, brand native classes by deterministic build inputs, and cover collection, descriptor, callback, lifetime, and ownership boundaries. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 1 + Cargo.lock | 53 +-- bindings/js/Cargo.toml | 15 +- bindings/js/README.md | 4 + .../fixtures/native-class-boundary.cjs | 320 ++++++++++++++++++ .../native-class-boundary-hooks.e2e.mjs | 22 ++ .../js/__test__/native-class-boundary.e2e.mjs | 35 ++ bindings/js/build.rs | 4 + bindings/js/build_support/native_branding.rs | 252 ++++++++++++++ bindings/js/package.json | 4 +- bindings/js/src/benchmarks.rs | 19 +- bindings/js/src/com.rs | 226 +++++++------ bindings/js/src/com_borrowed.rs | 14 +- bindings/js/src/com_completion.rs | 20 +- bindings/js/src/com_raw.rs | 49 +-- bindings/js/src/js_boundary_tests.rs | 27 ++ bindings/js/src/lib.rs | 5 + bindings/js/src/native_class_ref.rs | 27 ++ bindings/js/src/native_class_test_hooks.rs | 144 ++++++++ bindings/js/src/property_value.rs | 23 +- bindings/js/src/value.rs | 11 +- bindings/js/src/win32.rs | 33 +- bindings/js/src/win32_boundary.rs | 107 ++---- bindings/js/src/winrt_array.rs | 11 +- bindings/js/src/winrt_delegate.rs | 5 +- bindings/js/src/winrt_delegate_method.rs | 62 ++-- bindings/js/src/winrt_element_factory.rs | 21 +- bindings/js/src/winrt_implementation.rs | 83 ++--- bindings/js/src/winrt_methods.rs | 10 +- bindings/js/src/winrt_struct.rs | 11 +- bindings/js/src/winrt_types.rs | 12 +- .../javascript-binding-internals.md | 66 ++++ 32 files changed, 1311 insertions(+), 385 deletions(-) create mode 100644 bindings/js/__test__/fixtures/native-class-boundary.cjs create mode 100644 bindings/js/__test__/native-class-boundary-hooks.e2e.mjs create mode 100644 bindings/js/__test__/native-class-boundary.e2e.mjs create mode 100644 bindings/js/build_support/native_branding.rs create mode 100644 bindings/js/src/native_class_ref.rs create mode 100644 bindings/js/src/native_class_test_hooks.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 892557c1..edce2257 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -389,6 +389,7 @@ jobs: npx napi build --no-const-enum --platform --release --target x86_64-pc-windows-msvc --features test-hooks -o dist npm run build:entrypoints --silent node scripts\verify-runtime-artifact.mjs dist --test-hooks + npm run test:native-classes:hooks - name: Stage test-hooks artifact shell: pwsh run: | diff --git a/Cargo.lock b/Cargo.lock index f31e8e22..ef9eaa42 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -307,19 +307,9 @@ dependencies = [ [[package]] name = "ctor" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "424e0138278faeb2b401f174ad17e715c829512d74f3d1e81eb43365c2e0590e" -dependencies = [ - "ctor-proc-macro", - "dtor", -] - -[[package]] -name = "ctor-proc-macro" -version = "0.0.7" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" [[package]] name = "digest" @@ -331,21 +321,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "dtor" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404d02eeb088a82cfd873006cb713fe411306c7d182c344905e101fb1167d301" -dependencies = [ - "dtor-proc-macro", -] - -[[package]] -name = "dtor-proc-macro" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" - [[package]] name = "dyn-clone" version = "1.0.20" @@ -616,9 +591,11 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "napi-derive-backend", "pollster", "serde", "serde_json", + "sha2", "windows", "windows-future", "windows-string", @@ -677,30 +654,30 @@ checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "napi" -version = "3.8.3" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6944d0bf100571cd6e1a98a316cdca262deb6fccf8d93f5ae1502ca3fc88bd3" +checksum = "6f71d6bc097c4a6eb853c3f24991ab8c9f50f57d1f719e305175541482217e36" dependencies = [ "bitflags", "ctor", "futures", "napi-build", - "napi-sys 3.2.1", + "napi-sys 3.3.2", "nohash-hasher", "rustc-hash", ] [[package]] name = "napi-build" -version = "2.3.1" +version = "2.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d376940fd5b723c6893cd1ee3f33abbfd86acb1cd1ec079f3ab04a2a3bc4d3b1" +checksum = "9befcb51d87271051c0c11aaf625d09340266b7f1ac3fef5975e62274dc2813f" [[package]] name = "napi-derive" -version = "3.5.2" +version = "3.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c914b5e420182bfb73504e0607592cdb8e2e21437d450883077669fb72a114d" +checksum = "4d5c9c02556ea6dc99dffd36c1ce60141411657438501a125b675776d011ce92" dependencies = [ "convert_case", "ctor", @@ -712,9 +689,9 @@ dependencies = [ [[package]] name = "napi-derive-backend" -version = "5.0.2" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0864cf6a82e2cfb69067374b64c9253d7e910e5b34db833ed7495dda56ccb18" +checksum = "6a9d8365cf97f54d9b6d6dbf83a25ca227ad7d6e920717426c599225aca6740b" dependencies = [ "convert_case", "proc-macro2", @@ -734,9 +711,9 @@ dependencies = [ [[package]] name = "napi-sys" -version = "3.2.1" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb602b84d7c1edae45e50bbf1374696548f36ae179dfa667f577e384bb90c2b" +checksum = "6801fc65ba4d7035636e93635e281113f00410401a237dcd4f55b1565ead2115" dependencies = [ "libloading 0.9.0", ] diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index 2c15768d..414acb95 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -2,6 +2,7 @@ [package] authors = ["Microsoft"] edition = "2021" +rust-version = "1.88" name = "jswinrt_rs" version = "0.1.0" license = "MIT" @@ -15,8 +16,8 @@ crate-type = ["cdylib"] test-hooks = ["dynwinrt/test-hooks", "windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_Media_Audio_Endpoints", "windows/Win32_UI_Shell_PropertiesSystem", "windows/ApplicationModel_Background"] [dependencies] -napi = { version = "3", features = ["napi7"] } -napi-derive = "3.0.0" +napi = { version = "=3.12.0", features = ["napi8"] } +napi-derive = "=3.6.1" dynwinrt = { path = "../../crates/dynwinrt" } windows-future = "0.3.2" windows-string = "0.0.0" @@ -63,6 +64,16 @@ features = [ [build-dependencies] cc = "1" napi-build = "2" +# Keep class conversion glue paired with the pinned runtime. +napi-derive-backend = "=6.1.0" +sha2 = "0.10" + +[dev-dependencies] +sha2 = "0.10" + +[[test]] +name = "native-branding" +path = "build_support/native_branding.rs" [profile.release] lto = true diff --git a/bindings/js/README.md b/bindings/js/README.md index 9b7404b2..bcd16892 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -403,6 +403,10 @@ Complete native struct collection support is tracked in - **Windows 10 / 11** — x64 and arm64 native binaries shipped via `napi-rs` prebuilds - **Node.js** ≥ 18 (Electron, plain Node, VS Code extensions, …) +- **Native class validation** uses N-API 8 type tags. Keep runtime facades from + the same installed package; native values from differently branded builds + are rejected rather than reinterpreted. +- **Building from source** requires Rust 1.88 or later. ## Links diff --git a/bindings/js/__test__/fixtures/native-class-boundary.cjs b/bindings/js/__test__/fixtures/native-class-boundary.cjs new file mode 100644 index 00000000..e60b1e93 --- /dev/null +++ b/bindings/js/__test__/fixtures/native-class-boundary.cjs @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +const assert = require('node:assert/strict') +const { Worker, parentPort } = require('node:worker_threads') +const root = require('../../dist/winrt.js') +const com = require('../../dist/com-unsafe.js') +const win32 = require('../../dist/win32-unsafe.js') +const { DynWinRtValue: Value, DynWinRtType: Type } = root +const { DynWin32: W, DynWin32Function: F } = win32 + +root.roInitialize(1) +let rejected = 0 +function report(details = {}) { + const result = { mode, rejected, arch: process.arch, node: process.version, ...details } + if (parentPort) parentPort.postMessage(result) + else console.log(JSON.stringify(result)) +} + +function reject(call, name = 'DynWinRTValue') { + assert.throws(call, (error) => { + assert.match(error.message, /Failed to recover|Failed to unwrap|not an instance of class/) + assert.ok(error.message.includes(name), error.message) + return true + }) + rejected++ +} + +function openOwnProcess() { + const result = F.bind({ + dll: 'kernel32.dll', + entryPoint: 'OpenProcess', + parameters: [ + { type: 'u32', direction: 'in' }, + { type: 'bool32', direction: 'in' }, + { type: 'u32', direction: 'in' }, + ], + returnType: 'handle', + returnCleanup: 'closeHandle', + successRule: 'nonnull', + captureLastError: true, + }).invoke([W.u32(0x1000), W.bool32(false), W.u32(process.pid)]) + assert.equal(result.succeeded, true, `OpenProcess failed: ${result.lastError}`) + const resource = W.toResource(result.returnValue) + assert.ok(resource) + assert.equal(resource.closed, false) + return resource +} + +function checkResourceUsable(resource) { + const result = F.bind({ + dll: 'kernel32.dll', + entryPoint: 'GetProcessId', + parameters: [{ type: 'handle', direction: 'in', resourceCleanup: 'closeHandle' }], + returnType: 'u32', + }).invoke([W.resource(resource, 'closeHandle')]) + assert.equal(W.toNumber(result.returnValue), process.pid) + assert.equal(resource.closed, false) +} + +const mode = process.argv[2] +if (mode === 'resource' || mode === 'resource-control') { + const resource = openOwnProcess() + try { + checkResourceUsable(resource) + if (mode === 'resource') reject(() => Value.createVector([resource], Type.object())) + checkResourceUsable(resource) + } finally { + resource.close() + } + assert.equal(resource.closed, true) + report({ closes: 1 }) +} else if (mode === 'controls') { + const nil = Value.nullValue() + const vector = Value.createVector([nil], Type.object()) + assert.equal(vector.isNull(), false) + assert.equal(nil.isNull(), true) + vector.release() + assert.equal(root.DynWinRtValue, com.DynWinRtValue) + assert.equal(root.DynWinRtValue, win32.DynWinRtValue) + for (const foreign of [ + {}, + new root.DynWinRtMethodSig(), + root.WinGuid.parse('00000000-0000-0000-c000-000000000046'), + ]) { + reject(() => Value.createVector([foreign], Type.object())) + } + reject(() => Value.createVector([], nil), 'DynWinRTType') + nil.release() + report() +} else if (mode === 'identity') { + const foreign = new root.DynWinRtMethodSig() + const originalPrototype = Object.getPrototypeOf(foreign) + let userCalls = 0 + const unexpected = () => { + userCalls++ + throw new Error('Identity validation must not call user code') + } + const nil = Value.nullValue() + const constructor = Object.getOwnPropertyDescriptor(Value.prototype, 'constructor') + Object.defineProperty(nil, 'isNull', { value: unexpected }) + Object.defineProperty(Value.prototype, 'constructor', { get: unexpected, configurable: true }) + Object.defineProperty(Value, Symbol.hasInstance, { value: () => true, configurable: true }) + try { + for (const invalid of [ + Object.create(Value.prototype), + { constructor: Value, isNull: unexpected }, + Object.setPrototypeOf(foreign, Value.prototype), + ]) { + reject(() => Value.createVector([invalid], Type.object())) + } + const vector = Value.createVector([nil], Type.object()) + vector.release() + assert.equal(userCalls, 0) + } finally { + Object.setPrototypeOf(foreign, originalPrototype) + Object.defineProperty(Value.prototype, 'constructor', constructor) + delete Value[Symbol.hasInstance] + nil.release() + } + report({ userCalls }) +} else if (mode === 'collections') { + const resource = openOwnProcess() + const key = Value.hstring('key') + const value = Value.hstring('value') + const nil = Value.nullValue() + const stringType = Type.hstring() + const signature = new root.DynWinRtMethodSig() + try { + reject(() => Value.createVector([resource], Type.object())) + reject(() => Value.createMap([resource], [value], stringType, stringType)) + reject(() => Value.createMap([key], [resource], stringType, stringType)) + reject(() => Value.createVector([], signature), 'DynWinRTType') + reject(() => Value.createMap([], [], resource, stringType), 'DynWinRTType') + reject(() => Value.createMap([], [], stringType, nil), 'DynWinRTType') + reject(() => signature.addIn(resource), 'DynWinRTType') + reject(() => signature.addOut(nil), 'DynWinRTType') + reject(() => Type.structType('Tests.RejectedNativeClass', [stringType, resource]), 'DynWinRTType') + reject(() => Type.interface(resource), 'WinGUID') + const guid = root.WinGuid.parse('fbf417fe-7a96-4b54-9997-3da55c9cdf8d') + const iface = Type.registerInterface('Tests.NativeClassBoundary', guid) + reject(() => iface.addMethod('Rejected', resource), 'DynWinRTMethodSig') + iface.addMethod('Valid', signature.addOut(stringType)) + const map = Value.createMap([key], [value], stringType, stringType) + assert.equal(map.isNull(), false) + map.release() + const vector = Value.createVector([nil], Type.object()) + vector.release() + checkResourceUsable(resource) + } finally { + resource.close() + key.release() + value.release() + nil.release() + } + report({ closes: 1 }) +} else if (mode === 'accessors') { + const Variant = com.DynComVariant + const variant = Variant.i32(9) + const resource = openOwnProcess() + const nil = Value.nullValue() + try { + const vartype = Object.getOwnPropertyDescriptor(Variant.prototype, 'vartype').get + const kind = Object.getOwnPropertyDescriptor(Variant.prototype, 'kind').get + assert.equal(vartype.call(variant), 3) + assert.equal(variant.toNumber(), 9) + for (const foreign of [resource, nil, {}, Object.create(Variant.prototype)]) { + reject(() => vartype.call(foreign), 'DynComVariant') + reject(() => kind.call(foreign), 'DynComVariant') + } + reject(() => Variant.unknown(resource)) + const nullable = Variant.unknown(null) + assert.equal(nullable.vartype, 13) + nullable.release() + checkResourceUsable(resource) + } finally { + variant.release() + resource.close() + nil.release() + } + assert.throws(() => variant.vartype, /released/i) + report({ closes: 1 }) +} else if (mode === 'bridges') { + const resource = openOwnProcess() + const nil = Value.nullValue() + const variant = com.DynComVariant.i32(12) + const stored = com.DynCom.variant(variant) + try { + reject(() => root.unboxObject(resource)) + reject(() => com.DynCom.takeVariant(resource)) + reject(() => com.DynCom.takeBuffer(resource)) + reject(() => new com.DynComMethodSig().addIn(Type.i32()), 'DynComType') + reject(() => Value.createVector([variant], Type.object())) + assert.equal(root.unboxObject(nil), null) + const extracted = com.DynCom.takeVariant(stored) + assert.equal(extracted.toNumber(), 12) + extracted.release() + class Signature extends root.DynWinRtMethodSig {} + const signature = new Signature().addOut(Type.hstring()) + const iid = root.WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') + const type = Type.registerInterface('Windows.Foundation.IStringable', iid).addMethod('ToString', signature) + reject( + () => + root.DynWinRtInterfacePlan.create('Invalid', type, [{ name: 'ToString', vtableIndex: 6, signature: resource }]), + 'MethodSig', + ) + reject(() => root.DynWinRtDelegateMethod.create(iid, resource), 'MethodSig') + const plan = root.DynWinRtInterfacePlan.create('Windows.Foundation.IStringable', type, [ + { name: 'ToString', vtableIndex: 6, signature }, + ]) + let calls = 0 + let invalid = true + const owner = root.DynWinRtImplementation.create([plan], () => { + calls++ + return [invalid ? resource : Value.hstring('still usable')] + }) + const object = owner.toValue().cast(iid) + try { + assert.throws(() => type.method(6).getString(object)) + assert.match(owner.takeError(), /DynWinRtValue|class/i) + invalid = false + assert.equal(type.method(6).getString(object), 'still usable') + assert.equal(calls, 2) + } finally { + object.release() + owner.dispose() + owner.release() + } + checkResourceUsable(resource) + } finally { + resource.close() + nil.release() + stored.release() + variant.release() + } + report({ closes: 1 }) +} else if (mode === 'native-hooks') { + const native = require('../../dist/index.js') + const Probe = native.NativeClassTestProbe + assert.equal(typeof Probe, 'function', 'An explicitly built test-hooks addon is required') + assert.equal(typeof global.gc, 'function', '--expose-gc is required') + const calls = [ + (value) => Probe.read(value), + (value) => Probe.write(value), + (value) => Probe.alias(value), + (value) => Probe.instance(value), + (value) => Probe.reference(value), + (value) => native.nativeClassTestBridge(value), + ] + const start = native.nativeClassTestEntries() + const finalized = native.nativeClassTestFinalized() + ;(() => { + const controls = [native.nativeClassTestUntagged(), native.nativeClassTestOtherBuild()] + for (const value of controls) { + Object.setPrototypeOf(value, Value.prototype) + for (const call of calls) reject(() => call(value)) + } + })() + assert.equal(native.nativeClassTestEntries(), start, 'Rejected arguments entered a native body') + const nil = Value.nullValue() + for (const call of calls) call(nil) + assert.equal(native.nativeClassTestEntries(), start + calls.length) + const probe = new Probe() + probe.value = 17 + assert.equal(probe.value, 17) + const beforeAccessors = native.nativeClassTestEntries() + const descriptor = Object.getOwnPropertyDescriptor(Probe.prototype, 'value') + reject(() => descriptor.get.call(nil), 'NativeClassTestProbe') + reject(() => descriptor.set.call(nil, 1), 'NativeClassTestProbe') + assert.equal(native.nativeClassTestEntries(), beforeAccessors, 'Rejected receiver entered an accessor body') + nil.release() + assert.throws(() => native.nativeClassTestDuplicateTag(), /tag.*identity/i) + ;(async () => { + for (let attempt = 0; attempt < 20 && native.nativeClassTestFinalized() - finalized !== 3; attempt++) { + global.gc() + await new Promise(setImmediate) + } + assert.equal(native.nativeClassTestFinalized() - finalized, 3, 'Control payloads must each finalize once') + report({ finalized: 3, entriesForInvalidInputs: 0 }) + })().catch((error) => { + console.error(error) + process.exitCode = 1 + }) +} else if (mode === 'workers') { + Promise.all( + Array.from( + { length: 4 }, + () => + new Promise((resolve, rejectWorker) => { + const worker = new Worker(__filename, { argv: ['controls'] }) + let result + worker.on('message', (message) => { + result = message + }) + worker.on('error', rejectWorker) + worker.on('exit', (code) => { + if (code !== 0 || !result) rejectWorker(new Error(`Worker exited ${code} without its report`)) + else resolve(result) + }) + }), + ), + ) + .then((results) => { + for (const result of results) { + assert.equal(result.mode, 'controls') + rejected += result.rejected + } + const nil = Value.nullValue() + const vector = Value.createVector([nil], Type.object()) + vector.release() + nil.release() + report({ workers: results.length }) + }) + .catch((error) => { + console.error(error) + process.exitCode = 1 + }) +} else { + throw new Error(`Unknown native class boundary mode: ${mode}`) +} diff --git a/bindings/js/__test__/native-class-boundary-hooks.e2e.mjs b/bindings/js/__test__/native-class-boundary-hooks.e2e.mjs new file mode 100644 index 00000000..841cbaa1 --- /dev/null +++ b/bindings/js/__test__/native-class-boundary-hooks.e2e.mjs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' + +test('native class conversions reject old/foreign tags before bodies and finalize controls once', (t) => { + const fixture = fileURLToPath(new URL('./fixtures/native-class-boundary.cjs', import.meta.url)) + const child = spawnSync(process.execPath, ['--expose-gc', fixture, 'native-hooks'], { + encoding: 'utf8', + timeout: 30_000, + windowsHide: true, + }) + assert.equal(child.status, 0, `${child.error ?? ''}\n${child.stdout}\n${child.stderr}`) + const report = JSON.parse(child.stdout.trim()) + t.diagnostic(child.stdout.trim()) + assert.equal(report.rejected, 14) + assert.equal(report.entriesForInvalidInputs, 0) + assert.equal(report.finalized, 3) +}) diff --git a/bindings/js/__test__/native-class-boundary.e2e.mjs b/bindings/js/__test__/native-class-boundary.e2e.mjs new file mode 100644 index 00000000..55d992f6 --- /dev/null +++ b/bindings/js/__test__/native-class-boundary.e2e.mjs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' + +const fixture = fileURLToPath(new URL('./fixtures/native-class-boundary.cjs', import.meta.url)) +for (const mode of [ + 'resource-control', + 'resource', + 'controls', + 'identity', + 'collections', + 'accessors', + 'bridges', + 'workers', +]) { + test(`native class boundary: ${mode}`, (t) => { + const child = spawnSync(process.execPath, [fixture, mode], { + encoding: 'utf8', + timeout: 30_000, + windowsHide: true, + }) + assert.equal(child.status, 0, `${child.error ?? ''}\n${child.stdout}\n${child.stderr}`) + assert.equal(child.signal, null) + const report = JSON.parse(child.stdout.trim()) + t.diagnostic(child.stdout.trim()) + assert.equal(report.mode, mode) + if (mode !== 'resource-control') assert.ok(report.rejected > 0) + if (mode.startsWith('resource')) assert.equal(report.closes, 1) + if (mode === 'workers') assert.equal(report.workers, 4) + }) +} diff --git a/bindings/js/build.rs b/bindings/js/build.rs index 0d3c23ca..ef20f85a 100644 --- a/bindings/js/build.rs +++ b/bindings/js/build.rs @@ -1,4 +1,8 @@ +#[path = "build_support/native_branding.rs"] +mod native_branding; + fn main() { + native_branding::generate().expect("Unable to fingerprint the JavaScript native binding"); println!("cargo:rerun-if-changed=__test__/native/raw_union_oracle.c"); if std::env::var_os("CARGO_FEATURE_TEST_HOOKS").is_none() { return; diff --git a/bindings/js/build_support/native_branding.rs b/bindings/js/build_support/native_branding.rs new file mode 100644 index 00000000..85daf221 --- /dev/null +++ b/bindings/js/build_support/native_branding.rs @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{collections::BTreeMap, env, fs, io, path::Path, process::Command}; + +use sha2::{Digest, Sha256}; + +type Inputs = BTreeMap>; + +fn relative_name(root: &Path, path: &Path) -> io::Result { + let relative = path.strip_prefix(root).map_err(io::Error::other)?; + relative + .components() + .map(|component| { + component + .as_os_str() + .to_str() + .map(str::to_owned) + .ok_or_else(|| io::Error::other("Native source path is not valid Unicode")) + }) + .collect::>>() + .map(|components| components.join("/")) +} + +fn read_input(root: &Path, path: &Path, inputs: &mut Inputs) -> io::Result<()> { + println!("cargo:rerun-if-changed={}", path.display()); + inputs.insert(relative_name(root, path)?, fs::read(path)?); + Ok(()) +} + +fn read_tree(root: &Path, directory: &Path, inputs: &mut Inputs) -> io::Result<()> { + // Watching the directory also detects newly added/removed native source files. + println!("cargo:rerun-if-changed={}", directory.display()); + for entry in fs::read_dir(directory)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + read_tree(root, &entry.path(), inputs)?; + } else if kind.is_file() { + read_input(root, &entry.path(), inputs)?; + } else { + return Err(io::Error::other(format!( + "Native fingerprint inputs must be regular files/directories: {}", + entry.path().display() + ))); + } + } + Ok(()) +} + +fn fingerprint(inputs: &Inputs, configuration: &BTreeMap) -> String { + let mut digest = Sha256::new(); + for (kind, entries) in [ + ( + b"source".as_slice(), + inputs + .iter() + .map(|(name, value)| (name.as_str(), value.as_slice())) + .collect::>(), + ), + ( + b"configuration".as_slice(), + configuration + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())) + .collect::>(), + ), + ] { + for (name, value) in entries { + digest.update(kind); + digest.update((name.len() as u64).to_le_bytes()); + digest.update(name.as_bytes()); + digest.update((value.len() as u64).to_le_bytes()); + digest.update(value); + } + } + format!("{:x}", digest.finalize()) +} + +pub fn generate() -> io::Result<()> { + let manifest = env::var_os("CARGO_MANIFEST_DIR") + .ok_or_else(|| io::Error::other("CARGO_MANIFEST_DIR is required"))?; + let root = Path::new(&manifest).join("..").join("..").canonicalize()?; + let mut inputs = Inputs::new(); + for name in ["Cargo.toml", "Cargo.lock"] { + read_input(&root, &root.join(name), &mut inputs)?; + } + for components in [ + ["bindings", "js"], + ["crates", "dynwinrt"], + ["crates", "dynwinrt-com-contracts"], + ["crates", "dynwinrt-win32-contracts"], + ] { + let directory = root.join(components[0]).join(components[1]); + read_input(&root, &directory.join("Cargo.toml"), &mut inputs)?; + let build_script = directory.join("build.rs"); + if build_script.try_exists()? { + read_input(&root, &build_script, &mut inputs)?; + } + read_tree(&root, &directory.join("src"), &mut inputs)?; + } + let binding = root.join("bindings").join("js"); + read_tree(&root, &binding.join("build_support"), &mut inputs)?; + read_tree(&root, &binding.join("__test__").join("native"), &mut inputs)?; + + let mut configuration = BTreeMap::new(); + for (name, value) in env::vars() { + if name.starts_with("CARGO_CFG_") + || name.starts_with("CARGO_FEATURE_") + || [ + "TARGET", + "PROFILE", + "OPT_LEVEL", + "DEBUG", + "CARGO_ENCODED_RUSTFLAGS", + ] + .contains(&name.as_str()) + { + let root_name = root.to_string_lossy(); + let portable_root = root_name + .strip_prefix(r"\\?\") + .unwrap_or(root_name.as_ref()); + let value = value + .replace(root_name.as_ref(), "") + .replace(portable_root, "") + .replace(&portable_root.replace('\\', "/"), ""); + configuration.insert(name, value); + } + } + let rustc = env::var_os("RUSTC").ok_or_else(|| io::Error::other("RUSTC is required"))?; + let version = Command::new(rustc).arg("-vV").output()?; + if !version.status.success() { + return Err(io::Error::other(format!( + "rustc -vV failed: {}", + String::from_utf8_lossy(&version.stderr) + ))); + } + configuration.insert( + "rustc-version".into(), + String::from_utf8(version.stdout).map_err(io::Error::other)?, + ); + let salt = format!( + "microsoft.dynwinrt.native/{}", + fingerprint(&inputs, &configuration) + ); + let generated = format!( + "macro_rules! native_class {{ ($item:item) => {{ #[napi_derive::napi(type_tag = {salt:?})] $item }}; }}\n" + ); + let output = env::var_os("OUT_DIR").ok_or_else(|| io::Error::other("OUT_DIR is required"))?; + fs::write(Path::new(&output).join("native_class_tag.rs"), generated)?; + println!("cargo:rustc-env=DYNWINRT_NATIVE_CLASS_SALT={salt}"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct SourceTree(std::path::PathBuf); + + impl SourceTree { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + loop { + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = env::temp_dir().join(format!("dynwinrt-branding-{}-{id}", std::process::id())); + match fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("Unable to create native branding test tree: {error}"), + } + } + } + } + + impl Drop for SourceTree { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).expect("Remove the native branding test's own source tree"); + } + } + + #[test] + fn source_order_and_workspace_location_do_not_change_the_fingerprint() { + let first = Inputs::from([ + ("src/b.rs".into(), b"second".to_vec()), + ("src/a.rs".into(), b"first".to_vec()), + ]); + let second = Inputs::from([ + ("src/a.rs".into(), b"first".to_vec()), + ("src/b.rs".into(), b"second".to_vec()), + ]); + assert_eq!( + fingerprint(&first, &BTreeMap::new()), + fingerprint(&second, &BTreeMap::new()) + ); + assert_eq!( + relative_name(Path::new(r"C:\one"), Path::new(r"C:\one\src\a.rs")).unwrap(), + relative_name(Path::new(r"D:\two"), Path::new(r"D:\two\src\a.rs")).unwrap(), + ); + } + + #[test] + fn copied_source_trees_match_and_edits_or_new_files_invalidate_the_brand() { + let first = SourceTree::new(); + let second = SourceTree::new(); + let collect = |root: &Path| { + let mut inputs = Inputs::new(); + read_tree(root, &root.join("src"), &mut inputs).unwrap(); + fingerprint(&inputs, &BTreeMap::new()) + }; + for root in [&first.0, &second.0] { + fs::create_dir(root.join("src")).unwrap(); + fs::write(root.join("src").join("value.rs"), "struct Value(u32);").unwrap(); + } + let original = collect(&first.0); + assert_eq!(original, collect(&second.0)); + fs::write(second.0.join("src").join("value.rs"), "struct Value(u64);").unwrap(); + assert_ne!(original, collect(&second.0)); + fs::write(second.0.join("src").join("value.rs"), "struct Value(u32);").unwrap(); + fs::write(second.0.join("src").join("extra.rs"), "struct Extra;").unwrap(); + assert_ne!(original, collect(&second.0)); + } + + #[test] + fn source_dependency_target_feature_and_compiler_changes_change_the_fingerprint() { + let inputs = Inputs::from([("src/value.rs".into(), b"layout".to_vec())]); + let configuration = BTreeMap::from([ + ("TARGET".into(), "aarch64-pc-windows-msvc".into()), + ("rustc-version".into(), "rustc 1".into()), + ]); + let original = fingerprint(&inputs, &configuration); + for (name, value) in [ + ("src/value.rs", "new layout"), + ("Cargo.lock", "new dependency"), + ("src/new.rs", "new class"), + ] { + let mut changed = inputs.clone(); + changed.insert(name.into(), value.as_bytes().to_vec()); + assert_ne!(original, fingerprint(&changed, &configuration)); + } + for (name, value) in [ + ("TARGET", "x86_64-pc-windows-msvc"), + ("CARGO_FEATURE_TEST_HOOKS", "1"), + ("rustc-version", "rustc 2"), + ("CARGO_ENCODED_RUSTFLAGS", "-Zrandomize-layout"), + ] { + let mut changed = configuration.clone(); + changed.insert(name.into(), value.into()); + assert_ne!(original, fingerprint(&inputs, &changed)); + } + } +} diff --git a/bindings/js/package.json b/bindings/js/package.json index cd6afd75..f14d1ffc 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -108,7 +108,9 @@ "format:toml": "taplo format", "format:rs": "cargo fmt", "lint": "oxlint", - "test": "npm run test:types && ava", + "test": "npm run test:types && ava && npm run test:native-classes", + "test:native-classes": "node --test __test__/native-class-boundary.e2e.mjs", + "test:native-classes:hooks": "node --test __test__/native-class-boundary-hooks.e2e.mjs", "test:imports": "ava __test__/native-imports.spec.ts", "test:collection-factories": "node --test __test__/collection-factories.e2e.mjs", "test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts", diff --git a/bindings/js/src/benchmarks.rs b/bindings/js/src/benchmarks.rs index 1a5ee755..71ba3e36 100644 --- a/bindings/js/src/benchmarks.rs +++ b/bindings/js/src/benchmarks.rs @@ -4,22 +4,25 @@ use napi_derive::napi; use windows::core::HSTRING; -#[napi] -pub struct RustStaticBench; +native_class! { + pub struct RustStaticBench; +} fn map_win_err(e: windows::core::Error) -> napi::Error { napi::Error::from_reason(e.message()) } -/// Pre-created Uri for static benchmark (stores typed interface, no QI on access). -#[napi] -pub struct StaticUri(windows::Foundation::Uri); +native_class! { + /// Pre-created Uri for static benchmark (stores typed interface, no QI on access). + pub struct StaticUri(windows::Foundation::Uri); +} unsafe impl Send for StaticUri {} unsafe impl Sync for StaticUri {} -/// Pre-created opaque COM object for static benchmark (factory results). -#[napi] -pub struct StaticObj(#[allow(dead_code)] windows::core::IInspectable); +native_class! { + /// Pre-created opaque COM object for static benchmark (factory results). + pub struct StaticObj(#[allow(dead_code)] windows::core::IInspectable); +} unsafe impl Send for StaticObj {} unsafe impl Sync for StaticObj {} diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index bc73d6d4..7b69eaf7 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -136,18 +136,20 @@ fn callback_com_value( env: napi::sys::napi_env, value: napi::sys::napi_value, ) -> napi::Result { - let value = unsafe { <&DynWinRTValue>::from_napi_value(env, value) }?; - let value = value.to_com_value()?; - Ok(match value { - dynwinrt::com::Value::Buffer(buffer) => { - let count = buffer.count(); - dynwinrt::com::Value::Buffer(dynwinrt::com::ComBufferValue::from_owned_bytes( - buffer.copy_bytes().map_err(com_error)?, - count, - )) - } - value => value, - }) + unsafe { + crate::native_class_ref::with_ref::(env, value, |value| { + Ok(match value.to_com_value()? { + dynwinrt::com::Value::Buffer(buffer) => { + let count = buffer.count(); + dynwinrt::com::Value::Buffer(dynwinrt::com::ComBufferValue::from_owned_bytes( + buffer.copy_bytes().map_err(com_error)?, + count, + )) + } + value => value, + }) + }) + } } fn create_iunknown_sink( @@ -482,7 +484,16 @@ pub(super) fn pointer(value: Unknown) -> napi::Result { // here would make it indistinguishable from an owned raw pointer to // adoptComPointer(), which can double-release the original wrapper's COM // object. Callers that already have raw pointer bits should pass those bits. - if unsafe { <&DynWinRTValue>::from_napi_value(env, raw) }.is_ok() { + if unsafe { + napi::bindgen_prelude::validate_type_tag( + env, + raw, + &::type_tag(), + "DynWinRtValue", + ) + } + .is_ok() + { return Err(napi::Error::from_reason( "pointer(): DynWinRtValue inputs are not accepted; pass raw pointer bits, Buffer/Uint8Array, or null instead", )); @@ -1548,11 +1559,13 @@ fn safe_array_element_type_from_name( }) } -#[napi] -pub struct DynComType(pub(super) dynwinrt::com::Type); +native_class! { + pub struct DynComType(pub(super) dynwinrt::com::Type); +} -#[napi] -pub struct DynComMethodSig(dynwinrt::com::MethodSignature); +native_class! { + pub struct DynComMethodSig(dynwinrt::com::MethodSignature); +} #[napi] impl DynComMethodSig { @@ -1764,8 +1777,9 @@ impl DynComMethodSig { } } -#[napi] -pub struct DynComInterface(dynwinrt::com::Interface); +native_class! { + pub struct DynComInterface(dynwinrt::com::Interface); +} #[napi] impl DynComInterface { @@ -1811,8 +1825,9 @@ impl DynComInterface { } } -#[napi] -pub struct DynComUnsafeInterface(dynwinrt::com::Interface); +native_class! { + pub struct DynComUnsafeInterface(dynwinrt::com::Interface); +} #[napi] impl DynComUnsafeInterface { @@ -1843,21 +1858,24 @@ impl DynComUnsafeInterface { } } -#[napi] -pub struct DynComMethodHandle(dynwinrt::com::MethodHandle); +native_class! { + pub struct DynComMethodHandle(dynwinrt::com::MethodHandle); +} -#[napi] -pub struct DynComRawDispatchState { - entered: std::cell::Cell, +native_class! { + pub struct DynComRawDispatchState { + entered: std::cell::Cell, + } } -#[napi] -pub struct DynComDispatchInvokeResult { - hresult: i32, - result: Option, - excep_info: Option, - arg_err: Option, - finalization_error: Option, +native_class! { + pub struct DynComDispatchInvokeResult { + hresult: i32, + result: Option, + excep_info: Option, + arg_err: Option, + finalization_error: Option, + } } #[napi] @@ -2091,15 +2109,17 @@ impl DynComRaw { } } -#[napi] -pub struct DynCom; +native_class! { + pub struct DynCom; +} -/// Explicit opt-in surface for manually declared native COM ABI contracts. -/// -/// Supplying an invalid pointer, IID, vtable slot, direction, count relation, -/// or ownership contract can crash the process or corrupt memory. -#[napi] -pub struct DynComUnsafe; +native_class! { + /// Explicit opt-in surface for manually declared native COM ABI contracts. + /// + /// Supplying an invalid pointer, IID, vtable slot, direction, count relation, + /// or ownership contract can crash the process or corrupt memory. + pub struct DynComUnsafe; +} #[napi] impl DynComUnsafe { @@ -2247,16 +2267,18 @@ impl DynComUnsafe { } } -#[napi] -pub struct DynComNativeStruct { - descriptor: String, - bytes: Vec, +native_class! { + pub struct DynComNativeStruct { + descriptor: String, + bytes: Vec, + } } -#[napi] -pub struct DynComNativeStructArray { - descriptor: String, - bytes: Vec, +native_class! { + pub struct DynComNativeStructArray { + descriptor: String, + bytes: Vec, + } } #[napi] @@ -2272,10 +2294,11 @@ impl DynComNativeStructArray { } } -#[napi] -pub struct DynComNativeUnion { - descriptor: String, - value: dynwinrt::com::NativeUnionValue, +native_class! { + pub struct DynComNativeUnion { + descriptor: String, + value: dynwinrt::com::NativeUnionValue, + } } #[napi] @@ -2296,10 +2319,11 @@ impl DynComNativeUnion { } } -#[napi] -pub struct DynComVariant { - value: Option, - inputs: super::com_input::InputBindings, +native_class! { + pub struct DynComVariant { + value: Option, + inputs: super::com_input::InputBindings, + } } impl DynComVariant { @@ -2539,11 +2563,12 @@ impl DynComVariant { } } -#[napi] -pub struct DynComDispatchParams { - owner_thread: std::thread::ThreadId, - value: Option, - inputs: super::com_input::InputBindings, +native_class! { + pub struct DynComDispatchParams { + owner_thread: std::thread::ThreadId, + value: Option, + inputs: super::com_input::InputBindings, + } } impl DynComDispatchParams { @@ -2648,10 +2673,11 @@ impl DynComDispatchParams { } } -#[napi] -pub struct DynComExcepInfo { - owner_thread: std::thread::ThreadId, - value: Option, +native_class! { + pub struct DynComExcepInfo { + owner_thread: std::thread::ThreadId, + value: Option, + } } impl DynComExcepInfo { @@ -2737,15 +2763,17 @@ impl DynComExcepInfo { } } -#[napi] -pub struct DynComStatStg { - owner_thread: std::thread::ThreadId, - value: Option, +native_class! { + pub struct DynComStatStg { + owner_thread: std::thread::ThreadId, + value: Option, + } } -#[napi] -pub struct DynComFormatEtc { - value: dynwinrt::com::FormatEtcValue, +native_class! { + pub struct DynComFormatEtc { + value: dynwinrt::com::FormatEtcValue, + } } #[napi] @@ -2788,9 +2816,10 @@ impl DynComFormatEtc { } } -#[napi] -pub struct DynComStgMedium { - value: dynwinrt::com::StgMediumValue, +native_class! { + pub struct DynComStgMedium { + value: dynwinrt::com::StgMediumValue, + } } #[napi] @@ -2813,9 +2842,10 @@ impl DynComStgMedium { } } -#[napi] -pub struct DynComAudioFormat { - value: dynwinrt::com::AudioFormatValue, +native_class! { + pub struct DynComAudioFormat { + value: dynwinrt::com::AudioFormatValue, + } } #[napi] @@ -2910,11 +2940,12 @@ impl DynComAudioFormat { } } -#[napi] -#[derive(Debug)] -pub struct DynComOwnedHandle { - address: Option, - cleanup: dynwinrt::com::OwnedHandleCleanup, +native_class! { + #[derive(Debug)] + pub struct DynComOwnedHandle { + address: Option, + cleanup: dynwinrt::com::OwnedHandleCleanup, + } } #[cfg(test)] @@ -3090,11 +3121,12 @@ impl DynComStatStg { } } -#[napi] -pub struct DynComAllocation { - owner_thread: std::thread::ThreadId, - allocator: Option, - pointer: usize, +native_class! { + pub struct DynComAllocation { + owner_thread: std::thread::ThreadId, + allocator: Option, + pointer: usize, + } } impl DynComAllocation { @@ -3328,10 +3360,11 @@ pub struct DynComSafeArrayBound { pub length: f64, } -#[napi] -pub struct DynComSafeArray { - value: Option, - inputs: super::com_input::InputBindings, +native_class! { + pub struct DynComSafeArray { + value: Option, + inputs: super::com_input::InputBindings, + } } impl DynComSafeArray { @@ -3792,9 +3825,10 @@ impl DynComSafeArray { } } -#[napi] -pub struct DynComPropVariant { - value: Option, +native_class! { + pub struct DynComPropVariant { + value: Option, + } } impl DynComPropVariant { diff --git a/bindings/js/src/com_borrowed.rs b/bindings/js/src/com_borrowed.rs index 21d10c22..220b8316 100644 --- a/bindings/js/src/com_borrowed.rs +++ b/bindings/js/src/com_borrowed.rs @@ -52,8 +52,9 @@ fn parse_contract(value: &str) -> napi::Result { BorrowedCopyContract::parse(value).map_err(invalid) } -#[napi] -pub struct DynComBorrowedCopyPlan(BorrowedCopyPlan); +native_class! { + pub struct DynComBorrowedCopyPlan(BorrowedCopyPlan); +} #[napi(object)] pub struct DynComCapturePacketCopy { @@ -84,10 +85,11 @@ impl DynComBorrowedCopyPlan { } #[cfg(feature = "test-hooks")] -#[napi] -pub struct DynComBorrowedCopyTestFixture { - fixture: dynwinrt::com::borrowed::testing::CopyFixture, - owner: std::thread::ThreadId, +native_class! { + pub struct DynComBorrowedCopyTestFixture { + fixture: dynwinrt::com::borrowed::testing::CopyFixture, + owner: std::thread::ThreadId, + } } #[cfg(feature = "test-hooks")] diff --git a/bindings/js/src/com_completion.rs b/bindings/js/src/com_completion.rs index 0a18aba5..68db3aa2 100644 --- a/bindings/js/src/com_completion.rs +++ b/bindings/js/src/com_completion.rs @@ -16,7 +16,7 @@ use dynwinrt::com::completion::{ OwnerOperation, ResultArgument, StartArgument, }; use napi::{ - bindgen_prelude::{FromNapiValue, PromiseRaw, ToNapiValue}, + bindgen_prelude::{PromiseRaw, ToNapiValue}, sys, Env, JsError, Status, }; use napi_derive::napi; @@ -314,12 +314,13 @@ fn dispatch(token: u64, env: sys::napi_env) -> napi::Result<()> { DynWinRTValue::to_napi_value(env, DynWinRTValue::new(dynwinrt::WinRTValue::Null)) } .map_err(|error| CompletionError::contract("projection", error.to_string()))?; - let wrapped = unsafe { <&mut DynWinRTValue>::from_napi_value(env, value) } - .map_err(|error| CompletionError::contract("projection", error.to_string()))?; - *wrapped.winrt_mut() = dynwinrt::WinRTValue::Object(object); - wrapped - .bind_current_com_apartment() - .map_err(|error| CompletionError::contract("projection", error.to_string()))?; + unsafe { + crate::native_class_ref::with_mut::(env, value, |wrapped| { + *wrapped.winrt_mut() = dynwinrt::WinRTValue::Object(object); + wrapped.bind_current_com_apartment() + }) + } + .map_err(|error| CompletionError::contract("projection", error.to_string()))?; Ok(value) }); match result { @@ -400,8 +401,9 @@ pub(crate) fn start_with_plan<'env>( Ok(PromiseRaw::new(env.raw(), promise)) } -#[napi] -pub struct DynComAsync; +native_class! { + pub struct DynComAsync; +} #[napi] impl DynComAsync { diff --git a/bindings/js/src/com_raw.rs b/bindings/js/src/com_raw.rs index 2a69c9c4..42db8a49 100644 --- a/bindings/js/src/com_raw.rs +++ b/bindings/js/src/com_raw.rs @@ -547,8 +547,9 @@ fn managed_from_owned_com_value(value: IUnknown) -> napi::Result Ok(value) } -#[napi] -pub struct DynComRaw; +native_class! { + pub struct DynComRaw; +} #[napi] impl DynComRaw { @@ -576,8 +577,9 @@ impl DynComRaw { } } -#[napi] -pub struct DynComRawCleanup; +native_class! { + pub struct DynComRawCleanup; +} #[napi] impl DynComRawCleanup { @@ -756,9 +758,10 @@ impl DynComRawCleanup { } } -#[napi] -pub struct DynComRawOwnedComPointer { - state: Arc, +native_class! { + pub struct DynComRawOwnedComPointer { + state: Arc, + } } impl Drop for DynComRawOwnedComPointer { @@ -892,10 +895,11 @@ impl DynComRawOwnedComPointer { } } -#[napi] -pub struct DynComRawStructLayout { - descriptor: String, - layout: Arc, +native_class! { + pub struct DynComRawStructLayout { + descriptor: String, + layout: Arc, + } } #[napi] @@ -986,10 +990,11 @@ impl DynComRawStructLayout { } } -#[napi] -pub struct DynComRawUnionLayout { - descriptor: String, - layout: Arc, +native_class! { + pub struct DynComRawUnionLayout { + descriptor: String, + layout: Arc, + } } #[napi] @@ -1105,9 +1110,10 @@ impl DynComRawUnionLayout { } } -#[napi] -pub struct DynComRawMemory { - allocation: Arc, +native_class! { + pub struct DynComRawMemory { + allocation: Arc, + } } #[napi] @@ -1479,9 +1485,10 @@ impl DynComRawMemory { } } -#[napi] -pub struct DynComRawPointer { - kind: RawPointerKind, +native_class! { + pub struct DynComRawPointer { + kind: RawPointerKind, + } } impl DynComRawPointer { diff --git a/bindings/js/src/js_boundary_tests.rs b/bindings/js/src/js_boundary_tests.rs index 0e2bcba8..e21ac7a8 100644 --- a/bindings/js/src/js_boundary_tests.rs +++ b/bindings/js/src/js_boundary_tests.rs @@ -5,6 +5,33 @@ use crate::value::ensure_progress_type_supported; use super::*; +#[test] +fn native_class_tags_include_the_build_brand_and_actual_rust_class() { + use napi::bindgen_prelude::{type_tag_from_ident, TypeTag}; + + let value = DynWinRTValue::type_tag(); + assert_eq!( + value, + type_tag_from_ident(concat!( + env!("DYNWINRT_NATIVE_CLASS_SALT"), + "::jswinrt_rs::value::DynWinRTValue" + )) + ); + for other in [ + DynWinRTType::type_tag(), + DynWinRTMethodSig::type_tag(), + WinGUID::type_tag(), + DynComType::type_tag(), + DynComVariant::type_tag(), + ] { + assert_ne!(value, other); + } + assert_ne!( + value, + type_tag_from_ident("other-build::jswinrt_rs::value::DynWinRTValue") + ); +} + #[test] fn hresult_arrays_use_the_i32_projection() { let array = DynWinRTArray::new(dynwinrt::ArrayData::from_values( diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 6cfc50aa..4fa9fc92 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -4,6 +4,8 @@ #![deny(clippy::all)] #![allow(clippy::missing_safety_doc)] +include!(concat!(env!("OUT_DIR"), "\\native_class_tag.rs")); + mod com; pub use com::{ initialize_com, DynCom, DynComDispatchInvokeResult, DynComDispatchParams, DynComExcepInfo, @@ -49,6 +51,9 @@ mod initialization; pub use initialization::{get_winappsdk_resource_pri_path, init_winappsdk, ro_initialize}; pub(crate) use initialization::{set_winui_dispatcher_loop_active, winui_dispatcher_loop_exited}; mod js_numbers; +mod native_class_ref; +#[cfg(feature = "test-hooks")] +mod native_class_test_hooks; mod property_value; pub use property_value::unbox_object; mod winrt_types; diff --git a/bindings/js/src/native_class_ref.rs b/bindings/js/src/native_class_ref.rs new file mode 100644 index 00000000..d96b8cb1 --- /dev/null +++ b/bindings/js/src/native_class_ref.rs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use napi::{ + bindgen_prelude::{FromNapiMutRef, FromNapiRef}, + sys, +}; + +/// Keep checked native references inside the synchronous bridge. The +/// higher-ranked closure cannot return a borrow of the native payload. +pub(crate) unsafe fn with_ref( + env: sys::napi_env, + value: sys::napi_value, + operation: impl for<'a> FnOnce(&'a T) -> napi::Result, +) -> napi::Result { + let value = unsafe { T::from_napi_ref(env, value) }?; + operation(value) +} + +pub(crate) unsafe fn with_mut( + env: sys::napi_env, + value: sys::napi_value, + operation: impl for<'a> FnOnce(&'a mut T) -> napi::Result, +) -> napi::Result { + let value = unsafe { T::from_napi_mut_ref(env, value) }?; + operation(value) +} diff --git a/bindings/js/src/native_class_test_hooks.rs b/bindings/js/src/native_class_test_hooks.rs new file mode 100644 index 00000000..aa9a08c2 --- /dev/null +++ b/bindings/js/src/native_class_test_hooks.rs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ + ffi::c_void, + ptr, + sync::atomic::{AtomicU32, Ordering}, +}; + +use napi::{ + bindgen_prelude::{ClassInstance, FromNapiValue, Reference, Unknown}, + sys, Env, JsValue, +}; +use napi_derive::napi; + +use crate::DynWinRTValue; + +static ENTERED: AtomicU32 = AtomicU32::new(0); +static FINALIZED: AtomicU32 = AtomicU32::new(0); + +type ValueAlias = &'static DynWinRTValue; + +fn entered() -> u32 { + ENTERED.fetch_add(1, Ordering::SeqCst) + 1 +} + +native_class! { + pub struct NativeClassTestProbe { + value: u32, + } +} + +#[napi] +impl NativeClassTestProbe { + #[napi(constructor)] + pub fn new() -> Self { + Self { value: 0 } + } + + #[napi(getter)] + pub fn value(&self) -> u32 { + entered(); + self.value + } + + #[napi(setter)] + pub fn set_value(&mut self, value: u32) { + entered(); + self.value = value; + } + + #[napi] + pub fn read(_value: &DynWinRTValue) -> u32 { + entered() + } + + #[napi] + pub fn write(_value: &mut DynWinRTValue) -> u32 { + entered() + } + + #[napi] + pub fn alias(#[napi(ts_arg_type = "DynWinRtValue")] _value: ValueAlias) -> u32 { + entered() + } + + #[napi] + pub fn instance(_value: ClassInstance<'_, DynWinRTValue>) -> u32 { + entered() + } + + #[napi] + pub fn reference(_value: Reference) -> u32 { + entered() + } +} + +#[napi] +pub fn native_class_test_bridge(value: Unknown<'_>) -> napi::Result { + unsafe { + crate::native_class_ref::with_ref::(value.value().env, value.raw(), |_| { + Ok(entered()) + }) + } +} + +#[napi] +pub fn native_class_test_entries() -> u32 { + ENTERED.load(Ordering::SeqCst) +} + +#[napi] +pub fn native_class_test_finalized() -> u32 { + FINALIZED.load(Ordering::SeqCst) +} + +unsafe extern "C" fn finalize(_: sys::napi_env, data: *mut c_void, _: *mut c_void) { + drop(unsafe { Box::from_raw(data.cast::()) }); + FINALIZED.fetch_add(1, Ordering::SeqCst); +} + +fn control_value<'env>(env: Env, brand: u32) -> napi::Result> { + let mut object = ptr::null_mut(); + napi::check_status!(unsafe { sys::napi_create_object(env.raw(), &mut object) })?; + let mut value = Box::new(DynWinRTValue::new(dynwinrt::WinRTValue::Null)); + napi::check_status!(unsafe { + sys::napi_wrap( + env.raw(), + object, + (&mut *value as *mut DynWinRTValue).cast(), + Some(finalize), + ptr::null_mut(), + ptr::null_mut(), + ) + })?; + let _ = Box::into_raw(value); + if brand != 0 { + let tag = napi::bindgen_prelude::type_tag_from_ident( + "dynwinrt-native-class-control/other-build::jswinrt_rs::value::DynWinRTValue", + ); + unsafe { napi::bindgen_prelude::tag_object(env.raw(), object, &tag) }?; + if brand == 2 { + // The payload is still the same valid Rust type. Only the immutable + // identity differs; the installed finalizer owns it on tagging failure. + unsafe { napi::bindgen_prelude::tag_object(env.raw(), object, &tag) }?; + } + } + unsafe { Unknown::from_napi_value(env.raw(), object) } +} + +#[napi] +pub fn native_class_test_untagged<'env>(env: Env) -> napi::Result> { + control_value(env, 0) +} + +#[napi] +pub fn native_class_test_other_build<'env>(env: Env) -> napi::Result> { + control_value(env, 1) +} + +#[napi] +pub fn native_class_test_duplicate_tag<'env>(env: Env) -> napi::Result> { + control_value(env, 2) +} diff --git a/bindings/js/src/property_value.rs b/bindings/js/src/property_value.rs index fb371423..86457739 100644 --- a/bindings/js/src/property_value.rs +++ b/bindings/js/src/property_value.rs @@ -120,14 +120,19 @@ pub fn unbox_object<'env>(env: Env, value: Unknown<'env>) -> napi::Result::from_napi_value(env.raw(), napi::JsValue::raw(&value)) - }?; - match dynwinrt::unbox_property_value(raw.winrt()) - .map_err(|error| napi::Error::from_reason(error.message()))? - { - dynwinrt::PropertyValueUnboxResult::Null => null_unknown(env), - dynwinrt::PropertyValueUnboxResult::NotPropertyValue => Ok(value), - dynwinrt::PropertyValueUnboxResult::Value(value) => property_value_to_javascript(env, value), + unsafe { + crate::native_class_ref::with_ref::( + env.raw(), + napi::JsValue::raw(&value), + |raw| match dynwinrt::unbox_property_value(raw.winrt()) + .map_err(|error| napi::Error::from_reason(error.message()))? + { + dynwinrt::PropertyValueUnboxResult::Null => null_unknown(env), + dynwinrt::PropertyValueUnboxResult::NotPropertyValue => Ok(value), + dynwinrt::PropertyValueUnboxResult::Value(value) => { + property_value_to_javascript(env, value) + } + }, + ) } } diff --git a/bindings/js/src/value.rs b/bindings/js/src/value.rs index 5a8b4e1f..eccdc4a6 100644 --- a/bindings/js/src/value.rs +++ b/bindings/js/src/value.rs @@ -55,11 +55,12 @@ pub(crate) fn ensure_progress_type_supported( } } -#[napi] -pub struct DynWinRTValue { - winrt: dynwinrt::WinRTValue, - storage: Option, - com: com_value::ComValueState, +native_class! { + pub struct DynWinRTValue { + winrt: dynwinrt::WinRTValue, + storage: Option, + com: com_value::ComValueState, + } } // Unbound WinRT bookkeeping is thread-safe. Once COM ownership is established, // owner checks protect apartment-local Rc state; foreign destruction leaks only diff --git a/bindings/js/src/win32.rs b/bindings/js/src/win32.rs index 84395945..ed93b5cc 100644 --- a/bindings/js/src/win32.rs +++ b/bindings/js/src/win32.rs @@ -480,8 +480,9 @@ impl DynWin32CallResult { } } -#[napi] -pub struct DynWin32; +native_class! { + pub struct DynWin32; +} #[napi] impl DynWin32 { @@ -651,17 +652,18 @@ impl DynWin32 { "Win32 handles and structs are not managed COM references", )); } - let value = boundary::managed_com_value(&value)?; - let iid = WinGUID( - windows::core::GUID::try_from(iid.as_str()) - .map_err(|_| napi::Error::from_reason("Invalid COM interface IID"))?, - ); - let owner = com::with_win32_input_leases(&[value], |validate_inputs| { - let owner = com::try_cast(value, &iid)?.ok_or_else(|| { - napi::Error::from_reason("Managed object does not implement the required Win32 interface") - })?; - validate_inputs()?; - Ok(owner) + let owner = boundary::with_managed_com_value(&value, |value| { + let iid = WinGUID( + windows::core::GUID::try_from(iid.as_str()) + .map_err(|_| napi::Error::from_reason("Invalid COM interface IID"))?, + ); + com::with_win32_input_leases(&[value], |validate_inputs| { + let owner = com::try_cast(value, &iid)?.ok_or_else(|| { + napi::Error::from_reason("Managed object does not implement the required Win32 interface") + })?; + validate_inputs()?; + Ok(owner) + }) })?; let pointer = owner .winrt() @@ -1836,8 +1838,9 @@ fn native_ffi_field_type(typ: &serde_json::Value) -> napi::Result<(libffi::middl }) } -#[napi] -pub struct DynWin32Unsafe; +native_class! { + pub struct DynWin32Unsafe; +} #[napi] impl DynWin32Unsafe { diff --git a/bindings/js/src/win32_boundary.rs b/bindings/js/src/win32_boundary.rs index ad67b02c..d8580374 100644 --- a/bindings/js/src/win32_boundary.rs +++ b/bindings/js/src/win32_boundary.rs @@ -2,12 +2,12 @@ // Licensed under the MIT License. //! Every opaque Win32 carrier checks a native type tag before typed unwrapping. -//! napi-rs class casts only test JavaScript prototypes, which are mutable. +//! These opaque carriers retain their own tags, separate from napi-rs classes. -use std::{cell::RefCell, collections::HashMap, ffi::c_void, ptr, sync::OnceLock}; +use std::{ffi::c_void, ptr, sync::OnceLock}; use napi::{ - bindgen_prelude::{BigInt, Buffer, FromNapiValue, Function, Unknown}, + bindgen_prelude::{BigInt, Buffer, Function, Unknown}, sys, Env, JsValue, }; use napi_derive::napi; @@ -17,85 +17,32 @@ use super::{ DynWin32Resource, DynWin32SubsystemContext, DynWin32Value, DynWinRTValue, }; -thread_local! { - static COM_RECEIVER_GUARDS: RefCell>> = RefCell::new(HashMap::new()); -} - -#[napi(module_exports, skip_typescript)] -fn capture_com_receiver_guard(env: Env) -> napi::Result<()> { - let constructor = napi::bindgen_prelude::get_class_constructor("DynWinRtValue\0") - .ok_or_else(|| napi::Error::from_reason("Managed COM carrier constructor is unavailable"))?; - let mut class = ptr::null_mut(); - napi::check_status!(unsafe { - sys::napi_get_reference_value(env.raw(), constructor, &mut class) - })?; - let mut prototype = ptr::null_mut(); - let mut method = ptr::null_mut(); - napi::check_status!(unsafe { - sys::napi_get_named_property(env.raw(), class, c"prototype".as_ptr(), &mut prototype) - })?; - napi::check_status!(unsafe { - sys::napi_get_named_property(env.raw(), prototype, c"isNull".as_ptr(), &mut method) - })?; - let mut reference = ptr::null_mut(); - napi::check_status!(unsafe { sys::napi_create_reference(env.raw(), method, 1, &mut reference) })?; - let key = env.raw() as usize; - let result = (|| { - if COM_RECEIVER_GUARDS.with(|guards| !guards.borrow().contains_key(&key)) { - let _hook = env.add_env_cleanup_hook(key, |key| { - if let Some(references) = - COM_RECEIVER_GUARDS.with(|guards| guards.borrow_mut().remove(&key)) - { - for reference in references { - let _ = unsafe { sys::napi_delete_reference(key as sys::napi_env, reference) }; - } - } - })?; - } - COM_RECEIVER_GUARDS.with(|guards| { - let mut guards = guards.borrow_mut(); - let references = guards.entry(key).or_default(); - references - .try_reserve_exact(1) - .map_err(|_| napi::Error::from_reason("Unable to retain native COM carrier validation"))?; - references.push(reference); - Ok(()) - }) - })(); - if result.is_err() { - let _ = unsafe { sys::napi_delete_reference(env.raw(), reference) }; +pub(super) fn with_managed_com_value( + value: &Unknown, + operation: impl for<'a> FnOnce(&'a DynWinRTValue) -> napi::Result, +) -> napi::Result { + unsafe { + napi::bindgen_prelude::validate_type_tag( + value.value().env, + value.raw(), + &::type_tag(), + "DynWinRtValue", + ) } - result -} - -pub(super) fn managed_com_value<'a>(value: &'a Unknown) -> napi::Result<&'a DynWinRTValue> { - let env = value.value().env; - let raw = value.raw(); - // Node's original napi_define_class method enforces its native receiver - // signature. Unlike instanceof, this rejects another wrapped Rust type even - // after prototype spoofing. Retain the method before exports are published so - // replacing the public prototype cannot replace this validation. - let references = COM_RECEIVER_GUARDS - .with(|guards| guards.borrow().get(&(env as usize)).cloned()) - .ok_or_else(|| napi::Error::from_reason("Native COM carrier validation is unavailable"))?; - for reference in references { - let mut method = ptr::null_mut(); - let mut result = ptr::null_mut(); - napi::check_status!(unsafe { sys::napi_get_reference_value(env, reference, &mut method) })?; - let status = unsafe { sys::napi_call_function(env, raw, method, 0, ptr::null(), &mut result) }; - if status == sys::Status::napi_pending_exception { - let mut exception = ptr::null_mut(); - napi::check_status!(unsafe { sys::napi_get_and_clear_last_exception(env, &mut exception) })?; - continue; + .map_err(|error| { + if error.status == napi::Status::InvalidArg { + napi::Error::new( + error.status, + format!( + "DynWin32.comObject(): expected a native managed COM carrier: {}", + error.reason + ), + ) + } else { + error } - napi::check_status!(status)?; - let mut is_null = false; - napi::check_status!(unsafe { sys::napi_get_value_bool(env, result, &mut is_null) })?; - return unsafe { <&DynWinRTValue>::from_napi_value(env, raw) }; - } - Err(napi::Error::from_reason( - "DynWin32.comObject(): expected a native managed COM carrier", - )) + })?; + unsafe { crate::native_class_ref::with_ref(value.value().env, value.raw(), operation) } } #[repr(C)] diff --git a/bindings/js/src/winrt_array.rs b/bindings/js/src/winrt_array.rs index 6fed7091..f157b0ed 100644 --- a/bindings/js/src/winrt_array.rs +++ b/bindings/js/src/winrt_array.rs @@ -41,11 +41,12 @@ where .collect() } -#[napi] -pub struct DynWinRTArray( - pub(crate) dynwinrt::ArrayData, - pub(crate) Option, -); +native_class! { + pub struct DynWinRTArray( + pub(crate) dynwinrt::ArrayData, + pub(crate) Option, + ); +} impl DynWinRTArray { pub(crate) fn new(data: dynwinrt::ArrayData) -> Self { diff --git a/bindings/js/src/winrt_delegate.rs b/bindings/js/src/winrt_delegate.rs index 96e2b1e9..fa3db7c4 100644 --- a/bindings/js/src/winrt_delegate.rs +++ b/bindings/js/src/winrt_delegate.rs @@ -5,8 +5,9 @@ use crate::{direct_callback::*, managed_tsfn, DynWinRTType, DynWinRTValue, WinGU use napi_derive::napi; use std::sync::Arc; -#[napi] -pub struct DynWinRtDelegate(pub(crate) dynwinrt::WinRTValue); +native_class! { + pub struct DynWinRtDelegate(pub(crate) dynwinrt::WinRTValue); +} #[napi] impl DynWinRtDelegate { diff --git a/bindings/js/src/winrt_delegate_method.rs b/bindings/js/src/winrt_delegate_method.rs index 88f1438a..102e974a 100644 --- a/bindings/js/src/winrt_delegate_method.rs +++ b/bindings/js/src/winrt_delegate_method.rs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use napi::{ - bindgen_prelude::{FromNapiValue, Unknown}, - JsValue, -}; +use napi::{bindgen_prelude::Unknown, JsValue}; use napi_derive::napi; use windows::core::{IInspectable, IUnknown, Interface, GUID}; @@ -13,14 +10,15 @@ use crate::{winrt_implementation::require_instance, DynWinRTMethodSig, DynWinRTV type DelegateCall = dyn Fn(&IUnknown, &[dynwinrt::WinRTValue]) -> windows::core::Result>; -/// A prepared caller for a metadata-described WinRT delegate's Invoke method. -/// Delegates derive from IUnknown, so Invoke is slot 3, not IInspectable slot 6. -/// Supply the full delegate signature and its concrete IID (including generic -/// type arguments). This does not register an interface or use the COM planner. -#[napi] -pub struct DynWinRtDelegateMethod { - iid: GUID, - call: Box, +native_class! { + /// A prepared caller for a metadata-described WinRT delegate's Invoke method. + /// Delegates derive from IUnknown, so Invoke is slot 3, not IInspectable slot 6. + /// Supply the full delegate signature and its concrete IID (including generic + /// type arguments). This does not register an interface or use the COM planner. + pub struct DynWinRtDelegateMethod { + iid: GUID, + call: Box, + } } fn clone_arguments(args: Vec>) -> napi::Result> { @@ -28,11 +26,13 @@ fn clone_arguments(args: Vec>) -> napi::Result(&value, "DynWinRtValue")?; - Ok( - unsafe { <&DynWinRTValue>::from_napi_value(value.value().env, value.raw()) }? - .winrt() - .clone(), - ) + unsafe { + crate::native_class_ref::with_ref::( + value.value().env, + value.raw(), + |value| Ok(value.winrt().clone()), + ) + } }) .collect() } @@ -83,7 +83,9 @@ impl DynWinRtDelegateMethod { ) -> napi::Result { require_instance::(&iid, "WinGuid")?; require_instance::(&signature, "DynWinRtMethodSig")?; - let iid = unsafe { <&WinGUID>::from_napi_value(iid.value().env, iid.raw()) }?.0; + let iid = unsafe { + crate::native_class_ref::with_ref::(iid.value().env, iid.raw(), |iid| Ok(iid.0)) + }?; if [ GUID::zeroed(), IUnknown::IID, @@ -99,9 +101,14 @@ impl DynWinRtDelegateMethod { "A WinRT delegate caller requires a delegate IID, not an infrastructure IID", )); } - let signature = - unsafe { <&DynWinRTMethodSig>::from_napi_value(signature.value().env, signature.raw()) }?; - let method = signature.0.clone().build(3); + let signature = unsafe { + crate::native_class_ref::with_ref::( + signature.value().env, + signature.raw(), + |signature| Ok(signature.0.clone()), + ) + }?; + let method = signature.build(3); Ok(Self { iid, // Keep the native facade's unnameable prepared Method type opaque. @@ -121,9 +128,16 @@ impl DynWinRtDelegateMethod { #[napi(ts_arg_type = "DynWinRtValue[]")] args: Vec>, ) -> napi::Result> { require_instance::(&value, "DynWinRtValue")?; - let value = unsafe { <&DynWinRTValue>::from_napi_value(value.value().env, value.raw()) }?; - value.ensure_existing_com_apartment()?; - let target = value.winrt().clone(); + let target = unsafe { + crate::native_class_ref::with_ref::( + value.value().env, + value.raw(), + |value| { + value.ensure_existing_com_apartment()?; + Ok(value.winrt().clone()) + }, + ) + }?; let args = clone_arguments(args)?; self.invoke_native(target, &args) } diff --git a/bindings/js/src/winrt_element_factory.rs b/bindings/js/src/winrt_element_factory.rs index 6a0d21e2..e15c128a 100644 --- a/bindings/js/src/winrt_element_factory.rs +++ b/bindings/js/src/winrt_element_factory.rs @@ -14,10 +14,11 @@ struct ElementFactoryCallbackRefs { recycle_element: Option>>, } -#[napi] -pub struct DynWinRtElementFactory { - value: dynwinrt::WinRTValue, - callbacks: Arc>, +native_class! { + pub struct DynWinRtElementFactory { + value: dynwinrt::WinRTValue, + callbacks: Arc>, + } } unsafe fn take_pending_exception_message(env: napi::sys::napi_env) -> Option { @@ -69,7 +70,7 @@ impl DynWinRtElementFactory { #[napi(ts_arg_type = "(args: DynWinRtValue) => void")] recycle_element: ElementFactoryRecycleFunction, ) -> napi::Result { - use napi::bindgen_prelude::{FromNapiValue, ToNapiValue}; + use napi::bindgen_prelude::ToNapiValue; use napi::JsValue; use windows::Win32::System::Threading::GetCurrentThreadId; @@ -141,10 +142,12 @@ impl DynWinRtElementFactory { "IElementFactory getElement callback failed: {detail}" ))); } - <&DynWinRTValue>::from_napi_value(raw_env, raw_result)? - .winrt() - .cast(&element_iid) - .map_err(|error| napi::Error::from_reason(error.message())) + crate::native_class_ref::with_ref::(raw_env, raw_result, |value| { + value + .winrt() + .cast(&element_iid) + .map_err(|error| napi::Error::from_reason(error.message())) + }) })(); let call_result = call_result.map_err(|error| match take_pending_exception_message(raw_env) { diff --git a/bindings/js/src/winrt_implementation.rs b/bindings/js/src/winrt_implementation.rs index e71d15e2..8634e48a 100644 --- a/bindings/js/src/winrt_implementation.rs +++ b/bindings/js/src/winrt_implementation.rs @@ -17,7 +17,7 @@ use dynwinrt::{ WinRtMethodDefinition, WinRtThreadingPolicy, }; use napi::{ - bindgen_prelude::{FromNapiValue, Function, JavaScriptClassExt, ToNapiValue, Unknown}, + bindgen_prelude::{FromNapiValue, Function, ToNapiValue, TypeTag, Unknown}, sys, Env, JsValue, }; use napi_derive::napi; @@ -95,18 +95,9 @@ fn binding_error(error: windows::core::Error) -> napi::Error { napi::Error::from_reason(error.message()) } -pub(crate) fn require_instance( - value: &Unknown<'_>, - name: &str, -) -> napi::Result<()> { - // JavaScriptClassExt uses the registered JS name (DynWinRt*). napi-rs's - // ValidateNapiValue derives instead look up the legacy Rust DynWinRT* name. - if T::instance_of(&Env::from_raw(value.value().env), value)? { - Ok(()) - } else { - Err(napi::Error::from_reason(format!( - "Expected a {name} instance" - ))) +pub(crate) fn require_instance(value: &Unknown<'_>, name: &str) -> napi::Result<()> { + unsafe { + napi::bindgen_prelude::validate_type_tag(value.value().env, value.raw(), &T::type_tag(), name) } } @@ -119,10 +110,11 @@ pub struct DynWinRtImplementationMethod<'env> { pub signature: Unknown<'env>, } -/// A standalone WinRT interface descriptor. Creation never registers a COM class -/// or changes the outbound WinRT method registry. -#[napi] -pub struct DynWinRtInterfacePlan(WinRtInterfaceDefinition); +native_class! { + /// A standalone WinRT interface descriptor. Creation never registers a COM class + /// or changes the outbound WinRT method registry. + pub struct DynWinRtInterfacePlan(WinRtInterfaceDefinition); +} #[napi] impl DynWinRtInterfacePlan { @@ -135,7 +127,11 @@ impl DynWinRtInterfacePlan { ) -> napi::Result { require_instance::(&interface_type, "DynWinRtType")?; let interface_type = unsafe { - <&DynWinRTType>::from_napi_value(interface_type.value().env, interface_type.raw()) + crate::native_class_ref::with_ref::( + interface_type.value().env, + interface_type.raw(), + |typ| Ok(typ.type_handle()), + ) }?; let methods = methods .into_iter() @@ -143,11 +139,15 @@ impl DynWinRtInterfacePlan { let env = method.signature.value().env; let raw = method.signature.raw(); require_instance::(&method.signature, "DynWinRtMethodSig")?; - let signature = unsafe { <&DynWinRTMethodSig>::from_napi_value(env, raw) }?; + let signature = unsafe { + crate::native_class_ref::with_ref::(env, raw, |signature| { + Ok(signature.0.clone()) + }) + }?; Ok(WinRtMethodDefinition { name: method.name, vtable_index: crate::js_numbers::js_u32(method.vtable_index, "vtableIndex")? as usize, - signature: signature.0.clone(), + signature, }) }) .collect::>>()?; @@ -158,12 +158,12 @@ impl DynWinRtInterfacePlan { let env = iid.value().env; let raw = iid.raw(); require_instance::(&iid, "WinGuid")?; - Ok(unsafe { <&WinGUID>::from_napi_value(env, raw) }?.0) + unsafe { crate::native_class_ref::with_ref::(env, raw, |iid| Ok(iid.0)) } }) .collect::>>()?; let definition = WinRtInterfaceDefinition { name, - interface_type: interface_type.type_handle(), + interface_type, required_iids, methods, }; @@ -172,15 +172,16 @@ impl DynWinRtInterfacePlan { } } -/// Owns one reference to a synchronous, non-agile WinRT implementation. -/// -/// release()/GC drops this owner's reference only. Native references keep the -/// callback alive. dispose() disconnects every view and breaks callback cycles. -/// Call dispose() explicitly when a handler captures its owner or a native view; -/// those cross-runtime cycles are not visible to JavaScript's garbage collector. -#[napi] -pub struct DynWinRtImplementation { - state: Rc, +native_class! { + /// Owns one reference to a synchronous, non-agile WinRT implementation. + /// + /// release()/GC drops this owner's reference only. Native references keep the + /// callback alive. dispose() disconnects every view and breaks callback cycles. + /// Call dispose() explicitly when a handler captures its owner or a native view; + /// those cross-runtime cycles are not visible to JavaScript's garbage collector. + pub struct DynWinRtImplementation { + state: Rc, + } } impl Drop for DynWinRtImplementation { @@ -206,11 +207,11 @@ impl DynWinRtImplementation { .map(|interface| { let raw = interface.raw(); require_instance::(&interface, "DynWinRtInterfacePlan")?; - Ok( - unsafe { <&DynWinRtInterfacePlan>::from_napi_value(env.raw(), raw) }? - .0 - .clone(), - ) + unsafe { + crate::native_class_ref::with_ref::(env.raw(), raw, |plan| { + Ok(plan.0.clone()) + }) + } }) .collect::>>()?; let plan = WinRtImplementationPlan::new(definitions, WinRtThreadingPolicy::OwnerThread) @@ -402,11 +403,11 @@ fn parse_outputs(env: sys::napi_env, result: sys::napi_value) -> napi::Result::from_napi_value(env, raw) }? - .winrt() - .clone(), - ); + outputs.push(unsafe { + crate::native_class_ref::with_ref::(env, raw, |value| { + Ok(value.winrt().clone()) + }) + }?); } Ok(outputs) } diff --git a/bindings/js/src/winrt_methods.rs b/bindings/js/src/winrt_methods.rs index d37d96c9..13573a8b 100644 --- a/bindings/js/src/winrt_methods.rs +++ b/bindings/js/src/winrt_methods.rs @@ -6,8 +6,9 @@ use napi::{bindgen_prelude::PromiseRaw, Env}; use napi_derive::napi; use windows::core::{Interface, HSTRING}; -#[napi] -pub struct DynWinRTMethodSig(pub(crate) dynwinrt::MethodSignature); +native_class! { + pub struct DynWinRTMethodSig(pub(crate) dynwinrt::MethodSignature); +} unsafe impl Send for DynWinRTMethodSig {} unsafe impl Sync for DynWinRTMethodSig {} @@ -41,8 +42,9 @@ impl DynWinRTMethodSig { // MethodHandle binding // ====================================================================== -#[napi] -pub struct DynWinRTMethodHandle(pub(crate) dynwinrt::MethodHandle); +native_class! { + pub struct DynWinRTMethodHandle(pub(crate) dynwinrt::MethodHandle); +} unsafe impl Send for DynWinRTMethodHandle {} unsafe impl Sync for DynWinRTMethodHandle {} diff --git a/bindings/js/src/winrt_struct.rs b/bindings/js/src/winrt_struct.rs index 1ce98cc3..1b0f2fb3 100644 --- a/bindings/js/src/winrt_struct.rs +++ b/bindings/js/src/winrt_struct.rs @@ -7,11 +7,12 @@ use napi_derive::napi; use std::mem; use windows::core::HSTRING; -#[napi] -pub struct DynWinRTStruct( - pub(crate) dynwinrt::ValueTypeData, - pub(crate) Vec>, -); +native_class! { + pub struct DynWinRTStruct( + pub(crate) dynwinrt::ValueTypeData, + pub(crate) Vec>, + ); +} unsafe impl Send for DynWinRTStruct {} unsafe impl Sync for DynWinRTStruct {} diff --git a/bindings/js/src/winrt_types.rs b/bindings/js/src/winrt_types.rs index 6cfab567..e11232b0 100644 --- a/bindings/js/src/winrt_types.rs +++ b/bindings/js/src/winrt_types.rs @@ -9,8 +9,9 @@ use std::sync::Arc; pub(crate) static TABLE: std::sync::LazyLock> = std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new()); -#[napi] -pub struct DynWinRTType(pub(crate) dynwinrt::TypeHandle); +native_class! { + pub struct DynWinRTType(pub(crate) dynwinrt::TypeHandle); +} impl DynWinRTType { pub(crate) fn type_handle(&self) -> dynwinrt::TypeHandle { @@ -228,9 +229,10 @@ impl DynWinRTType { } } -#[napi] -#[derive(Debug, Clone, Copy)] -pub struct WinGUID(pub(crate) windows::core::GUID); +native_class! { + #[derive(Debug, Clone, Copy)] + pub struct WinGUID(pub(crate) windows::core::GUID); +} #[napi] impl WinGUID { diff --git a/docs/architecture/javascript-binding-internals.md b/docs/architecture/javascript-binding-internals.md index 0ea1498f..98b4ca99 100644 --- a/docs/architecture/javascript-binding-internals.md +++ b/docs/architecture/javascript-binding-internals.md @@ -5,6 +5,72 @@ Classic COM facades and flat Win32 facades remain separate public APIs. `bindings/js/src/lib.rs` only declares modules and re-exports their existing registrations; it does not interpret native contracts. +## Native class identity + +The binding pins `napi` 3.12.0 and `napi-derive` 3.6.1 (backend 6.1.0) +and explicitly enables `napi8`. This is required for the upstream native +class type-tag checks; enabling only `napi7` leaves those checks inactive. +Node.js 18 already supports N-API 8. Building this binding requires Rust 1.88 +or later. The guarantee applies to the shipped Windows native addons, not +the upstream WebAssembly fallback. + +napi-rs stamps the actual Rust class's tag in constructors, factories and +`ToNapiValue`/instance publication. Ref, mutable-ref, `ClassInstance`, +`Reference`, method-receiver and accessor-receiver conversions check that tag +before a typed Rust cast/reference/dereference. Some upstream paths first +retrieve an opaque pointer with `napi_unwrap`; that does not interpret the +Rust payload. Nested `Vec`/`Option` inputs and handwritten `FromNapiValue` +bridges use the same generated class conversions. + +Handwritten bridges use `native_class_ref::with_ref` / `with_mut` for the +upstream tag-checked conversion and synchronous use. The higher-ranked closure +cannot return a reference to the payload; metadata/value copies and independent +COM owners are returned instead. + +This paired release contains the complete native type-tag fix from +[napi-rs/napi-rs#3405](https://github.com/napi-rs/napi-rs/pull/3405). +The backend is pinned explicitly because its otherwise-compatible version +range also admits later borrow-tracking code. That separate policy change +rejects existing reentrant delegate release/`once` behavior and needs its own +compatibility work. This change does not claim to solve general Rust aliasing +or addon-unload safety. + +These checks must not be replaced with constructor names, JavaScript +`instanceof`, or calls to public methods. In particular, a Node receiver +signature describes a JavaScript template, not every possible Rust payload +publication path. `winrt_implementation::require_instance` uses the native +tag for its explicit descriptor and callback-output checks. + +`native_class!` only adds the upstream `type_tag` attribute to a class +declaration. It does not wrap methods or implement argument conversion. +`build_support/native_branding.rs` computes its salt from sorted, relative native +source paths and bytes, the binding/core/contract manifests, the lockfile, +target/configuration/features, and `rustc -vV`. Cargo watches the files and +directories so additions and edits invalidate the salt. The upstream +derivation still includes each Rust module and class name: classes never +share a single build-wide tag. Object-shaped metadata records are not native +classes and do not use this macro. + +The salt is a conservative native-build compatibility boundary, not a +cross-library Rust ABI guarantee. Different source, dependencies, compiler, +target or feature configuration must not reinterpret one another's objects, +even when package versions coincide. The current npm release pipeline sets +JavaScript package versions after the native build; the Python preparation +helper updates the Python/codegen Cargo manifests, not this binding. +All facades of one published runtime still share the same native addon and +class identities. Existing Win32 carriers retain their separate, module-local +N-API tags and finalizers; they are not stamped again as napi-rs classes. +Identity validation does not replace COM apartments, released-state checks, +resource cleanup contracts or core WinRT value validation. + +Run `npm run test:native-classes` against a production addon for bounded +child-process collection, descriptor, accessor, callback and worker checks. +The owned process resource must remain usable after rejection and close once. +After an explicit `test-hooks` build, `npm run test:native-classes:hooks` +also checks mutable/owned/aliased references, setters, and layout-identical +untagged or differently branded controls. Counters verify rejected inputs +never enter native bodies, and controlled payloads finalize once. + ## JavaScript storage `js_storage.rs` owns behavior-neutral backing-store primitives: