diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8149093c..7386681f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -358,6 +358,9 @@ jobs: - name: Test metadata-driven COM borrowed copies working-directory: bindings/js run: npm run test:borrowed-copy + - name: Test Win32 failed-cleanup recovery + working-directory: bindings/js + run: node --expose-gc __test__\fixtures\win32-cleanup-errors.cjs # dynwinrt-codegen (x64 + arm64) dynwinrt-codegen: diff --git a/README.md b/README.md index d4f196be..e6b90a40 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # dynwinrt -**An experimental runtime for calling Windows APIs from JavaScript, TypeScript, or Python — without writing a native extension.** +**Call Windows Runtime (WinRT) APIs from JavaScript, TypeScript, or Python — without writing a native extension.** [![@microsoft/dynwinrt](https://img.shields.io/npm/v/@microsoft/dynwinrt.svg?label=%40microsoft%2Fdynwinrt)](https://www.npmjs.com/package/@microsoft/dynwinrt) [![@microsoft/dynwinrt-codegen](https://img.shields.io/npm/v/@microsoft/dynwinrt-codegen.svg?label=%40microsoft%2Fdynwinrt-codegen)](https://www.npmjs.com/package/@microsoft/dynwinrt-codegen) @@ -8,17 +8,6 @@ [![dynwinrt-codegen on PyPI](https://img.shields.io/pypi/v/dynwinrt-codegen.svg?label=PyPI%20dynwinrt-codegen)](https://pypi.org/project/dynwinrt-codegen/) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) -> **Status: experimental.** `dynwinrt` is under active development and intended -> for evaluation and prototyping. Public APIs, generated bindings, and -> runtime/codegen contracts may change between releases; backward compatibility -> is not yet guaranteed. Do not treat it as a stable production dependency. -> Use matching runtime and codegen versions, regenerate bindings when upgrading, -> and validate the APIs you rely on in your target environment. -> -> WinRT projections are available for JavaScript/TypeScript and Python. -> Classic COM and flat Win32 projections currently support JavaScript/TypeScript -> only, with the capability boundaries described below. - ## Why dynwinrt? If you've ever tried to call a modern Windows API (WinAppSDK, Windows AI, notifications, file pickers, sensors, …) from an Electron, Node, or Python app, you've probably hit one of these walls: @@ -31,8 +20,7 @@ If you've ever tried to call a modern Windows API (WinAppSDK, Windows AI, notifi > **Scope** — `dynwinrt` primarily targets **data-style WinRT APIs**. WinUI > `Application + Window` hosting is also supported on a caller-managed STA UI -> thread. Classic COM and contract-driven flat Win32 have separate -> JavaScript/TypeScript surfaces described below. +> thread. Classic COM has a separate preview surface described below. ## Quick start @@ -219,21 +207,6 @@ contracts or provide a universal overload parser. See the - [Classic COM JavaScript usage guide](docs/guides/windows/classic-com-usage.md) - [Supported ABI, coverage, limitations, and ownership model](docs/architecture/classic-com-support.md) -## Contract-driven flat Win32 - -Generate JavaScript bindings with TypeScript declarations for Win32 DLL exports -from `Windows.Win32.winmd`. Supported features include native structures, -counted buffers, managed resource cleanup, and IOCP-backed asynchronous file I/O. -Explicit subsystem contexts load their lifecycle DLLs on demand. - -An independent `contracts/win32` registry describes ownership, buffer -relationships, and lifecycle rules. Generated bindings use the separate -`@microsoft/dynwinrt/win32` entrypoint, preserving the existing COM and WinRT -semantic models. -See the [supported capabilities and contract boundary](docs/architecture/flat-win32-contracts.md), -[generation command](tools/dynwinrt-codegen/README.md#contract-driven-flat-win32), -and [JavaScript examples](samples/js/win32/README.md). - ## Repository layout ``` diff --git a/bindings/js/README.md b/bindings/js/README.md index 5d25143f..bb95a461 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -226,6 +226,31 @@ adding an eager dependency to ordinary WinRT/COM imports. MAPI utility initialization is available only on the unsafe subpath and requires a configured provider. +When a failed call cannot close an owned result, both Win32 entrypoints throw +`DynWin32CallError`, an `Error` with the original invocation message. +Its read-only `cleanupFailures` array contains each native `target`, the original +cleanup `error` (`code`, a signed HRESULT, and `message`), and a managed +`DynWin32Resource`. Keep the error or a resource alias until cleanup succeeds. +After correcting the native condition, call `error.retryCleanup()` or close the +individual resources. Retry does not invoke the original function again. +Failed retries retain the owners; successful retries and `close()` are +idempotent, and the original records remain available with `resource.closed` +set to `true`. Aliases share that close state. + +If projecting a recoverable error or its records fails, the runtime attempts +to create an `AggregateError` retaining the native error in `cause` and +`errors[0]`, alongside the projection failure in `errors[1]`. +It also exposes `cleanupFailures` and `retryCleanup()` +for recovery without discarding the native owner. Recovery property descriptors +have no prototype, so inherited descriptor fields cannot break decoration. +If constructing or decorating that aggregate also fails, the original native +error is rethrown unchanged. It can remain unprojected or non-extensible and +need not satisfy `instanceof DynWin32CallError`; use +`DynWin32CallError.getCleanupFailures(error)` and +`DynWin32CallError.retryCleanup(error)` to recover without modifying its +prototype. These static methods validate the native carrier, not `instanceof`. +Errors without cleanup failures retain their existing behavior. + See the [Win32 generation guide](../../tools/dynwinrt-codegen/README.md#contract-driven-flat-win32), [JavaScript samples](../../samples/js/win32/README.md), and [supported capabilities and ownership rules](../../docs/architecture/flat-win32-contracts.md). diff --git a/bindings/js/__test__/fixtures/win32-cleanup-errors.cjs b/bindings/js/__test__/fixtures/win32-cleanup-errors.cjs new file mode 100644 index 00000000..dd4f0db3 --- /dev/null +++ b/bindings/js/__test__/fixtures/win32-cleanup-errors.cjs @@ -0,0 +1,424 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const assert = require('node:assert/strict') +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const { runInNewContext } = require('node:vm') +const native = require('../../dist/index.js') + +if (typeof native.win32TestCleanupFailure !== 'function') { + throw new Error('Win32 cleanup recovery requires the test-hooks addon') +} + +main().catch((error) => { + console.error(error) + process.exitCode = 1 +}) + +async function main() { + const { DynWin32, DynWin32CallError, DynWin32Function, DynWin32Resource } = require('../../dist/win32-unsafe.js') + assert.equal(typeof global.gc, 'function') + const setInformation = DynWin32Function.bind({ + dll: 'kernel32.dll', + entryPoint: 'SetHandleInformation', + parameters: [ + { type: 'handle', direction: 'in', resourceCleanup: 'closeHandle' }, + { type: 'u32', direction: 'in' }, + { type: 'u32', direction: 'in' }, + ], + returnType: 'bool32', + successRule: 'nonzero', + captureLastError: true, + }) + const getInformation = DynWin32Function.bind({ + dll: 'kernel32.dll', + entryPoint: 'GetHandleInformation', + parameters: [ + { type: 'handle', direction: 'in', resourceCleanup: 'closeHandle' }, + { type: 'u32', direction: 'out' }, + ], + returnType: 'bool32', + successRule: 'nonzero', + captureLastError: true, + }) + const fn = DynWin32Function.bind({ + dll: 'kernel32.dll', + entryPoint: 'GetLastError', + parameters: [], + returnType: 'u32', + }) + const unprotect = (resource) => { + const result = setInformation.invoke([DynWin32.handle(resource), DynWin32.u32(2), DynWin32.u32(0)]) + assert.equal(result.succeeded, true, `SetHandleInformation: ${result.lastError}`) + } + const inspect = (resource) => getInformation.invoke([DynWin32.handle(resource)]) + const capture = (call) => { + try { + call() + } catch (error) { + return error + } + throw new Error('Expected a native cleanup failure') + } + const resourceOf = (error) => native.win32CallErrorCleanupFailures(error)[0].resource + const retire = (error, resource) => { + if (!native.win32ResourceClosed(resource)) { + unprotect(resource) + native.win32CallErrorRetryCleanup(error) + } + } + const throughFacade = (error, subsystem, functionView = fn) => { + const name = subsystem ? 'win32InvokeWithSubsystem' : 'win32Invoke' + const original = native[name] + // The real test-only ABI supplies the failure; only facade routing is replaced. + native[name] = () => { + throw error + } + try { + return capture(() => + subsystem ? functionView.invokeWithSubsystem(subsystem, 'winsock', []) : functionView.invoke([]), + ) + } finally { + native[name] = original + } + } + + const originalToString = Object.getOwnPropertyDescriptor(Error.prototype, 'toString') + const originalCause = Object.getOwnPropertyDescriptor(Error.prototype, 'cause') + let coercions = 0 + let raw + try { + Object.defineProperty(Error.prototype, 'toString', { + configurable: true, + value() { + coercions++ + throw new Error('Unexpected Error.toString during transport') + }, + }) + Object.defineProperty(Error.prototype, 'cause', { + configurable: true, + get() { + coercions++ + throw new Error('Unexpected Error.cause during transport') + }, + }) + raw = capture(() => native.win32TestCleanupFailure()) + } finally { + Object.defineProperty(Error.prototype, 'toString', originalToString) + if (originalCause) Object.defineProperty(Error.prototype, 'cause', originalCause) + else delete Error.prototype.cause + } + const retained = resourceOf(raw) + try { + assert.equal(coercions, 0) + assert.ok(raw instanceof Error) + assert.equal(native.win32CarrierKind(raw), 8) + const nativeMessage = raw.message + const error = throughFacade(raw) + assert.equal(error, raw) + assert.ok(error instanceof Error) + assert.ok(error instanceof DynWin32CallError) + assert.equal(error.name, 'DynWin32CallError') + assert.equal(error.message, nativeMessage) + const records = error.cleanupFailures + assert.equal(records.length, 1) + assert.equal(error.cleanupFailures, records) + const record = records[0] + const resource = record.resource + assert.deepEqual(record.target, { kind: 'return' }) + assert.equal(record.error.code >>> 0, 0x80070006) + assert.equal(error.message, `DynWin32Function test!cleanupFailure: 0x80070006: ${record.error.message}`) + assert.ok(resource instanceof DynWin32Resource) + assert.equal(typeof resource.value, 'bigint') + assert.ok(resource.value > 0n) + assert.equal(resource.closed, false) + for (const value of [records, record, record.target, record.error]) assert.ok(Object.isFrozen(value)) + assert.equal(Reflect.set(error, 'cleanupFailures', []), false) + assert.equal(Reflect.set(record, 'resource', {}), false) + assert.equal(Reflect.set(record.target, 'kind', 'parameter'), false) + assert.equal(Reflect.set(record.error, 'message', 'replacement'), false) + + const alias = DynWin32.toResource(DynWin32.handle(resource)) + assert.ok(alias instanceof DynWin32Resource) + assert.equal(alias.value, resource.value) + assert.throws(() => error.retryCleanup()) + assert.throws(() => resource.close()) + assert.equal(error.cleanupFailures, records) + assert.equal(error.cleanupFailures[0].resource, resource) + assert.equal(resource.closed, false) + assert.equal(alias.closed, false) + const receiverMessage = Object.getOwnPropertyDescriptor(error, 'message').get + assert.throws(() => receiverMessage.call(DynWin32.u32(1)), /native DynWin32CallError/) + Object.setPrototypeOf(error, DynWin32Resource.prototype) + assert.throws(() => DynWin32Resource.prototype.close.call(error), /native DynWin32Resource/) + assert.throws(() => DynWin32.resource(error, 'closeHandle'), /native DynWin32Resource/) + Object.setPrototypeOf(error, DynWin32CallError.prototype) + + const handle = resource.value + unprotect(resource) + error.retryCleanup() + assert.equal(resource.closed, true) + assert.equal(alias.closed, true) + assert.equal(native.win32ResourceClosed(retained), true) + assert.equal(error.cleanupFailures, records) + assert.equal(error.cleanupFailures[0].error, record.error) + assert.equal(inspect(handle).succeeded, false) + assert.doesNotThrow(() => error.retryCleanup()) + assert.doesNotThrow(() => resource.close()) + assert.doesNotThrow(() => alias.close()) + } finally { + retire(raw, retained) + } + + const context = DynWin32.initializeWinsock() + const subsystemError = capture(() => native.win32TestCleanupFailure()) + const subsystemResource = resourceOf(subsystemError) + try { + assert.equal(throughFacade(subsystemError, context), subsystemError) + assert.ok(subsystemError instanceof DynWin32CallError) + const resource = subsystemError.cleanupFailures[0].resource + const alias = DynWin32.toResource(DynWin32.handle(resource)) + unprotect(resource) + alias.close() + assert.equal(resource.closed, true) + assert.doesNotThrow(() => subsystemError.retryCleanup()) + } finally { + retire(subsystemError, subsystemResource) + context.close() + } + + const unprojectable = capture(() => native.win32TestCleanupFailure()) + const unprojectableResource = resourceOf(unprojectable) + try { + Object.preventExtensions(unprojectable) + const aggregate = throughFacade(unprojectable) + assert.ok(aggregate instanceof AggregateError) + assert.equal(aggregate.cause, unprojectable) + assert.equal(aggregate.errors[0], unprojectable) + assert.ok(aggregate.errors[1] instanceof TypeError) + const resource = aggregate.cleanupFailures[0].resource + assert.ok(resource instanceof DynWin32Resource) + assert.throws(() => aggregate.retryCleanup()) + assert.equal(resource.closed, false) + unprotect(resource) + aggregate.retryCleanup() + assert.equal(resource.closed, true) + assert.doesNotThrow(() => aggregate.retryCleanup()) + } finally { + retire(unprojectable, unprojectableResource) + } + + const pollutedError = capture(() => native.win32TestCleanupFailure()) + const pollutedResource = resourceOf(pollutedError) + try { + Object.preventExtensions(pollutedError) + const previousGet = Object.getOwnPropertyDescriptor(Object.prototype, 'get') + let received + try { + Object.defineProperty(Object.prototype, 'get', { + __proto__: null, + value: undefined, + configurable: true, + }) + received = throughFacade(pollutedError) + } finally { + Reflect.deleteProperty(Object.prototype, 'get') + if (previousGet) Object.defineProperty(Object.prototype, 'get', { __proto__: null, ...previousGet }) + } + assert.ok(received instanceof AggregateError) + assert.equal(received.cause, pollutedError) + assert.equal(received.errors[0], pollutedError) + const resource = received.cleanupFailures[0].resource + assert.throws(() => received.retryCleanup()) + unprotect(resource) + received.retryCleanup() + assert.equal(resource.closed, true) + } finally { + retire(pollutedError, pollutedResource) + } + + const facadeSource = readFileSync(join(__dirname, '..', '..', 'dist', 'win32-internal.js'), 'utf8') + for (const stage of ['construct', 'decorate']) { + const wrappingFailure = new Error(`Injected ${stage} failure`) + const overrides = + stage === 'construct' + ? { + AggregateError: function () { + throw wrappingFailure + }, + } + : { + Object: new Proxy(Object, { + get(target, name) { + if (name === 'defineProperties') + return () => { + throw wrappingFailure + } + return Reflect.get(target, name) + }, + }), + } + const module = { exports: {} } + runInNewContext(facadeSource, { + module, + require(name) { + assert.equal(name, './index.js') + return native + }, + Error, + TypeError, + AggregateError, + ...overrides, + }) + const Recovery = module.exports.DynWin32CallError + const functionView = module.exports.DynWin32Function.bind({ + dll: 'kernel32.dll', + entryPoint: 'GetLastError', + parameters: [], + returnType: 'u32', + }) + for (const mode of ['invoke', 'records']) { + const state = (() => { + const original = capture(() => native.win32TestCleanupFailure()) + const handle = native.win32ResourceValue(resourceOf(original)) + if (mode === 'invoke') Object.preventExtensions(original) + let received = throughFacade(original, undefined, functionView) + if (mode === 'records') { + const read = native.win32CallErrorCleanupFailures + try { + native.win32CallErrorCleanupFailures = (error) => { + const records = read(error) + Object.preventExtensions(records[0].resource) + return records + } + received = capture(() => received.cleanupFailures) + } finally { + native.win32CallErrorCleanupFailures = read + } + } + return { received, carrier: new WeakRef(original), handle } + })() + try { + assert.equal(native.win32CarrierKind(state.received), 8, `${stage}/${mode} lost its native error`) + assert.equal(state.received, state.carrier.deref()) + for (let iteration = 0; iteration < 3; iteration++) { + await new Promise((resolve) => setImmediate(resolve)) + global.gc() + await new Promise((resolve) => setImmediate(resolve)) + } + assert.equal(state.carrier.deref(), state.received, 'Keeping the thrown value must retain the native carrier') + assert.equal(inspect(state.handle).succeeded, true) + assert.throws(() => Recovery.retryCleanup(state.received)) + const resource = Recovery.getCleanupFailures(state.received)[0].resource + assert.equal(resource.value, state.handle) + unprotect(resource) + Recovery.retryCleanup(state.received) + Recovery.retryCleanup(state.received) + assert.equal(resource.closed, true) + assert.equal(inspect(state.handle).succeeded, false) + } finally { + const original = state.carrier.deref() + if (original) retire(original, resourceOf(original)) + } + } + } + + const recordError = capture(() => native.win32TestCleanupFailure()) + const recordResource = resourceOf(recordError) + const readRecords = native.win32CallErrorCleanupFailures + try { + assert.equal(throughFacade(recordError), recordError) + native.win32CallErrorCleanupFailures = (error) => { + const records = readRecords(error) + Object.preventExtensions(records[0].resource) + return records + } + const aggregate = capture(() => recordError.cleanupFailures) + assert.ok(aggregate instanceof AggregateError) + assert.equal(aggregate.cause, recordError) + assert.equal(aggregate.errors[0], recordError) + assert.ok(aggregate.errors[1] instanceof TypeError) + unprotect(recordResource) + aggregate.retryCleanup() + assert.equal(native.win32ResourceClosed(recordResource), true) + native.win32CallErrorCleanupFailures = readRecords + assert.equal(aggregate.cleanupFailures[0].resource.closed, true) + } finally { + native.win32CallErrorCleanupFailures = readRecords + retire(recordError, recordResource) + } + + async function collectUntil(condition, description) { + const deadline = Date.now() + 5000 + do { + await new Promise((resolve) => setImmediate(resolve)) + global.gc() + await new Promise((resolve) => setImmediate(resolve)) + if (condition()) return + } while (Date.now() < deadline) + throw new Error(`GC did not retire ${description}`) + } + + const errorOnly = capture(() => native.win32TestCleanupFailure()) + const errorOnlyState = (() => { + const resource = resourceOf(errorOnly) + return { handle: native.win32ResourceValue(resource), weak: new WeakRef(resource) } + })() + try { + await collectUntil(() => errorOnlyState.weak.deref() === undefined, 'the unretained resource projection') + assert.equal(inspect(errorOnlyState.handle).succeeded, true) + unprotect(errorOnlyState.handle) + global.gc() + assert.equal(inspect(errorOnlyState.handle).succeeded, true, 'The native CallError alone retains ownership') + native.win32CallErrorRetryCleanup(errorOnly) + assert.equal(inspect(errorOnlyState.handle).succeeded, false) + } finally { + retire(errorOnly, resourceOf(errorOnly)) + } + + const aliasOnly = (() => { + const error = throughFacade(capture(() => native.win32TestCleanupFailure())) + return { weak: new WeakRef(error), resource: error.cleanupFailures[0].resource } + })() + try { + await collectUntil(() => aliasOnly.weak.deref() === undefined, 'the error while an alias remains') + assert.equal(aliasOnly.resource.closed, false) + const handle = aliasOnly.resource.value + unprotect(aliasOnly.resource) + aliasOnly.resource.close() + assert.equal(aliasOnly.resource.closed, true) + assert.equal(inspect(handle).succeeded, false) + } finally { + if (!aliasOnly.resource.closed) { + unprotect(aliasOnly.resource) + aliasOnly.resource.close() + } + } + + const finalizerOnly = (() => { + const error = capture(() => native.win32TestCleanupFailure()) + const resource = resourceOf(error) + const handle = native.win32ResourceValue(resource) + unprotect(resource) + return { handle, error: new WeakRef(error), resource: new WeakRef(resource) } + })() + try { + await collectUntil( + () => + finalizerOnly.error.deref() === undefined && + finalizerOnly.resource.deref() === undefined && + !inspect(finalizerOnly.handle).succeeded, + 'the finalizer-backed cleanup owner', + ) + assert.equal(inspect(finalizerOnly.handle).lastError, 6) + } finally { + const error = finalizerOnly.error.deref() + if (error) native.win32CallErrorRetryCleanup(error) + const resource = finalizerOnly.resource.deref() + if (resource) native.win32ResourceClose(resource) + } + console.log('PASS Win32 cleanup error native recovery and lifetime') +} diff --git a/bindings/js/__test__/fixtures/win32-cleanup-facade.cjs b/bindings/js/__test__/fixtures/win32-cleanup-facade.cjs new file mode 100644 index 00000000..4ec218c5 --- /dev/null +++ b/bindings/js/__test__/fixtures/win32-cleanup-facade.cjs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const assert = require('node:assert/strict') +const { readFileSync } = require('node:fs') +const { join, resolve } = require('node:path') +const { createContext, runInContext } = require('node:vm') + +const dist = process.argv[2] ? resolve(process.argv[2]) : resolve(__dirname, '..', '..', 'dist') +const tags = new WeakMap() +const owners = new WeakMap() +const diagnostics = new WeakMap() +function tagged(value, kind) { + tags.set(value, kind) + return value +} +function requireKind(value, kind, name) { + if (tags.get(value) !== kind) throw new Error(`Expected a native ${name} carrier`) +} +const native = { + DynWin32: class {}, + DynWin32Unsafe: class {}, + win32CarrierKind: (value) => tags.get(value) || 0, + win32Bind: () => tagged({}, 4), + win32CallErrorCleanupFailures(value) { + requireKind(value, 8, 'DynWin32CallError') + return diagnostics.get(value) + }, + win32CallErrorRetryCleanup(value) { + requireKind(value, 8, 'DynWin32CallError') + for (const record of diagnostics.get(value)) owners.get(record.resource).closed = true + }, + win32ResourceClosed: (value) => owners.get(value).closed, + win32ResourceClose(value) { + owners.get(value).closed = true + }, +} +function loadFacade(overrides = {}) { + const module = { exports: {} } + const context = createContext({ + module, + require(name) { + assert.equal(name, './index.js') + return native + }, + Error, + TypeError, + AggregateError, + ...overrides, + }) + runInContext(readFileSync(join(dist, 'win32-internal.js'), 'utf8'), context) + return { runtime: module.exports, context } +} +const loaded = loadFacade() +const { DynWin32CallError, DynWin32Function, DynWin32Resource } = loaded.runtime +const fn = DynWin32Function.bind({}) +const invokeModes = [() => fn.invoke([]), () => fn.invokeWithSubsystem({}, 'winsock', [])] +function capture(call) { + try { + call() + } catch (error) { + return error + } + throw new Error('Expected a thrown value') +} +function throwFromNative(error) { + native.win32Invoke = native.win32InvokeWithSubsystem = () => { + throw error + } +} +function failure() { + const error = tagged(new Error('original native cleanup error'), 8) + const resource = tagged({}, 3) + owners.set(resource, { closed: false }) + diagnostics.set(error, [ + { + target: { kind: 'parameter', index: 2 }, + error: { code: -2147024890, message: 'original cleanup diagnostic' }, + resource, + }, + ]) + return error +} + +assert.ok(DynWin32CallError.prototype instanceof Error) +assert.throws(() => new DynWin32CallError(), /native dispatch/) +for (const invoke of invokeModes) { + const error = failure() + throwFromNative(error) + assert.equal(capture(invoke), error) + assert.ok(error instanceof DynWin32CallError) + assert.equal(error.message, 'original native cleanup error') + const records = error.cleanupFailures + assert.equal(error.cleanupFailures, records) + assert.ok(Object.isFrozen(records)) + assert.ok(Object.isFrozen(records[0])) + assert.ok(Object.isFrozen(records[0].target)) + assert.ok(Object.isFrozen(records[0].error)) + assert.ok(records[0].resource instanceof DynWin32Resource) + assert.equal(Reflect.set(error, 'cleanupFailures', []), false) + assert.equal(Reflect.set(records[0], 'resource', {}), false) + assert.equal(Reflect.set(records[0].error, 'message', 'changed'), false) + assert.equal(records[0].resource.closed, false) + error.retryCleanup() + assert.equal(records[0].resource.closed, true) + assert.equal(error.cleanupFailures, records) + + const frozenError = failure() + Object.preventExtensions(frozenError) + throwFromNative(frozenError) + const aggregate = capture(invoke) + assert.ok(aggregate instanceof AggregateError) + assert.equal(aggregate.cause, frozenError) + assert.equal(aggregate.errors[0], frozenError) + assert.equal(aggregate.errors[1].name, 'TypeError') + const recovery = aggregate.cleanupFailures[0].resource + aggregate.retryCleanup() + assert.equal(recovery.closed, true) +} + +const descriptorPrototype = runInContext('Object.prototype', loaded.context) +for (const name of ['get', 'set', 'value', 'writable']) { + const original = Object.getOwnPropertyDescriptor(descriptorPrototype, name) + const error = failure() + Object.preventExtensions(error) + throwFromNative(error) + let received + try { + Object.defineProperty(descriptorPrototype, name, { __proto__: null, value: undefined, configurable: true }) + received = capture(invokeModes[0]) + } finally { + Reflect.deleteProperty(descriptorPrototype, name) + if (original) Object.defineProperty(descriptorPrototype, name, { __proto__: null, ...original }) + } + assert.ok(received instanceof AggregateError, `inherited descriptor ${name} must not break recovery`) + assert.equal(received.cause, error) + assert.equal(received.errors[0], error) + received.retryCleanup() + assert.equal(received.cleanupFailures[0].resource.closed, true) +} + +for (const stage of ['construct', 'decorate']) { + const failureInRecovery = new Error(`${stage} recovery failed`) + const overrides = + stage === 'construct' + ? { + AggregateError: function () { + throw failureInRecovery + }, + } + : { + Object: new Proxy(Object, { + get(target, name) { + if (name === 'defineProperties') + return () => { + throw failureInRecovery + } + return Reflect.get(target, name) + }, + }), + } + const runtime = loadFacade(overrides).runtime + const failing = runtime.DynWin32Function.bind({}) + for (const mode of ['invoke', 'records']) { + const error = failure() + throwFromNative(error) + if (mode === 'invoke') Object.preventExtensions(error) + let received = capture(() => failing.invoke([])) + if (mode === 'records') { + Object.preventExtensions(diagnostics.get(error)[0].resource) + received = capture(() => received.cleanupFailures) + } + assert.equal(received, error, `${stage}/${mode} must preserve the owning native error`) + runtime.DynWin32CallError.retryCleanup(received) + assert.equal(owners.get(diagnostics.get(error)[0].resource).closed, true) + if (mode === 'invoke') { + assert.equal(runtime.DynWin32CallError.getCleanupFailures(received)[0].resource.closed, true) + } + } +} + +const recordError = failure() +Object.preventExtensions(diagnostics.get(recordError)[0].resource) +throwFromNative(recordError) +assert.equal(capture(invokeModes[0]), recordError) +const recordProjection = capture(() => recordError.cleanupFailures) +assert.ok(recordProjection instanceof AggregateError) +assert.equal(recordProjection.cause, recordError) +assert.equal(recordProjection.errors[0], recordError) +recordProjection.retryCleanup() +assert.equal(owners.get(diagnostics.get(recordError)[0].resource).closed, true) + +const nativeProjection = failure() +throwFromNative(nativeProjection) +assert.equal(capture(invokeModes[0]), nativeProjection) +const readRecords = native.win32CallErrorCleanupFailures +const diagnosticError = new Error('N-API result projection failed') +native.win32CallErrorCleanupFailures = () => { + throw diagnosticError +} +const retained = capture(() => nativeProjection.cleanupFailures) +assert.equal(retained.cause, nativeProjection) +assert.equal(retained.errors[1], diagnosticError) +retained.retryCleanup() +native.win32CallErrorCleanupFailures = readRecords +assert.equal(retained.cleanupFailures[0].resource.closed, true) + +let coercions = 0 +const hostile = { + toString() { + coercions++ + throw new Error('unexpected toString') + }, + get cause() { + coercions++ + throw new Error('unexpected cause') + }, +} +for (const value of [ + new Error('ordinary'), + hostile, + Object.create(DynWin32CallError.prototype), + 'string', + 1, + 1n, + Symbol('value'), + null, + undefined, + false, + () => {}, +]) { + throwFromNative(value) + for (const invoke of invokeModes) assert.equal(capture(invoke), value) +} +assert.equal(coercions, 0) +const cleanupGetter = Object.getOwnPropertyDescriptor(DynWin32CallError.prototype, 'cleanupFailures').get +for (const forged of [hostile, Object.create(DynWin32CallError.prototype), tagged({}, 1)]) { + assert.throws(() => cleanupGetter.call(forged), /native DynWin32CallError/) + assert.throws(() => DynWin32CallError.prototype.retryCleanup.call(forged), /native DynWin32CallError/) +} + +const declaration = readFileSync(join(dist, 'index.d.ts'), 'utf8') +assert.match(declaration, /export declare class DynWin32CallError extends Error \{/) +assert.match(declaration, /readonly cleanupFailures: readonly DynWin32CleanupFailure\[\]/) +assert.match(declaration, /static getCleanupFailures\(error: unknown\): readonly DynWin32CleanupFailure\[\]/) +assert.match(declaration, /static retryCleanup\(error: unknown\): void/) +assert.match(declaration, /readonly kind: 'aggregate-field'; readonly parameter: number; readonly field: number/) +for (const facade of ['win32', 'win32-unsafe']) { + const text = readFileSync(join(dist, `${facade}.d.ts`), 'utf8') + assert.match(text, /\bDynWin32CallError\b/) + assert.match(text, /export type \{ DynWin32CleanupFailure, DynWin32ResultTarget \}/) + assert.doesNotMatch(text, /\bwin32TestCleanupFailure\b/) +} +for (const facade of ['winrt', 'com', 'com-unsafe', 'com-unsafe-raw']) { + assert.doesNotMatch( + readFileSync(join(dist, `${facade}.d.ts`), 'utf8'), + /DynWin32|win32CallError|win32TestCleanupFailure/, + ) + assert.doesNotMatch( + readFileSync(join(dist, `${facade}.js`), 'utf8'), + /DynWin32|win32CallError|win32TestCleanupFailure/, + ) +} +console.log('PASS Win32 cleanup error facade') diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 8037fd1d..47e532b4 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -172,12 +172,17 @@ test('package facades exactly partition native exports', (t) => { 'win32ResultOutputs', 'win32ResultLastError', 'win32ResultSucceeded', + 'win32CallErrorCleanupFailures', + 'win32CallErrorRetryCleanup', 'win32SubsystemName', 'win32SubsystemClosed', 'win32SubsystemClose', 'win32OverlappedCancel', 'win32OverlappedStart', ]) + if (typeof nativeRuntime.win32TestCleanupFailure === 'function') { + win32NativeNames.add('win32TestCleanupFailure') + } t.deepEqual( nativeKeys.filter((name) => name.startsWith('win32') || name.startsWith('DynWin32')), [...win32NativeNames].sort(), @@ -248,7 +253,7 @@ test('package facades exactly partition native exports', (t) => { t.false(Object.prototype.hasOwnProperty.call(facade, name)) } const safeWin32Names = [ - 'DynWin32', 'DynWin32NativeStruct', 'DynWin32OverlappedOperation', 'DynWin32Resource', + 'DynWin32', 'DynWin32CallError', 'DynWin32NativeStruct', 'DynWin32OverlappedOperation', 'DynWin32Resource', 'DynWin32SubsystemContext', 'DynWin32Value', 'DynWinRtValue', ] t.deepEqual(moduleKeys(win32CjsRuntime), safeWin32Names.sort()) diff --git a/bindings/js/__test__/win32-contracts.spec.ts b/bindings/js/__test__/win32-contracts.spec.ts index 7f56f11b..ffa99872 100644 --- a/bindings/js/__test__/win32-contracts.spec.ts +++ b/bindings/js/__test__/win32-contracts.spec.ts @@ -16,11 +16,14 @@ import { DynCom, DynWinRtValue, initializeCom } from '../dist/com-unsafe.js' import { DynWinRtType, WinGuid } from '../dist/winrt.js' import { DynWin32, + DynWin32CallError, DynWin32Function, DynWin32NativeStruct, DynWin32Resource, DynWin32Unsafe, + type DynWin32CleanupFailure, type DynWin32OverlappedOperation, + type DynWin32ResultTarget, } from '../dist/win32-unsafe.js' import * as safe from '../dist/win32.js' @@ -83,6 +86,7 @@ test('Win32 facades retain the full isolated runtime without manual safe descrip .sort(), [ 'DynWin32', + 'DynWin32CallError', 'DynWin32NativeStruct', 'DynWin32OverlappedOperation', 'DynWin32Resource', @@ -110,6 +114,138 @@ test('Win32 facades retain the full isolated runtime without manual safe descrip } }) +test('Win32 cleanup errors have a read-only typed recovery surface on both Win32 subpaths', (t) => { + t.is(safe.DynWin32CallError, DynWin32CallError) + t.true(DynWin32CallError.prototype instanceof Error) + t.throws(() => Reflect.construct(DynWin32CallError, []), { instanceOf: TypeError, message: /native dispatch/ }) + const getter = Object.getOwnPropertyDescriptor(DynWin32CallError.prototype, 'cleanupFailures')! + t.is(getter.set, undefined) + for (const forged of [ + {}, + new Error('ordinary error'), + Object.create(DynWin32CallError.prototype), + Object.setPrototypeOf(DynWin32.i32(1), DynWin32CallError.prototype), + Object.setPrototypeOf(Buffer.alloc(8), DynWin32CallError.prototype), + ]) { + t.throws(() => getter.get!.call(forged), { message: /native DynWin32CallError/ }) + t.throws(() => DynWin32CallError.prototype.retryCleanup.call(forged), { message: /native DynWin32CallError/ }) + t.throws(() => DynWin32CallError.getCleanupFailures(forged), { message: /native DynWin32CallError/ }) + t.throws(() => DynWin32CallError.retryCleanup(forged), { message: /native DynWin32CallError/ }) + } + + const typecheck = (error: DynWin32CallError) => { + const ordinary: Error = error + const records: readonly DynWin32CleanupFailure[] = error.cleanupFailures + const target: DynWin32ResultTarget = records[0].target + const resource: DynWin32Resource = records[0].resource + const diagnostic: { readonly code: number; readonly message: string } = records[0].error + const safeError: safe.DynWin32CallError = error + const safeRecord: safe.DynWin32CleanupFailure = records[0] + const safeTarget: safe.DynWin32ResultTarget = target + const unprojected: unknown = error + const recovered: readonly DynWin32CleanupFailure[] = DynWin32CallError.getCleanupFailures(unprojected) + safe.DynWin32CallError.retryCleanup(unprojected) + // @ts-expect-error recovery records cannot be replaced + error.cleanupFailures = [] + // @ts-expect-error the recovery list is immutable + records.push(records[0]) + // @ts-expect-error targets are immutable + records[0].target.kind = 'return' + // @ts-expect-error original diagnostics are immutable + records[0].error.message = 'changed' + // @ts-expect-error managed owners cannot be replaced + records[0].resource = resource + return [ordinary, diagnostic, safeError, safeRecord, safeTarget, recovered] + } + t.is(typeof typecheck, 'function') +}) + +test('Win32 cleanup error facade retains recovery on projection failures without native fixtures', (t) => { + const child = spawnSync( + process.execPath, + [fileURLToPath(new URL('./fixtures/win32-cleanup-facade.cjs', import.meta.url))], + { encoding: 'utf8', timeout: 15000, windowsHide: true }, + ) + t.is(child.status, 0, `${child.error}\n${child.stdout}\n${child.stderr}`) + t.regex(child.stdout, /PASS Win32 cleanup error facade/) +}) + +const cleanupNativeTest = typeof require('../dist/index.js').win32TestCleanupFailure === 'function' ? test : test.skip +cleanupNativeTest('Win32 cleanup failure native owners survive transport, retries, aliases and GC', (t) => { + const child = spawnSync( + process.execPath, + ['--expose-gc', fileURLToPath(new URL('./fixtures/win32-cleanup-errors.cjs', import.meta.url))], + { encoding: 'utf8', timeout: 30000, windowsHide: true }, + ) + t.is(child.status, 0, `${child.error}\n${child.stdout}\n${child.stderr}`) + t.regex(child.stdout, /PASS Win32 cleanup error native recovery and lifetime/) +}) + +test('Win32 invocation errors without cleanup retain their messages and user-thrown values', (t) => { + const mulDiv = DynWin32Function.bind({ + dll: 'kernel32.dll', + entryPoint: 'MulDiv', + parameters: Array.from({ length: 3 }, () => ({ type: 'i32', direction: 'in' })), + returnType: 'i32', + }) + const ordinary = t.throws(() => mulDiv.invoke([DynWin32.u32(1), DynWin32.i32(2), DynWin32.i32(3)]))! + t.false(ordinary instanceof DynWin32CallError) + t.regex(ordinary.message, /^DynWin32Function kernel32\.dll!MulDiv: /) + t.false('cleanupFailures' in ordinary) + t.false('retryCleanup' in ordinary) + + let coercions = 0 + const hostile = { + toString() { + coercions++ + throw new Error('User toString must not run') + }, + get cause() { + coercions++ + throw new Error('User cause must not run') + }, + } + const revoked = Proxy.revocable({}, {}) + revoked.revoke() + const context = DynWin32.initializeWinsock() + try { + for (const thrown of [ + ordinary, + hostile, + Object.create(DynWin32CallError.prototype), + revoked.proxy, + 'plain string', + 7, + 2n, + Symbol('thrown'), + null, + undefined, + false, + () => {}, + ]) { + const args = [DynWin32.i32(1)] + Object.defineProperty(args, 0, { + get() { + throw thrown + }, + }) + for (const invoke of [() => mulDiv.invoke(args), () => mulDiv.invokeWithSubsystem(context, 'winsock', args)]) { + let caught = false + try { + invoke() + } catch (error) { + caught = true + t.is(error, thrown) + } + t.true(caught) + } + } + t.is(coercions, 0) + } finally { + context.close() + } +}) + test('Win32 artifact consumers require the complete runtime dependency tree', (t) => { const artifact = mkdtempSync(fileURLToPath(new URL('../target-artifact-', import.meta.url))) const consumer = fileURLToPath(new URL('../scripts/verify-runtime-artifact.mjs', import.meta.url)) diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index f1aad9ce..c3196846 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -266,6 +266,7 @@ const win32NativeExports = [ 'win32ResourceActive', 'win32ResourceClose', 'win32Bind', 'win32FunctionDll', 'win32FunctionEntryPoint', 'win32Invoke', 'win32InvokeWithSubsystem', 'win32ResultReturnValue', 'win32ResultOutputs', 'win32ResultLastError', 'win32ResultSucceeded', + 'win32CallErrorCleanupFailures', 'win32CallErrorRetryCleanup', 'win32SubsystemName', 'win32SubsystemClosed', 'win32SubsystemClose', 'win32OverlappedCancel', 'win32OverlappedStart', ] @@ -280,9 +281,10 @@ const unsafeWin32Methods = [ const win32CarrierNames = [ 'DynWin32Value', 'DynWin32NativeStruct', 'DynWin32Resource', 'DynWin32Function', 'DynWin32CallResult', 'DynWin32SubsystemContext', 'DynWin32OverlappedOperation', + 'DynWin32CallError', ] const safeWin32Names = [ - 'DynWin32', 'DynWin32NativeStruct', 'DynWin32OverlappedOperation', + 'DynWin32', 'DynWin32CallError', 'DynWin32NativeStruct', 'DynWin32OverlappedOperation', 'DynWin32Resource', 'DynWin32SubsystemContext', 'DynWin32Value', 'DynWinRtValue', ] const unsafeWin32Names = [ @@ -292,6 +294,9 @@ writeFileSync(join(distDir, 'win32-internal.js'), [ '// Generated by scripts/generate-entrypoints.mjs - do not edit', "'use strict'", "const native = require('./index.js')", + 'const recoveryRecords = new WeakMap()', + 'const RecoveryAggregateError = AggregateError', + 'const defineProperties = Object.defineProperties', 'class DynWin32Value {', " constructor() { throw new TypeError('Win32 values originate from native runtime helpers') }", '}', @@ -313,8 +318,8 @@ writeFileSync(join(distDir, 'win32-internal.js'), [ ' static bind(spec) { return project(native.win32Bind(spec)) }', ' get dll() { return native.win32FunctionDll(this) }', ' get entryPoint() { return native.win32FunctionEntryPoint(this) }', - ' invoke(args) { return project(native.win32Invoke(this, args)) }', - ' invokeWithSubsystem(context, subsystem, args) { return project(native.win32InvokeWithSubsystem(this, context, subsystem, args)) }', + ' invoke(args) { return invokeNative(() => native.win32Invoke(this, args)) }', + ' invokeWithSubsystem(context, subsystem, args) { return invokeNative(() => native.win32InvokeWithSubsystem(this, context, subsystem, args)) }', '}', 'class DynWin32CallResult {', " constructor() { throw new TypeError('Win32 call results originate only from native dispatch') }", @@ -334,6 +339,13 @@ writeFileSync(join(distDir, 'win32-internal.js'), [ ' cancel() { return native.win32OverlappedCancel(this) }', ' start(callback) { return native.win32OverlappedStart(this, callback) }', '}', + 'class DynWin32CallError extends Error {', + " constructor() { throw new TypeError('Win32 call errors originate only from native dispatch') }", + ' static getCleanupFailures(error) { return cleanupFailures(error) }', + ' static retryCleanup(error) { return native.win32CallErrorRetryCleanup(error) }', + ' get cleanupFailures() { return cleanupFailures(this) }', + ' retryCleanup() { return native.win32CallErrorRetryCleanup(this) }', + '}', `const classes = [null, ${win32CarrierNames.join(', ')}]`, 'function project(value) {', ' if (value === null || typeof value !== "object") return value', @@ -342,6 +354,50 @@ writeFileSync(join(distDir, 'win32-internal.js'), [ ' if (kind) Object.setPrototypeOf(value, classes[kind].prototype)', ' return value', '}', + 'function recoveryProjectionError(value, error) {', + ' try {', + ' const aggregate = new RecoveryAggregateError([value, error], "Win32 cleanup error projection failed", { __proto__: null, cause: value })', + ' defineProperties(aggregate, {', + ' __proto__: null,', + ' cleanupFailures: { __proto__: null, get: () => cleanupFailures(value) },', + ' retryCleanup: { __proto__: null, value: () => native.win32CallErrorRetryCleanup(value) },', + ' })', + ' return aggregate', + ' } catch {', + ' // Never replace the owning carrier; static recovery does not require its projection.', + ' return value', + ' }', + '}', + 'function cleanupFailures(value) {', + ' const cached = recoveryRecords.get(value)', + ' if (cached) return cached', + ' try {', + ' const records = native.win32CallErrorCleanupFailures(value).map((record) => Object.freeze({', + ' target: Object.freeze(record.target),', + ' error: Object.freeze(record.error),', + ' resource: project(record.resource),', + ' }))', + ' Object.freeze(records)', + ' recoveryRecords.set(value, records)', + ' return records', + ' } catch (error) {', + ' if (native.win32CarrierKind(value) !== 8) throw error', + ' throw recoveryProjectionError(value, error)', + ' }', + '}', + 'function invokeNative(call) {', + ' let result', + ' try { result = call() } catch (error) {', + ' if (error === null || typeof error !== "object") throw error', + ' try {', + ' if (native.win32CarrierKind(error) === 8) project(error)', + ' } catch (projectionError) {', + ' throw recoveryProjectionError(error, projectionError)', + ' }', + ' throw error', + ' }', + ' return project(result)', + '}', 'function statics(source, omitted = []) {', ' class Runtime { constructor() { throw new TypeError("Win32 runtime helpers are static") } }', ' for (const name of Object.getOwnPropertyNames(source)) {', @@ -373,13 +429,33 @@ const carrierMembers = [ ['readonly returnValue: DynWin32Value | null', 'readonly outputs: DynWin32Value[]', 'readonly lastError: number | null', 'readonly succeeded: boolean'], ['readonly subsystem: string', 'readonly closed: boolean', 'close(): void'], ['cancel(): void', 'start(callback: (error: Error | null, bytesTransferred?: number) => void): void'], + [ + 'static getCleanupFailures(error: unknown): readonly DynWin32CleanupFailure[]', + 'static retryCleanup(error: unknown): void', + 'readonly cleanupFailures: readonly DynWin32CleanupFailure[]', + 'retryCleanup(): void', + ], +] +const win32CleanupDeclarations = [ + 'export type DynWin32ResultTarget =', + " | { readonly kind: 'return' }", + " | { readonly kind: 'parameter'; readonly index: number }", + " | { readonly kind: 'aggregate-field'; readonly parameter: number; readonly field: number }", + '/** Original cleanup diagnostics and a shared, managed owner; retained after successful retry. */', + 'export interface DynWin32CleanupFailure {', + ' readonly target: DynWin32ResultTarget', + ' /** code is the signed Windows HRESULT; message is the original cleanup error text. */', + ' readonly error: { readonly code: number; readonly message: string }', + ' readonly resource: DynWin32Resource', + '}', ] const carrierMarker = '// Win32 native carrier declarations (generated)' const nativeDeclaration = readFileSync(join(distDir, 'index.d.ts'), 'utf8').split(carrierMarker)[0] writeFileSync(join(distDir, 'index.d.ts'), [ nativeDeclaration.trimEnd(), '', carrierMarker, + ...win32CleanupDeclarations, ...win32CarrierNames.flatMap((name, index) => [ - `export declare class ${name} {`, + `export declare class ${name}${name === 'DynWin32CallError' ? ' extends Error' : ''} {`, ' private constructor()', ` private readonly __${name}Brand: never`, ...carrierMembers[index].map((member) => ` ${member}`), @@ -401,6 +477,7 @@ for (const [file, names, safe] of [ writeFileSync(join(distDir, `${file}.d.ts`), [ '// Generated by scripts/generate-entrypoints.mjs - do not edit', `export { ${names.filter((name) => !safe || name !== 'DynWin32').join(', ')} } from './index.js'`, + "export type { DynWin32CleanupFailure, DynWin32ResultTarget } from './index.js'", ...(safe ? [ `export declare const DynWin32: Omit JSON.stringify(name)).join(' | ')}>`, ] : [ diff --git a/bindings/js/src/win32.rs b/bindings/js/src/win32.rs index c10a0f58..0a156dd8 100644 --- a/bindings/js/src/win32.rs +++ b/bindings/js/src/win32.rs @@ -16,6 +16,8 @@ use super::{com, win32_subsystem, DynWin32SubsystemContext, DynWinRTValue, WinGU #[path = "win32_boundary.rs"] pub(super) mod boundary; +#[path = "win32_call_error.rs"] +mod call_error; #[path = "win32_io.rs"] mod io; pub use io::DynWin32OverlappedOperation; @@ -285,23 +287,32 @@ impl DynWin32Function { self.0.entry_point().to_string() } - pub fn invoke(&self, args: Vec<&DynWin32Value>) -> napi::Result { - self.invoke_impl(args) + pub fn invoke( + &self, + env: napi::Env, + args: Vec<&DynWin32Value>, + ) -> napi::Result { + self.invoke_impl(env, args) } pub fn invoke_with_subsystem( &self, + env: napi::Env, context: &DynWin32SubsystemContext, subsystem: String, args: Vec<&DynWin32Value>, ) -> napi::Result { let _subsystem_guard = win32_subsystem::call_guard(context, &subsystem)?; - self.invoke_impl(args) + self.invoke_impl(env, args) } } impl DynWin32Function { - fn invoke_impl(&self, args: Vec<&DynWin32Value>) -> napi::Result { + fn invoke_impl( + &self, + env: napi::Env, + args: Vec<&DynWin32Value>, + ) -> napi::Result { let owners = args .iter() .filter_map(|value| match &value.pointer_owner { @@ -311,12 +322,13 @@ impl DynWin32Function { }) .collect::>(); com::with_win32_input_leases(&owners, |validate_inputs| { - self.invoke_validated(&args, validate_inputs) + self.invoke_validated(env, &args, validate_inputs) }) } fn invoke_validated( &self, + env: napi::Env, args: &[&DynWin32Value], validate_inputs: &dyn Fn() -> napi::Result<()>, ) -> napi::Result { @@ -369,14 +381,32 @@ impl DynWin32Function { .map(|value| value.value.clone()) .collect::>(); validate_inputs()?; - let result = unsafe { self.0.invoke(&values) }.map_err(|error| { - napi::Error::from_reason(format!( - "DynWin32Function {}!{}: {}", - self.0.dll(), - self.0.entry_point(), - error.message() - )) - })?; + let failure = if self.0.has_owned_result_cleanup() { + Some(call_error::PreparedCallError::new( + env, + format!( + "DynWin32Function {}!{}: ", + self.0.dll(), + self.0.entry_point() + ), + )?) + } else { + None + }; + let result = match unsafe { self.0.invoke(&values) } { + Ok(result) => result, + Err(error) => { + return Err(match failure { + Some(failure) => failure.raise(error), + None => napi::Error::from_reason(format!( + "DynWin32Function {}!{}: {}", + self.0.dll(), + self.0.entry_point(), + error.message() + )), + }); + } + }; Ok(DynWin32CallResult { return_value: result.return_value.map(DynWin32Value::new), outputs: Some(result.outputs.into_iter().map(DynWin32Value::new).collect()), diff --git a/bindings/js/src/win32_boundary.rs b/bindings/js/src/win32_boundary.rs index f1e32ef1..ad67b02c 100644 --- a/bindings/js/src/win32_boundary.rs +++ b/bindings/js/src/win32_boundary.rs @@ -163,9 +163,18 @@ pub(crate) unsafe fn wrap( env: sys::napi_env, value: T, ) -> napi::Result { - let api = tags()?; let mut object = ptr::null_mut(); napi::check_status!(unsafe { sys::napi_create_object(env, &mut object) })?; + unsafe { wrap_existing(env, object, value) }?; + Ok(object) +} + +pub(super) unsafe fn wrap_existing( + env: sys::napi_env, + object: sys::napi_value, + value: T, +) -> napi::Result<*mut T> { + let api = tags()?; let mut value = Box::new(value); napi::check_status!(unsafe { sys::napi_wrap( @@ -178,9 +187,9 @@ pub(crate) unsafe fn wrap( ) })?; // The registered finalizer owns the value even if tagging or JS projection fails. - let _ = Box::into_raw(value); + let pointer = Box::into_raw(value); napi::check_status!(unsafe { (api.tag)(env, object, &tag(T::KIND)) })?; - Ok(object) + Ok(pointer) } unsafe fn has_tag(env: sys::napi_env, raw: sys::napi_value, kind: u32) -> napi::Result { @@ -292,7 +301,7 @@ pub(crate) use carrier; #[napi] pub fn win32_carrier_kind(value: Unknown) -> napi::Result { - for kind in 1..=7 { + for kind in 1..=8 { if unsafe { has_tag(value.value().env, value.raw(), kind) }? { return Ok(kind); } @@ -301,7 +310,7 @@ pub fn win32_carrier_kind(value: Unknown) -> napi::Result { } pub(super) fn has_carrier(env: sys::napi_env, raw: sys::napi_value) -> napi::Result { - for kind in 1..=7 { + for kind in 1..=8 { if unsafe { has_tag(env, raw, kind) }? { return Ok(true); } @@ -363,20 +372,23 @@ pub fn win32_function_entry_point(value: &DynWin32Function) -> String { #[napi] pub fn win32_invoke( + env: Env, value: &DynWin32Function, #[napi(ts_arg_type = "DynWin32Value[]")] args: Unknown, ) -> napi::Result { - value.invoke(super::specification::arguments(&args)?) + value.invoke(env, super::specification::arguments(&args)?) } #[napi] pub fn win32_invoke_with_subsystem( + env: Env, value: &DynWin32Function, context: &DynWin32SubsystemContext, #[napi(ts_arg_type = "string")] subsystem: super::specification::Name, #[napi(ts_arg_type = "DynWin32Value[]")] args: Unknown, ) -> napi::Result { value.invoke_with_subsystem( + env, context, subsystem.into_string(), super::specification::arguments(&args)?, diff --git a/bindings/js/src/win32_call_error.rs b/bindings/js/src/win32_call_error.rs new file mode 100644 index 00000000..2781409b --- /dev/null +++ b/bindings/js/src/win32_call_error.rs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ptr, sync::Arc}; + +use dynwinrt::win32::{CallError, ResultTarget}; +use napi::{ + bindgen_prelude::{JsObjectValue, Object, ToNapiValue}, + sys, Env, Property, PropertyAttributes, +}; +use napi_derive::napi; + +use super::{boundary, DynWin32Resource}; + +pub struct DynWin32CallError { + context: String, + error: Option, +} +boundary::carrier!(DynWin32CallError, 8, "DynWin32CallError"); + +impl DynWin32CallError { + fn error(&self) -> napi::Result<&CallError> { + self + .error + .as_ref() + .ok_or_else(|| napi::Error::from_reason("Win32 call error has not been installed")) + } + + fn message(&self) -> napi::Result { + Ok(format!("{}{}", self.context, self.error()?.message())) + } +} + +pub(super) struct PreparedCallError { + env: Env, + object: sys::napi_value, + state: *mut DynWin32CallError, +} + +impl PreparedCallError { + /// Prepare all JS storage before native dispatch can produce an owned result. + pub(super) fn new(env: Env, context: String) -> napi::Result { + let message = unsafe { String::to_napi_value(env.raw(), String::new()) }?; + let mut object = ptr::null_mut(); + napi::check_status!(unsafe { + sys::napi_create_error(env.raw(), ptr::null_mut(), message, &mut object) + })?; + let state = unsafe { + boundary::wrap_existing( + env.raw(), + object, + DynWin32CallError { + context, + error: None, + }, + ) + }?; + Object::from_raw(env.raw(), object).define_properties(&[ + Property::new() + .with_utf8_name("message")? + .with_getter(message_getter) + .with_property_attributes(PropertyAttributes::Configurable), + Property::new() + .with_utf8_name("name")? + .with_napi_value(&env, "DynWin32CallError")? + .with_property_attributes(PropertyAttributes::Configurable | PropertyAttributes::Writable), + Property::new() + .with_utf8_name("code")? + .with_napi_value(&env, "GenericFailure")? + .with_property_attributes(PropertyAttributes::Configurable | PropertyAttributes::Writable), + ])?; + Ok(Self { env, object, state }) + } + + pub(super) fn raise(self, error: CallError) -> napi::Error { + // The callback's handle scope roots this object until napi_throw takes over. + let state = unsafe { &mut *self.state }; + if error.cleanup_failures().is_empty() { + return napi::Error::from_reason(format!("{}{}", state.context, error.message())); + } + state.error = Some(error); + // No allocation, coercion, or user-controlled toString/cause access occurs + // between installing the native owner and throwing the existing Error. + let status = unsafe { sys::napi_throw(self.env.raw(), self.object) }; + if status != sys::Status::napi_ok { + return napi::Error::new( + napi::Status::from(status), + "Unable to throw the retained Win32 cleanup error", + ); + } + napi::Error::new(napi::Status::PendingException, String::new()) + } +} + +unsafe extern "C" fn message_getter( + env: sys::napi_env, + info: sys::napi_callback_info, +) -> sys::napi_value { + let result = (|| { + let mut receiver = ptr::null_mut(); + napi::check_status!(unsafe { + sys::napi_get_cb_info( + env, + info, + ptr::null_mut(), + ptr::null_mut(), + &mut receiver, + ptr::null_mut(), + ) + })?; + let value = unsafe { &*boundary::unwrap::(env, receiver)? }; + unsafe { String::to_napi_value(env, value.message()?) } + })(); + match result { + Ok(value) => value, + Err(error) => { + unsafe { napi::JsError::from(error).throw_into(env) }; + ptr::null_mut() + } + } +} + +fn field(env: &Env, name: &str, value: T) -> napi::Result { + // Define own data fields without invoking inherited setters during recovery. + Ok( + Property::new() + .with_utf8_name(name)? + .with_napi_value(env, value)? + .with_property_attributes(PropertyAttributes::Enumerable), + ) +} + +#[napi(ts_return_type = "DynWin32CleanupFailure[]")] +pub fn win32_call_error_cleanup_failures<'env>( + env: Env, + value: &DynWin32CallError, +) -> napi::Result>> { + value + .error()? + .cleanup_failures() + .iter() + .map(|failure| { + let mut target = Object::new(&env)?; + let indices = match failure.target() { + ResultTarget::Return {} => { + target.define_properties(&[field(&env, "kind", "return")?])?; + Vec::new() + } + ResultTarget::Parameter { index } => { + target.define_properties(&[field(&env, "kind", "parameter")?])?; + vec![("index", index)] + } + ResultTarget::AggregateField { + parameter, + field: index, + } => { + target.define_properties(&[field(&env, "kind", "aggregate-field")?])?; + vec![("parameter", parameter), ("field", index)] + } + }; + for (name, index) in indices { + let index = u32::try_from(index) + .map_err(|_| napi::Error::from_reason("Win32 cleanup target index exceeds u32"))?; + target.define_properties(&[field(&env, name, index)?])?; + } + let mut error = Object::new(&env)?; + error.define_properties(&[ + field(&env, "code", failure.error().code().0)?, + field(&env, "message", failure.error().to_string())?, + ])?; + let mut record = Object::new(&env)?; + record.define_properties(&[ + field(&env, "target", target)?, + field(&env, "error", error)?, + field( + &env, + "resource", + DynWin32Resource(Arc::clone(failure.resource())), + )?, + ])?; + Ok(record) + }) + .collect() +} + +#[napi] +pub fn win32_call_error_retry_cleanup(value: &DynWin32CallError) -> napi::Result<()> { + value + .error()? + .retry_cleanup() + .map_err(|error| napi::Error::from_reason(error.to_string())) +} + +#[cfg(feature = "test-hooks")] +#[napi] +pub fn win32_test_cleanup_failure(env: Env) -> napi::Result<()> { + let plan = dynwinrt::win32::test_cleanup_failure_plan() + .map_err(|error| napi::Error::from_reason(error.message()))?; + super::DynWin32Function(plan) + .invoke(env, Vec::new()) + .map(|_| ()) +} diff --git a/crates/dynwinrt/src/win32.rs b/crates/dynwinrt/src/win32.rs index d37d71c1..84afe006 100644 --- a/crates/dynwinrt/src/win32.rs +++ b/crates/dynwinrt/src/win32.rs @@ -47,6 +47,14 @@ pub use resource::{ FileCapability, OwnedResource, OwnedResourceAsyncLease, OwnedResourceLease, ResourceAccess, }; +#[path = "win32_result_cleanup.rs"] +mod result_cleanup; +use result_cleanup::ResultOwners; +#[cfg(feature = "test-hooks")] +#[doc(hidden)] +pub use result_cleanup::test_cleanup_failure_plan; +pub use result_cleanup::{CallError, CleanupFailure}; + #[doc(hidden)] #[path = "win32_module.rs"] pub mod module; @@ -709,11 +717,42 @@ impl CallPlan { self.calling_convention } + /// Whether any direct return or native out slot can own a cleanup resource. + pub fn has_owned_result_cleanup(&self) -> bool { + self.owned_result_capacity() != 0 + } + + fn owned_result_capacity(&self) -> usize { + self.contract + .results + .iter() + .filter(|result| { + !matches!(result.target, ResultTarget::AggregateField { .. }) + && result + .policies() + .any(|policy| result_cleanup(*policy).owns_resource()) + }) + .count() + } + + /// Invokes the native function, retaining failed result cleanups in the + /// returned `CallError` so callers can retry without adopting raw handles. + /// /// # Safety /// /// Every pointer and aggregate argument must remain valid for the complete /// native call and satisfy the contract used to construct this plan. - pub unsafe fn invoke(&self, args: &[Value]) -> Result { + pub unsafe fn invoke(&self, args: &[Value]) -> std::result::Result { + let mut result_owners = ResultOwners::default(); + unsafe { self.invoke_inner(args, &mut result_owners) } + .map_err(|error| result_owners.into_error(error)) + } + + unsafe fn invoke_inner( + &self, + args: &[Value], + result_owners: &mut ResultOwners, + ) -> Result { if args.len() != self.input_count { return Err(invalid_argument(&format!( "{}!{} expects {} inputs, received {}", @@ -970,6 +1009,7 @@ impl CallPlan { .as_ref() .map(|layout| try_zeroed_words(layout.size())) .transpose()?; + result_owners.reserve(self.owned_result_capacity())?; for (index, layout) in self.parameter_pointees.iter().enumerate() { let Some(layout) = layout else { continue; @@ -1125,6 +1165,22 @@ impl CallPlan { } } } + if let Some(value) = &return_storage.value { + unsafe { + result_owners.capture(ResultTarget::Return {}, value, &mut return_storage.cleanup) + }; + } + for (index, parameter) in self.parameters.iter().enumerate() { + if let Some(output) = parameter.output_index { + unsafe { + result_owners.capture( + ResultTarget::Parameter { index }, + &output_storage.values[output], + &mut output_storage.cleanup[output], + ) + }; + } + } for (index, layout) in self.parameter_pointees.iter().enumerate() { let Some(layout) = layout else { continue; @@ -1154,59 +1210,65 @@ impl CallPlan { } } - let mut return_value = - if let (Some(layout), Some(words)) = (&self.return_aggregate, aggregate_return_words) { - match return_policy.expect("validated aggregate return policy") { - ResultPolicy::Undefined {} => Some(Value::Unavailable), - ResultPolicy::Defined { - delivery: Delivery::Discard, - .. - } => Some(Value::Discarded), - ResultPolicy::Defined { - ownership: ResultOwnership::Value {}, - delivery: Delivery::Deliver, - } => { - let source = unsafe { - std::slice::from_raw_parts(words.as_ptr().cast::(), layout.size()) - }; - let mut bytes = Vec::new(); - #[cfg(test)] - outcome_tests::check_aggregate_return_allocation()?; - bytes - .try_reserve_exact(source.len()) - .map_err(|_| out_of_memory("native aggregate return"))?; - bytes.extend_from_slice(source); - Some(Value::OwnedAggregate { - layout: Arc::clone(layout), - bytes, - }) - } - _ => { - return Err(invalid_argument( - "Aggregate return has unsupported ownership", - )); - } + let mut return_value = if let (Some(layout), Some(words)) = + (&self.return_aggregate, aggregate_return_words) + { + match return_policy.expect("validated aggregate return policy") { + ResultPolicy::Undefined {} => Some(Value::Unavailable), + ResultPolicy::Defined { + delivery: Delivery::Discard, + .. + } => Some(Value::Discarded), + ResultPolicy::Defined { + ownership: ResultOwnership::Value {}, + delivery: Delivery::Deliver, + } => { + let source = unsafe { + std::slice::from_raw_parts(words.as_ptr().cast::(), layout.size()) + }; + let mut bytes = Vec::new(); + #[cfg(test)] + outcome_tests::check_aggregate_return_allocation()?; + bytes + .try_reserve_exact(source.len()) + .map_err(|_| out_of_memory("native aggregate return"))?; + bytes.extend_from_slice(source); + Some(Value::OwnedAggregate { + layout: Arc::clone(layout), + bytes, + }) } - } else { - match (self.return_type, return_policy) { - (Some(_), Some(ResultPolicy::Undefined {})) => Some(Value::Unavailable), - (Some(typ), Some(policy)) => { - #[cfg(test)] - outcome_tests::check_result_decode(ResultTarget::Return {})?; - let value = return_storage - .value - .take() - .ok_or_else(|| invalid_argument("Missing native return storage"))?; - Some(self.decode_result(typ, value, policy, args, &input_storage)?) - } - (None, None) => None, - _ => { - return Err(invalid_argument( - "flat Win32 call plan produced an inconsistent return value", - )); - } + _ => { + return Err(invalid_argument( + "Aggregate return has unsupported ownership", + )); } - }; + } + } else { + match (self.return_type, return_policy) { + (Some(_), Some(ResultPolicy::Undefined {})) => Some(Value::Unavailable), + (Some(typ), Some(policy)) => { + #[cfg(test)] + outcome_tests::check_result_decode(ResultTarget::Return {})?; + let value = return_storage + .value + .take() + .ok_or_else(|| invalid_argument("Missing native return storage"))?; + Some( + match result_owners.decode(ResultTarget::Return {}, policy) { + Some(result) => result?, + None => self.decode_result(typ, value, policy, args, &input_storage)?, + }, + ) + } + (None, None) => None, + _ => { + return Err(invalid_argument( + "flat Win32 call plan produced an inconsistent return value", + )); + } + } + }; if legacy_null_return { return_value = Some(Value::Handle(0)); } @@ -1234,13 +1296,21 @@ impl CallPlan { &mut output_storage.values[output_index], parameter.spec.typ.default_abi_value(), ); - let decoded = self.decode_result( - parameter.spec.typ, - raw, + let decoded = match result_owners.decode( + ResultTarget::Parameter { + index: _parameter_index, + }, output_policies[output_index], - args, - &input_storage, - )?; + ) { + Some(result) => result?, + None => self.decode_result( + parameter.spec.typ, + raw, + output_policies[output_index], + args, + &input_storage, + )?, + }; outputs.push(if legacy_null_outputs[output_index] { Value::Handle(0) } else { diff --git a/crates/dynwinrt/src/win32_aggregate_lock_tests.rs b/crates/dynwinrt/src/win32_aggregate_lock_tests.rs index 48c729a3..60588cbf 100644 --- a/crates/dynwinrt/src/win32_aggregate_lock_tests.rs +++ b/crates/dynwinrt/src/win32_aggregate_lock_tests.rs @@ -59,7 +59,7 @@ fn duplicate( plan: &CallPlan, input: &Arc, buffer: &Arc, -) -> Result { +) -> std::result::Result { duplicate_with_access(plan, input, buffer, Value::U32(0)) } @@ -68,7 +68,7 @@ fn duplicate_with_access( input: &Arc, buffer: &Arc, access: Value, -) -> Result { +) -> std::result::Result { let process = unsafe { GetCurrentProcess() }.0 as usize; unsafe { plan.invoke(&[ diff --git a/crates/dynwinrt/src/win32_aggregate_tests.rs b/crates/dynwinrt/src/win32_aggregate_tests.rs index 5118da48..a86eaf56 100644 --- a/crates/dynwinrt/src/win32_aggregate_tests.rs +++ b/crates/dynwinrt/src/win32_aggregate_tests.rs @@ -223,6 +223,7 @@ fn fields_are_owned_before_direct_return_conversion_and_result_delivery() { let layout = layout(); let buffer = NativeAggregateBuffer::new(Arc::clone(&layout), None).unwrap(); let plan = planned(layout); + assert!(!plan.has_owned_result_cleanup()); if let Some(target) = failure { outcome_tests::fail_decode(target); } diff --git a/crates/dynwinrt/src/win32_result_cleanup.rs b/crates/dynwinrt/src/win32_result_cleanup.rs new file mode 100644 index 00000000..04d20498 --- /dev/null +++ b/crates/dynwinrt/src/win32_result_cleanup.rs @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::sync::Arc; + +use super::{Cleanup, Delivery, OwnedResource, ResultPolicy, ResultTarget, Value}; +use crate::{ + abi::AbiValue, + result::{Error, Result}, +}; + +/// A defined owned result whose native cleanup failed. +#[derive(Debug)] +pub struct CleanupFailure { + target: ResultTarget, + resource: Arc, + error: windows_core::Error, +} + +impl CleanupFailure { + pub fn target(&self) -> ResultTarget { + self.target + } + + pub fn resource(&self) -> &Arc { + &self.resource + } + + pub fn error(&self) -> &windows_core::Error { + &self.error + } +} + +/// A Win32 invocation failure that retains resources needing cleanup retry. +#[derive(Debug)] +pub struct CallError { + source: Error, + cleanup_failures: Vec, +} + +impl CallError { + pub fn message(&self) -> String { + self.source.message() + } + + pub fn source_error(&self) -> &Error { + &self.source + } + + /// Failures from the invocation. Resources remain in this list after a + /// successful retry, with their shared owner marked closed. + pub fn cleanup_failures(&self) -> &[CleanupFailure] { + &self.cleanup_failures + } + + /// Retries every failed cleanup, preserving failed owners for another retry. + /// This never invokes the original native function again. + pub fn retry_cleanup(&self) -> windows_core::Result<()> { + let mut first_error = None; + for failure in &self.cleanup_failures { + if let Err(error) = failure.resource.close() { + first_error.get_or_insert(error); + } + } + first_error.map_or(Ok(()), Err) + } +} + +impl From for CallError { + fn from(source: Error) -> Self { + Self { + source, + cleanup_failures: Vec::new(), + } + } +} + +impl std::fmt::Display for CallError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.message()) + } +} + +impl std::error::Error for CallError {} + +struct OwnedResult { + target: ResultTarget, + resource: Arc, + cleanup_error: Option, +} + +#[derive(Default)] +pub(super) struct ResultOwners { + owned: Vec, + failures: Vec, +} + +impl ResultOwners { + pub(super) fn reserve(&mut self, capacity: usize) -> Result<()> { + self.owned + .try_reserve_exact(capacity) + .map_err(|_| super::out_of_memory("native result owners"))?; + self.failures + .try_reserve_exact(capacity) + .map_err(|_| super::out_of_memory("native result cleanup failures")) + } + + /// The caller has resolved the native result as defined and exclusively + /// owned, with the exact cleanup matching its resource kind. + pub(super) unsafe fn capture( + &mut self, + target: ResultTarget, + value: &AbiValue, + cleanup: &mut Cleanup, + ) { + if !cleanup.owns_resource() { + return; + } + let AbiValue::Pointer(pointer) = value else { + unreachable!("validated owned result is pointer-shaped"); + }; + if pointer.is_null() { + return; + } + let resource = Arc::new(OwnedResource::new(*pointer as usize, *cleanup)); + self.owned.push(OwnedResult { + target, + resource, + cleanup_error: None, + }); + *cleanup = Cleanup::None; + } + + pub(super) fn decode( + &mut self, + target: ResultTarget, + policy: ResultPolicy, + ) -> Option> { + let owned = self.owned.iter_mut().find(|owned| owned.target == target)?; + let ResultPolicy::Defined { + ownership: super::ResultOwnership::Owned { .. }, + delivery, + } = policy + else { + unreachable!("captured owner has a defined owned result policy"); + }; + Some(match delivery { + Delivery::Deliver => Ok(Value::Resource(Arc::clone(&owned.resource))), + Delivery::Discard => match owned.resource.close() { + Ok(()) => Ok(Value::Discarded), + Err(error) => { + owned.cleanup_error = Some(error.clone()); + Err(Error::WindowsError(error)) + } + }, + }) + } + + pub(super) fn into_error(mut self, source: Error) -> CallError { + for owned in self.owned { + let error = owned.cleanup_error.or_else(|| owned.resource.close().err()); + if let Some(error) = error { + self.failures.push(CleanupFailure { + target: owned.target, + resource: owned.resource, + error, + }); + } + } + CallError { + source, + cleanup_failures: self.failures, + } + } +} + +#[cfg(feature = "test-hooks")] +#[doc(hidden)] +pub fn test_cleanup_failure_plan() -> Result> { + use super::{ + CallContract, CallPlan, CallPlanSpec, CallingConvention, ResultContract, ResultOwnership, + SuccessRule, Type, + }; + use windows::Win32::{ + Foundation::{HANDLE_FLAG_PROTECT_FROM_CLOSE, SetHandleInformation}, + System::Threading::CreateEventW, + }; + + unsafe extern "system" fn protected_output() -> *mut std::ffi::c_void { + let handle = unsafe { CreateEventW(None, true, false, None) }.unwrap(); + unsafe { + SetHandleInformation( + handle, + HANDLE_FLAG_PROTECT_FROM_CLOSE.0, + HANDLE_FLAG_PROTECT_FROM_CLOSE, + ) + } + .unwrap(); + handle.0 + } + + let spec = CallPlanSpec { + dll: "kernel32.dll".into(), + entry_point: "GetLastError".into(), + parameters: Vec::new(), + return_type: Some(Type::Handle), + return_cleanup: Cleanup::CloseHandle, + success_rule: SuccessRule::ReturnNonNull, + capture_last_error: false, + calling_convention: CallingConvention::System, + parameter_aggregates: Vec::new(), + return_aggregate: None, + }; + let contract = CallContract::current( + vec![ResultContract { + target: ResultTarget::Return {}, + on_success: ResultPolicy::discarded(ResultOwnership::Owned { + cleanup: dynwinrt_win32_contracts::Cleanup::CloseHandle, + }), + on_failure: ResultPolicy::Undefined {}, + overrides: Vec::new(), + }], + Vec::new(), + ); + let mut plan = Arc::try_unwrap(unsafe { CallPlan::new_with_contract(spec, contract) }?) + .expect("unshared test plan"); + plan.function = protected_output as *const () as usize; + plan.dll = "test".into(); + plan.entry_point = "cleanupFailure".into(); + Ok(Arc::new(plan)) +} diff --git a/crates/dynwinrt/src/win32_result_cleanup_tests.rs b/crates/dynwinrt/src/win32_result_cleanup_tests.rs new file mode 100644 index 00000000..c587170d --- /dev/null +++ b/crates/dynwinrt/src/win32_result_cleanup_tests.rs @@ -0,0 +1,435 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +use std::cell::Cell; +use windows::Win32::{ + Foundation::{HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAGS, SetHandleInformation}, + System::Threading::CreateEventW, +}; + +thread_local! { + static HANDLES: RefCell> = const { RefCell::new(Vec::new()) }; + static PROTECTED: Cell = const { Cell::new(0) }; +} + +struct Fixture; + +impl Fixture { + fn new(protected: u8) -> Self { + reset(); + HANDLES.with(|handles| handles.borrow_mut().clear()); + PROTECTED.set(protected); + Self + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + // Reclaim only fixture handles whose tracked cleanup never succeeded. + HANDLES.with(|handles| { + for raw in handles.borrow().iter().copied() { + if outcome_tests::successful_cleanup_count_for(raw) == 0 { + protect(raw, false); + unsafe { CloseHandle(HANDLE(raw as *mut c_void)) }.unwrap(); + } + } + }); + } +} + +fn protect(raw: usize, protected: bool) { + unsafe { + SetHandleInformation( + HANDLE(raw as *mut c_void), + HANDLE_FLAG_PROTECT_FROM_CLOSE.0, + if protected { + HANDLE_FLAG_PROTECT_FROM_CLOSE + } else { + HANDLE_FLAGS(0) + }, + ) + } + .unwrap(); +} + +fn event(index: u8) -> *mut c_void { + let handle = unsafe { CreateEventW(None, true, false, None) }.unwrap(); + HANDLES.with(|handles| handles.borrow_mut().push(handle.0 as usize)); + if PROTECTED.get() & (1 << index) != 0 { + protect(handle.0 as usize, true); + } + handle.0 +} + +fn discarded() -> ResultPolicy { + ResultPolicy::discarded(ResultOwnership::Owned { + cleanup: dynwinrt_win32_contracts::Cleanup::CloseHandle, + }) +} + +#[test] +fn discarded_return_and_out_slots_keep_retryable_owners_on_native_success_or_failure() { + unsafe extern "system" fn returned() -> *mut c_void { + event(0) + } + unsafe extern "system" fn output(slot: *mut *mut c_void) -> i32 { + unsafe { *slot = event(0) }; + 1 + } + for direct in [true, false] { + for native_success in [true, false] { + for explicit_retry in [true, false] { + let _fixture = Fixture::new(1); + let target = if direct { + ResultTarget::Return {} + } else { + ResultTarget::Parameter { index: 0 } + }; + let signature = if direct { + spec( + Vec::new(), + Type::Handle, + Cleanup::CloseHandle, + if native_success { + SuccessRule::ReturnNonNull + } else { + SuccessRule::ReturnZero + }, + ) + } else { + spec( + vec![Parameter::output(Type::Handle, Cleanup::CloseHandle)], + Type::Bool32, + Cleanup::None, + if native_success { + SuccessRule::ReturnNonZero + } else { + SuccessRule::ReturnZero + }, + ) + }; + let call = plan( + if direct { + returned as *const () as usize + } else { + output as *const () as usize + }, + signature, + |contract| { + let result = contract + .results + .iter_mut() + .find(|result| result.target == target) + .unwrap(); + result.on_success = discarded(); + result.on_failure = discarded(); + }, + ); + assert!(call.has_owned_result_cleanup()); + let error = unsafe { call.invoke(&[]) }.unwrap_err(); + let raw = HANDLES.with(|handles| handles.borrow()[0]); + assert_eq!(error.cleanup_failures().len(), 1); + let failure = &error.cleanup_failures()[0]; + assert_eq!(failure.target(), target); + assert_eq!(failure.resource().raw(), raw); + assert_eq!(failure.error().code().0 as u32, 0x80070006); + assert!(matches!(error.source_error(), Error::WindowsError(_))); + assert_eq!(outcome_tests::cleanup_count_for(raw), 1); + assert_eq!(outcome_tests::successful_cleanup_count_for(raw), 0); + if explicit_retry { + assert!(error.retry_cleanup().is_err()); + assert_eq!(error.cleanup_failures()[0].resource().raw(), raw); + assert_eq!(outcome_tests::cleanup_count_for(raw), 2); + protect(raw, false); + let alias = Arc::clone(error.cleanup_failures()[0].resource()); + error.retry_cleanup().unwrap(); + error.retry_cleanup().unwrap(); + assert!(alias.is_closed()); + assert_eq!(alias.raw(), 0); + drop(error); + alias.close().unwrap(); + assert_eq!(outcome_tests::cleanup_count_for(raw), 3); + } else { + protect(raw, false); + drop(error); + assert_eq!(outcome_tests::cleanup_count_for(raw), 2); + } + assert_eq!(outcome_tests::successful_cleanup_count_for(raw), 1); + } + } + } +} + +unsafe extern "system" fn three_results( + first: *mut *mut c_void, + second: *mut *mut c_void, +) -> *mut c_void { + let returned = event(0); + unsafe { + *first = event(1); + *second = event(2); + } + returned +} + +fn three_result_spec() -> CallPlanSpec { + spec( + vec![Parameter::output(Type::Handle, Cleanup::CloseHandle); 2], + Type::Handle, + Cleanup::CloseHandle, + SuccessRule::ReturnNonNull, + ) +} + +#[test] +fn later_conversion_failure_preserves_every_owner_and_partial_cleanup_retry() { + let _fixture = Fixture::new(7); + let call = plan( + three_results as *const () as usize, + three_result_spec(), + |_| {}, + ); + outcome_tests::fail_decode(ResultTarget::Parameter { index: 1 }); + let error = unsafe { call.invoke(&[]) }.unwrap_err(); + assert!( + error + .message() + .contains("Injected native result conversion failure") + ); + assert_eq!(error.cleanup_failures().len(), 3); + assert_eq!( + error + .cleanup_failures() + .iter() + .map(CleanupFailure::target) + .collect::>(), + [ + ResultTarget::Return {}, + ResultTarget::Parameter { index: 0 }, + ResultTarget::Parameter { index: 1 } + ] + ); + let raw = HANDLES.with(|handles| handles.borrow().clone()); + for handle in &raw { + assert_eq!(outcome_tests::cleanup_count_for(*handle), 1); + } + protect(raw[1], false); + assert!(error.retry_cleanup().is_err()); + assert!(!error.cleanup_failures()[0].resource().is_closed()); + assert!(error.cleanup_failures()[1].resource().is_closed()); + assert!(!error.cleanup_failures()[2].resource().is_closed()); + protect(raw[0], false); + protect(raw[2], false); + error.retry_cleanup().unwrap(); + error.retry_cleanup().unwrap(); + drop(error); + for (index, handle) in raw.iter().enumerate() { + assert_eq!( + outcome_tests::cleanup_count_for(*handle), + if index == 1 { 2 } else { 3 } + ); + assert_eq!(outcome_tests::successful_cleanup_count_for(*handle), 1); + } +} + +#[test] +fn failed_discard_retires_other_delivered_and_unprocessed_results_once() { + let _fixture = Fixture::new(2); + let call = plan( + three_results as *const () as usize, + three_result_spec(), + |contract| { + contract + .results + .iter_mut() + .find(|result| result.target == (ResultTarget::Parameter { index: 0 })) + .unwrap() + .on_success = discarded(); + }, + ); + let error = unsafe { call.invoke(&[]) }.unwrap_err(); + let raw = HANDLES.with(|handles| handles.borrow().clone()); + assert_eq!(error.cleanup_failures().len(), 1); + assert_eq!( + error.cleanup_failures()[0].target(), + ResultTarget::Parameter { index: 0 } + ); + for handle in &raw { + assert_eq!(outcome_tests::cleanup_count_for(*handle), 1); + } + assert_eq!(outcome_tests::successful_cleanup_count_for(raw[0]), 1); + assert_eq!(outcome_tests::successful_cleanup_count_for(raw[2]), 1); + protect(raw[1], false); + error.retry_cleanup().unwrap(); + drop(error); + assert_eq!(outcome_tests::successful_cleanup_count_for(raw[1]), 1); + assert_eq!(outcome_tests::cleanup_count_for(raw[1]), 2); +} + +#[test] +fn cleanup_recovery_does_not_retire_borrowed_aliases_and_respects_resource_leases() { + unsafe extern "system" fn alias(input: *mut c_void, output: *mut *mut c_void) -> *mut c_void { + unsafe { *output = event(1) }; + input + } + let _fixture = Fixture::new(2); + let input = unsafe { OwnedResource::adopt(event(0) as usize, Cleanup::CloseHandle) }.unwrap(); + let input_raw = input.raw(); + let call = plan( + alias as *const () as usize, + spec( + vec![ + Parameter { + resource_cleanup: Cleanup::CloseHandle, + ..Parameter::input(Type::Handle, false) + }, + Parameter::output(Type::Handle, Cleanup::CloseHandle), + ], + Type::Handle, + Cleanup::CloseHandle, + SuccessRule::ReturnNonNull, + ), + |contract| { + for result in &mut contract.results { + result.on_success = if result.target == (ResultTarget::Return {}) { + ResultPolicy::delivered(ResultOwnership::AliasInput { parameter: 0 }) + } else { + discarded() + }; + } + }, + ); + let error = unsafe { call.invoke(&[Value::Resource(Arc::clone(&input))]) }.unwrap_err(); + assert_eq!(error.cleanup_failures().len(), 1); + assert!(!input.is_closed()); + assert_eq!(outcome_tests::cleanup_count_for(input_raw), 0); + let resource = Arc::clone(error.cleanup_failures()[0].resource()); + let raw = resource.raw(); + protect(raw, false); + let lease = resource.async_lease(Cleanup::CloseHandle).unwrap(); + assert!(error.retry_cleanup().is_err()); + assert!(!resource.is_closed()); + assert_eq!(outcome_tests::cleanup_count_for(raw), 1); + drop(lease); + error.retry_cleanup().unwrap(); + assert!(resource.is_closed()); + input.close().unwrap(); + assert_eq!(outcome_tests::successful_cleanup_count_for(raw), 1); + assert_eq!(outcome_tests::successful_cleanup_count_for(input_raw), 1); +} + +#[test] +fn errors_before_dispatch_have_no_cleanup_recovery_resources() { + let _fixture = Fixture::new(0); + let call = plan( + three_results as *const () as usize, + three_result_spec(), + |_| {}, + ); + let error = unsafe { call.invoke(&[Value::U32(1)]) }.unwrap_err(); + assert!(error.message().contains("expects 0 inputs")); + assert!(error.cleanup_failures().is_empty()); + error.retry_cleanup().unwrap(); + assert!(HANDLES.with(|handles| handles.borrow().is_empty())); +} + +#[test] +fn scalar_calls_do_not_require_cleanup_error_preparation() { + extern "system" fn scalar() -> u32 { + 42 + } + let call = plan( + scalar as *const () as usize, + spec(Vec::new(), Type::U32, Cleanup::None, SuccessRule::Always), + |_| {}, + ); + assert!(!call.has_owned_result_cleanup()); + assert!(matches!( + unsafe { call.invoke(&[]) }.unwrap().return_value, + Some(Value::U32(42)) + )); +} + +#[test] +fn aggregate_conversion_failure_keeps_field_ownership_separate_from_slot_recovery() { + unsafe extern "system" fn combined( + aggregate: *mut usize, + output: *mut *mut c_void, + ) -> *mut c_void { + let returned = event(0); + unsafe { + *aggregate = event(1) as usize; + *output = event(2); + } + returned + } + + let _fixture = Fixture::new(7); + let layout = NativeAggregatePointerLayout::new( + "Tests.CleanupResult".into(), + size_of::(), + align_of::(), + vec![AggregateResultField { + name: "handle".into(), + offset: 0, + typ: Type::Handle, + cleanup: Cleanup::CloseHandle, + }], + ) + .unwrap(); + let buffer = NativeAggregateBuffer::new(Arc::clone(&layout), None).unwrap(); + let specification = spec( + vec![ + Parameter::input(Type::Pointer, false), + Parameter::output(Type::Handle, Cleanup::CloseHandle), + ], + Type::Handle, + Cleanup::CloseHandle, + SuccessRule::ReturnNonNull, + ); + let pointees = vec![Some(layout), None]; + let contract = + CallContract::defaults(&contract::shape_with_pointees(&specification, &pointees)); + let mut call = Arc::try_unwrap( + unsafe { CallPlan::new_with_contract_and_pointees(specification, contract, pointees) } + .unwrap(), + ) + .unwrap(); + call.function = combined as *const () as usize; + outcome_tests::fail_decode(ResultTarget::AggregateField { + parameter: 0, + field: 0, + }); + let error = + unsafe { call.invoke(&[Value::AggregatePointer(Arc::clone(&buffer))]) }.unwrap_err(); + let raw = HANDLES.with(|handles| handles.borrow().clone()); + assert_eq!( + error + .cleanup_failures() + .iter() + .map(CleanupFailure::target) + .collect::>(), + [ + ResultTarget::Return {}, + ResultTarget::Parameter { index: 1 } + ] + ); + assert_eq!(usize::from_ne_bytes(buffer.read(0).unwrap()), raw[1]); + assert_eq!(outcome_tests::cleanup_count_for(raw[1]), 0); + assert!(buffer.write(0, &0usize.to_ne_bytes()).is_err()); + for handle in &raw { + protect(*handle, false); + } + error.retry_cleanup().unwrap(); + buffer.prepare().unwrap(); + drop(error); + drop(buffer); + for (index, handle) in raw.iter().enumerate() { + assert_eq!(outcome_tests::successful_cleanup_count_for(*handle), 1); + assert_eq!( + outcome_tests::cleanup_count_for(*handle), + if index == 1 { 1 } else { 2 } + ); + } +} diff --git a/crates/dynwinrt/src/win32_result_tests.rs b/crates/dynwinrt/src/win32_result_tests.rs index cda99468..680553df 100644 --- a/crates/dynwinrt/src/win32_result_tests.rs +++ b/crates/dynwinrt/src/win32_result_tests.rs @@ -4,6 +4,9 @@ use super::*; use std::cell::RefCell; +#[path = "win32_result_cleanup_tests.rs"] +mod cleanup_tests; + thread_local! { static ALLOCATED: RefCell> = const { RefCell::new(Vec::new()) }; } fn allocate() -> *mut c_void { diff --git a/docs/architecture/flat-win32-contracts.md b/docs/architecture/flat-win32-contracts.md index 05edad09..1295c08b 100644 --- a/docs/architecture/flat-win32-contracts.md +++ b/docs/architecture/flat-win32-contracts.md @@ -4,6 +4,14 @@ Flat Win32 bindings dynamically invoke DLL exports described by Windows metadata. They use a Win32-local ABI model and explicit semantic contracts, separate from WinRT activation and Classic COM vtables. +> **Status: experimental.** Flat Win32 support is under active development and +> intended for evaluation and prototyping. Its JavaScript/TypeScript APIs, +> generated bindings, and Win32 runtime/codegen contracts may change between +> releases; backward compatibility is not yet guaranteed. Do not treat this +> projection as a stable production dependency. Use matching runtime and +> codegen versions, regenerate Win32 bindings when upgrading, and validate the +> APIs you rely on in your target environment. + ## Metadata and supported capabilities Built-in contracts are validated against @@ -95,6 +103,34 @@ allocation or conversion failure also retires valid, untransferred resources. Language projection chooses nullability and exception/result shape; it cannot erase cleanup obligations. +Direct-return and independent out-slot resource owners are captured before +fallible result processing. An error retires untransferred results and preserves +any failed cleanup in `win32::CallError::cleanup_failures()`, together with its +result target, original cleanup error, and shared `OwnedResource`. This includes +results converted earlier in the call but not yet delivered to the caller. +`retry_cleanup()` attempts every retained cleanup without invoking the original +function again; successful owners stay closed and failed owners remain available +for another retry. Native consumption and resource effects are not rolled back +by a result-processing failure. Callers can also retain +or explicitly close the same resource owner through the failure record. +No raw-handle re-adoption or process-global recovery queue is used. + +JavaScript recovery wrapping uses null-prototype property descriptors. If an +`AggregateError` cannot be constructed or decorated after projection failure, +the original native error carrier is rethrown rather than replaced by the +wrapping exception. `DynWin32CallError.getCleanupFailures(error)` and +`DynWin32CallError.retryCleanup(error)` work without installing an instance +prototype, including for non-extensible carriers. Keeping the thrown carrier +therefore keeps the native cleanup owner and its recovery path alive. + +`CallPlan::invoke()` returns the Win32-specific `CallError` on failure; its +`message()` and `source_error()` preserve the original invocation error. +Dropping the error releases its retained owners and performs best-effort cleanup. +Deterministic recovery requires keeping the error or resource alive, resolving +the reason cleanup was refused, and retrying. The runtime does not remove native +close-protection flags or bypass resource leases. Aggregate-field ownership +continues to reside in the caller's aggregate buffer. + Descriptors without a version are read as version 1. Their historical null resource results and cleanup behavior are isolated in an explicit compatibility adapter and lowered to the common execution plan. Version 2 slot-only contracts @@ -304,6 +340,7 @@ and live Windows API tests: | Aggregate field result tests | Caller-owned storage identity, per-field validity and ownership, failed delivery before `_call` wrapping, partial and cross-aggregate conversion failures, unsafe legacy transfers, safe-write protection, extraction, failed discard cleanup retry and real `CreateProcessW` handle retirement. | | Aggregate owner lock tests | Bounded real `DuplicateHandle` reuse, shared-owner rejection without mutation, moved/distinct owners, input-alias policies, failed/busy retirement, invalid-input preservation and ordered/cross-thread resource coordination. | | Native side-effect tests | Input consumption, alias/lease state and real file completion-mode updates across native success/failure, field/return conversion errors and discard cleanup failure. | +| Result cleanup recovery tests | Protected-handle cleanup failures for direct returns and out slots, partial conversion, cleanup of other results, repeated and partial retries, shared owner state, lease exclusion, and best-effort error destruction. | | Native I/O tests | Real local file/pipe I/O without Node, synchronous/pending completion, cancellation, dropped consumers, queued-result quotas and exact lifetime retirement. | | JS Win32 tests | Native carrier identity, argument/descriptor validation, encoded strings and buffers, resource lifetimes, IOCP cancellation/capacity and subsystem state. | | Module/lifecycle loading tests | Controlled System32 paths, successful-cache identity, retryable failures, concurrent load reference balance, complete function-table publication, startup/shutdown/rollback state, and the actual shared-addon PE import boundary. |