From 9d288a9eaf85836a9c66554e6146ac76b792be7b Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 8 Sep 2026 05:01:27 +0800 Subject: [PATCH 1/4] Add guarded COM borrowed-copy transactions Add metadata-validated owned-copy plans for Audio, WIC BGRA8 and linear Media Foundation buffers. Observe real successful Audio initialization and GetService calls, retain canonical identity provenance across aliases, and finalize native borrows exactly once with thread and poison guards. Preserve WIC's existing complete surface, keep three copy-only facades out of complete-interface counts, require full regeneration, and add exact metadata evidence, native fixtures, live x64/i686 tests and regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 29 +- bindings/js/__test__/borrowed-copy-child.cjs | 289 ++++ bindings/js/__test__/borrowed-copy.e2e.ts | 100 ++ .../generated-unsafe-companion.e2e.ts | 3 +- bindings/js/__test__/index.spec.ts | 1 + bindings/js/package.json | 1 + bindings/js/scripts/generate-entrypoints.mjs | 1 + bindings/js/src/com.rs | 129 +- bindings/js/src/com_borrowed.rs | 429 +++++ bindings/js/src/lib.rs | 175 +- crates/dynwinrt/Cargo.toml | 5 + crates/dynwinrt/src/com.rs | 34 + crates/dynwinrt/src/com_borrowed.rs | 1426 +++++++++++++++++ .../dynwinrt/src/com_borrowed_test_support.rs | 1076 +++++++++++++ crates/dynwinrt/src/com_borrowed_tests.rs | 755 +++++++++ .../classic-com-contract-evidence-registry.md | 34 +- .../classic-com-generated-unsafe.md | 4 +- docs/architecture/classic-com-support.md | 174 +- docs/guides/windows/classic-com-usage.md | 81 +- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 22 +- .../classic-com-capability-summary.json | 506 +++++- .../classic-com-interface-support.csv | 2 +- .../src/codegen/com/capability.rs | 28 +- .../src/codegen/com/generated_unsafe.rs | 4 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 39 + .../src/codegen/com/javascript/render.rs | 89 +- .../codegen/com/javascript/render_tests.rs | 17 + tools/dynwinrt-codegen/src/codegen/com/mod.rs | 15 + .../src/codegen/com/model/borrowed.rs | 197 +++ .../src/codegen/com/model/mod.rs | 1 + .../src/codegen/com/project/borrowed.rs | 166 ++ .../codegen/com/project/legacy_diagnostics.rs | 1 + .../src/codegen/com/project/mod.rs | 36 +- .../src/com_borrowed_metadata.rs | 525 ++++++ tools/dynwinrt-codegen/src/com_metadata.rs | 7 +- .../dynwinrt-codegen/src/contract_registry.rs | 17 +- tools/dynwinrt-codegen/src/main.rs | 34 +- 37 files changed, 6335 insertions(+), 117 deletions(-) create mode 100644 bindings/js/__test__/borrowed-copy-child.cjs create mode 100644 bindings/js/__test__/borrowed-copy.e2e.ts create mode 100644 bindings/js/src/com_borrowed.rs create mode 100644 crates/dynwinrt/src/com_borrowed.rs create mode 100644 crates/dynwinrt/src/com_borrowed_test_support.rs create mode 100644 crates/dynwinrt/src/com_borrowed_tests.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs create mode 100644 tools/dynwinrt-codegen/src/com_borrowed_metadata.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index aaa4a114..84e1d2e3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -73,6 +73,8 @@ jobs: "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV - name: Test core library run: cargo test -p dynwinrt + - name: Test borrowed-copy ABI on live i686 + run: cargo test -p dynwinrt --target i686-pc-windows-msvc --lib borrowed_copy - name: Test dynwinrt-codegen run: cargo test -p dynwinrt-codegen - name: Test raw union MSVC C oracle (x64) @@ -118,6 +120,12 @@ jobs: ) { throw "Classic COM compact interface support index changed" } + foreach ($name in @('IAudioRenderClient', 'IAudioCaptureClient', 'IMFMediaBuffer')) { + $copyOnly = @($support | Where-Object { $_.name -eq $name }) + if ($copyOnly.Count -ne 1 -or $copyOnly[0].safe_complete -ne 'false') { + throw "Bounded copy facade $name was incorrectly counted as complete" + } + } $expected = @{ x64 = @(412, 1431, 389) i686 = @(411, 1408, 413) @@ -135,15 +143,15 @@ jobs: } if ( $result.safeEvidence.safeComplete -ne 5697 -or - $result.safeEvidence.standardDerived -ne 5333 -or - $result.safeEvidence.exactRegistryDependent -ne 364 -or + $result.safeEvidence.standardDerived -ne 5332 -or + $result.safeEvidence.exactRegistryDependent -ne 365 -or $result.safeEvidence.metadataFactOccurrences -ne 5983 -or $result.safeEvidence.comStandardFactOccurrences -ne 26134 -or - $result.safeEvidence.registeredExactEntries -ne 506 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 506 -or - $result.safeEvidence.safeConsumedExactEntries -ne 415 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 671 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 417 + $result.safeEvidence.registeredExactEntries -ne 532 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 532 -or + $result.safeEvidence.safeConsumedExactEntries -ne 431 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 693 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 424 ) { throw "Classic COM safe evidence dependency census changed" } @@ -154,7 +162,9 @@ jobs: @($statuses | Where-Object { $_.familyId -eq 'com.ownership.v1' -and $_.safeConsumed }).Count -ne 118 -or @($statuses | Where-Object { $_.familyId -eq 'windows.borrowed-hwnd-output.v1' }).Count -ne 22 -or @($statuses | Where-Object { $_.familyId -eq 'com.enumerator-next-exception.v1' }).Count -ne 73 -or - @($statuses | Where-Object { $_.familyId -eq 'audio.conditional-output.v1' }).Count -ne 1 + @($statuses | Where-Object { $_.familyId -eq 'audio.conditional-output.v1' }).Count -ne 1 -or + @($statuses | Where-Object { $_.familyId -eq 'audio.context-effect.v1' }).Count -ne 3 -or + @($statuses | Where-Object { $_.familyId -eq 'buffers.borrowed-copy.v1' }).Count -ne 23 ) { throw "Classic COM exact registry entry validation changed" } @@ -290,6 +300,9 @@ jobs: - name: Test metadata-driven native COM one-shot completion working-directory: bindings/js run: npm run test:native-completion + - name: Test metadata-driven COM borrowed copies + working-directory: bindings/js + run: npm run test:borrowed-copy # dynwinrt-codegen (x64 + arm64) dynwinrt-codegen: diff --git a/bindings/js/__test__/borrowed-copy-child.cjs b/bindings/js/__test__/borrowed-copy-child.cjs new file mode 100644 index 00000000..13ba463b --- /dev/null +++ b/bindings/js/__test__/borrowed-copy-child.cjs @@ -0,0 +1,289 @@ +// 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 native = require('../dist/index.js') +const com = require('../dist/com.js') +const unsafe = require('../dist/com-unsafe.js') +const generatedRoot = process.env.DYNWINRT_BORROWED_GENERATED +const generated = require(join(generatedRoot, 'com', 'index.js')) +const { IAudioClient, IAudioClient3, IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer } = generated +const { DynComAudioFormat, projectAs } = com +const scenario = process.argv[2] + +native.initializeCom(scenario === 'mta' ? 1 : 0) +assert.equal(require('../dist/winrt.js').DynComBorrowedCopyPlan, undefined) +assert.equal(com.DynComBorrowedCopyPlan, undefined) + +function fixture() { + return new native.DynComBorrowedCopyTestFixture() +} +function wrap(f, kind, type) { + const value = f.object(kind) + try { + return projectAs(value, type) + } finally { + value.release() + } +} +function initialize(f, { mode = 0, flags = 0, three = false, format } = {}) { + const client = wrap(f, 'client', three ? IAudioClient3 : IAudioClient) + format ??= DynComAudioFormat.pcm(2, 48000, 16) + if (three) client.initializeSharedAudioStream(flags, 2, format, null) + else client.initialize(mode, flags, 10000n, 0n, format, null) + return client +} +function service(client, type) { + const value = client.getService(type.IID.toString()) + try { + return projectAs(value, type) + } finally { + value.release() + } +} +function count(f, prefix) { + return f.events().filter((event) => event.startsWith(prefix)).length +} + +if (scenario === 'audio') { + const f = fixture() + const client = initialize(f, { flags: 0x80000000 }) + assert.equal(client.getMixFormat().blockAlign, 1) + const render = service(client, IAudioRenderClient) + const queried = projectAs(render, IAudioRenderClient) + queried.release() + const alias = wrap(f, 'render', IAudioRenderClient) + assert.equal(render.getBuffer, undefined) + assert.equal(render.releaseBuffer, undefined) + assert.equal(render.attachFormat, undefined) + client.release() + render.release() + f.releaseOwners() + assert.equal(count(f, 'drop.client'), 0) + const data = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]) + alias.writeFramesCopy(data) + assert.deepEqual(f.bytes().subarray(0, 8), data) + assert(f.events().includes('render.acquire.2')) + assert(f.events().includes('render.release.2.0')) + alias.writeFramesCopy(Buffer.alloc(0)) + alias.writeSilence(0) + assert.equal(count(f, 'render.acquire'), 1) + assert.throws(() => alias.writeFramesCopy(Buffer.alloc(3)), /whole.*frames/i) + assert.throws(() => alias.writeSilence(9), /native.*capacity/i) + assert.throws(() => alias.writeSilence(1.5), /integer/i) + assert.throws(() => alias.writeFramesCopy(new Uint8Array(new SharedArrayBuffer(4))), /SharedArrayBuffer/i) + const detached = new Uint8Array(4) + structuredClone(detached.buffer, { transfer: [detached.buffer] }) + assert.throws(() => alias.writeFramesCopy(detached), /detached/i) + f.configure('renderNull', 1) + alias.writeSilence(2) + assert(f.events().includes('render.release.2.2')) + assert.throws(() => alias.writeFramesCopy(Buffer.alloc(4)), /null/i) + assert(f.events().includes('render.release.0.0')) + f.configure('renderNull', 0) + f.configure('renderReleaseHr', 0x80004005) + assert.throws(() => alias.writeFramesCopy(Buffer.alloc(4))) + const finalizations = count(f, 'render.release') + assert.throws(() => alias.writeFramesCopy(Buffer.alloc(4)), /poisoned/i) + assert.equal(count(f, 'render.release'), finalizations) + alias.release() + assert.equal(count(f, 'drop.client'), 1) +} else if (scenario === 'provenance') { + const f = fixture() + const external = wrap(f, 'render', IAudioRenderClient) + assert.throws(() => external.writeFramesCopy(Buffer.alloc(4)), /observed/i) + const client = wrap(f, 'client', IAudioClient) + f.configure('initializeHr', 0x80004005) + assert.throws(() => client.initialize(0, 0, 1000n, 0n, DynComAudioFormat.pcm(2, 48000, 16), null)) + f.configure('initializeHr', 0) + f.configure('externalInitialized', 1) + assert.throws(() => client.initialize(0, 0, 1000n, 0n, DynComAudioFormat.pcm(2, 48000, 16), null)) + const noProof = service(client, IAudioRenderClient) + assert.throws(() => noProof.writeFramesCopy(Buffer.alloc(4)), /observed.*initialization/i) + assert.equal(count(f, 'render.acquire'), 0) + noProof.release() + external.release() + client.release() + const supported = fixture() + const shared = initialize(supported, { three: true }) + const alias = projectAs(shared, IAudioClient) + assert.throws(() => alias.initialize(1, 0, 1000n, 0n, DynComAudioFormat.pcm(1, 48000, 8), null)) + const render = service(alias, IAudioRenderClient) + render.writeFramesCopy(Buffer.alloc(8)) + assert(supported.events().includes('render.acquire.2')) + supported.configure('serviceWrong', 1) + assert.throws(() => service(shared, IAudioCaptureClient)) + render.release() + alias.release() + shared.release() + const exclusive = fixture() + const eventClient = initialize(exclusive, { mode: 1, flags: 0x40000 }) + const eventRender = service(eventClient, IAudioRenderClient) + assert.throws(() => eventRender.writeFramesCopy(Buffer.alloc(4)), /Exclusive event-driven/i) + assert.equal(count(exclusive, 'render.acquire'), 0) + eventRender.release() + eventClient.release() +} else if (scenario === 'capture') { + const f = fixture() + const client = initialize(f, { mode: 1 }) + const capture = service(client, IAudioCaptureClient) + f.configure('captureHr', 0x08890001) + assert.equal(capture.readPacketCopy(), null) + assert.equal(count(f, 'capture.release'), 0) + f.configure('captureHr', 0) + f.configure('captureFlags', 6) + f.configure('captureNull', 1) + const silent = capture.readPacketCopy() + assert.equal(silent.kind, 'silent') + assert.equal(silent.data, undefined) + assert.equal(silent.timestampsValid, false) + assert.equal(silent.devicePosition, undefined) + assert.equal(silent.frames, 2) + f.configure('captureFlags', 1) + f.configure('captureNull', 0) + const packet = capture.readPacketCopy() + assert.equal(packet.kind, 'data') + assert.deepEqual(packet.data, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7])) + assert.equal(packet.devicePosition, 123n) + assert.equal(packet.qpcPosition, 456n) + packet.data[0] = 99 + assert.equal(f.bytes()[0], 0, 'packet data must not alias native storage') + packet.data[0] = 0 + f.configure('captureFrames', 9) + assert.throws(() => capture.readPacketCopy(), /capacity/i) + assert(f.events().includes('capture.release.0')) + f.configure('captureHr', 2) + assert.throws(() => capture.readPacketCopy(), /Unexpected acquisition HRESULT/i) + assert.throws(() => capture.readPacketCopy(), /poisoned/i) + assert.equal(count(f, 'capture.next'), 0) + assert.deepEqual(packet.data, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7])) + capture.release() + client.release() +} else if (scenario === 'media') { + const f = fixture() + const media = wrap(f, 'media', IMFMediaBuffer) + const alias = wrap(f, 'mediaUnknown', IMFMediaBuffer) + const copy = media.readCopy() + assert.deepEqual(copy, Buffer.from([0, 1, 2, 3])) + media.replaceCopy(Buffer.from([9, 8, 7])) + assert.deepEqual(alias.readCopy(), Buffer.from([9, 8, 7])) + assert.deepEqual(copy, Buffer.from([0, 1, 2, 3])) + assert.throws(() => media.replaceCopy(Buffer.alloc(17)), /capacity/i) + f.configure('mediaCurrent', 17) + assert.throws(() => media.readCopy(), /current.*maximum/i) + f.configure('mediaCurrent', 3) + f.configure('mediaSetHr', 0x80004005) + assert.throws(() => media.replaceCopy(Buffer.alloc(4))) + assert.equal(count(f, 'media.acquire'), count(f, 'media.unlock')) + f.configure('mediaSetHr', 0) + f.configure('mediaUnlockHr', 0x80004005) + assert.throws(() => media.readCopy()) + const unlocks = count(f, 'media.unlock') + media.release() + assert.throws(() => alias.readCopy(), /poisoned/i) + assert.equal(count(f, 'media.unlock'), unlocks) + alias.release() +} else if (scenario === 'wic' || scenario === 'mta') { + const f = fixture() + const bitmap = wrap(f, 'bitmap', IWICBitmap) + const rect = { x: 0, y: 0, width: 2, height: 2 } + if (scenario === 'mta') { + assert.throws(() => bitmap.readLockedBgra8Copy(rect), /STA apartment/i) + assert.equal(count(f, 'wic.acquire'), 0) + } else { + const copy = bitmap.readLockedBgra8Copy(rect) + assert.deepEqual(copy.data, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19])) + copy.data[0] = 99 + assert.equal(f.bytes()[0], 0, 'read-only bitmap copy must not write native storage') + f.configure('wicStride', 8) + f.configure('wicCount', 16) + assert.deepEqual(bitmap.readLockedBgra8Copy(rect).data, Buffer.from(Array.from({ length: 16 }, (_, i) => i))) + f.configure('wicCount', 15) + assert.throws(() => bitmap.readLockedBgra8Copy(rect), /span/i) + f.configure('wicWrongFormat', 1) + assert.throws(() => bitmap.readLockedBgra8Copy(rect), /32bpp BGRA/i) + f.configure('wicWrongFormat', 0) + f.configure('wicLockHr', 0x80004005) + assert.throws(() => bitmap.readLockedBgra8Copy(rect)) + assert.equal(count(f, 'wic.acquire'), count(f, 'wic.release')) + assert.throws(() => bitmap.readLockedBgra8Copy({ ...rect, width: 3 }), /native dimensions/i) + } + bitmap.release() +} else if (scenario === 'callback') { + const f = fixture() + const client = initialize(f) + const render = service(client, IAudioRenderClient) + let callbacks = 0 + const iid = native.WinGuid.parse('5bbdf51f-3e8d-40c5-ad0f-d8b341172d12') + const iface = native.DynCom.registerIUnknownInterface('BorrowedProbe', iid).addMethodAt( + 3, + 'Probe', + new native.DynComMethodSig(), + ) + const sink = native.DynCom.createIUnknownSink(iface, () => { + callbacks++ + return 0 + }) + native.DynCom.bindComObject(sink) + f.installCallbackProbe(sink) + render.writeFramesCopy(Buffer.alloc(4)) + assert.equal(callbacks, 0) + assert(f.events().includes('callback.rejected.true')) + render.release() + client.release() + sink.release() +} else if (scenario === 'descriptor') { + const source = readFileSync( + join(generatedRoot, 'com', 'windows', 'win32', 'media', 'media-foundation', 'IMFMediaBuffer.js'), + 'utf8', + ) + const match = source.match(/DynComBorrowedCopyPlan\.prepare\(("(?:\\.|[^"\\])*")\)/) + assert(match) + const descriptor = JSON.parse(JSON.parse(match[1])) + assert.equal(descriptor.exposure, 'owned-copy-only') + assert.equal(descriptor.access, 'read-write') + assert.equal(descriptor.owner, 'receiver') + assert.deepEqual(descriptor.acquire.storage, ['borrowed-bytes', 'out-u32', 'out-u32']) + for (const edit of [ + (d) => { + d.version++ + }, + (d) => { + d.acquire.slot++ + }, + (d) => { + d.audio_origin_required = true + }, + (d) => { + d.finalize = null + }, + (d) => { + d.metadata_sha256 = 'unknown' + }, + (d) => { + d.exposure = 'native-view' + }, + (d) => { + d.owner = 'acquired-interface' + }, + (d) => { + d.acquired_hresult = 1 + }, + (d) => { + d.empty_hresult = 0x08890001 + }, + ]) { + const changed = structuredClone(descriptor) + edit(changed) + assert.throws( + () => unsafe.DynComBorrowedCopyPlan.prepare(JSON.stringify(changed)), + /descriptor|evidence|Unsupported/i, + ) + } +} else { + throw new Error(`Unknown scenario ${scenario}`) +} +console.log(`borrowed-copy:${scenario}:ok`) diff --git a/bindings/js/__test__/borrowed-copy.e2e.ts b/bindings/js/__test__/borrowed-copy.e2e.ts new file mode 100644 index 00000000..829ccd8d --- /dev/null +++ b/bindings/js/__test__/borrowed-copy.e2e.ts @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import test from 'ava' +import { spawnSync } from 'node:child_process' +import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { join, resolve } from 'node:path' + +const packageRoot = resolve(process.cwd()) +const repositoryRoot = resolve(packageRoot, '..', '..') +const output = join(packageRoot, 'target-generated-borrowed-copy') + +test.before((t) => { + const winmd = process.env.DYNWINRT_WIN32_WINMD + t.truthy(winmd, 'Pinned DYNWINRT_WIN32_WINMD is required') + rmSync(output, { recursive: true, force: true }) + const args = [ + 'run', + '--quiet', + '-p', + 'dynwinrt-codegen', + '--', + 'generate', + '--winmd', + winmd!, + '--class-name', + 'Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.Media.Audio.IAudioClient3,Windows.Win32.Media.Audio.IAudioRenderClient,Windows.Win32.Media.Audio.IAudioCaptureClient,Windows.Win32.Graphics.Imaging.IWICBitmap,Windows.Win32.Media.MediaFoundation.IMFMediaBuffer', + '--output', + output, + ] + for (const extra of [['--dry-run'], []]) { + const generated = spawnSync('cargo', [...args, ...extra], { + cwd: repositoryRoot, + encoding: 'utf8', + windowsHide: true, + }) + t.is(generated.status, 0, `${generated.stdout}\n${generated.stderr}`) + } + const scope = join(output, 'node_modules', '@microsoft') + mkdirSync(scope, { recursive: true }) + symlinkSync(packageRoot, join(scope, 'dynwinrt'), 'junction') + writeFileSync( + join(output, 'borrowed-types.mts'), + [ + "import { IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer } from './com/index.js'", + 'declare const render: IAudioRenderClient', + 'declare const capture: IAudioCaptureClient', + 'declare const bitmap: IWICBitmap', + 'declare const media: IMFMediaBuffer', + 'render.writeFramesCopy(new Uint8Array(8)); render.writeSilence(2)', + 'const packet = capture.readPacketCopy(); if (packet?.kind === "data") packet.data?.subarray(0)', + 'const pixels: Buffer = bitmap.readLockedBgra8Copy({ x: 0, y: 0, width: 2, height: 2 }).data', + 'const bytes: Buffer = media.readCopy(); media.replaceCopy(bytes); void pixels', + '// @ts-expect-error Native acquisition is not a public escape hatch.', + 'render.getBuffer(2)', + '// @ts-expect-error No caller-asserted block alignment.', + 'render.writeFramesCopy(new Uint8Array(8), 4)', + '// @ts-expect-error Lock is available only inside owned-copy transactions.', + 'media.lock()', + '// @ts-expect-error The copy transaction has fixed READ access, no caller flags.', + 'bitmap.readLockedBgra8Copy({ x: 0, y: 0, width: 2, height: 2 }, 2)', + ].join('\n'), + ) + const types = spawnSync( + process.execPath, + [ + join(packageRoot, 'node_modules', 'typescript', 'bin', 'tsc'), + '--noEmit', + '--strict', + '--target', + 'ESNext', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + join(output, 'borrowed-types.mts'), + ], + { cwd: packageRoot, encoding: 'utf8', windowsHide: true }, + ) + t.is(types.status, 0, `${types.stdout}\n${types.stderr}`) +}) + +for (const scenario of ['audio', 'provenance', 'capture', 'media', 'wic', 'mta', 'callback', 'descriptor']) { + test.serial(`borrowed copy: ${scenario}`, (t) => { + const result = spawnSync(process.execPath, [join(packageRoot, '__test__', 'borrowed-copy-child.cjs'), scenario], { + cwd: packageRoot, + encoding: 'utf8', + windowsHide: true, + timeout: 30_000, + env: { ...process.env, DYNWINRT_BORROWED_GENERATED: output }, + }) + t.is(result.status, 0, `${result.error ?? ''}\n${result.stdout}\n${result.stderr}`) + t.regex(result.stdout, new RegExp(`borrowed-copy:${scenario}:ok`)) + }) +} + +test.after.always(() => { + rmSync(output, { recursive: true, force: true }) + rmSync(join(packageRoot, '.target-generated-borrowed-copy.dynwinrt-lock'), { force: true }) +}) diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 9cd7cefd..51bf3b5d 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -454,7 +454,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ' assert.equal(safeAudioStats().isFormatSupportedCalls, 4)', ' assert.equal(safeAudioStats().getMixFormatCalls, 1)', ' assert.equal(safeAudioStats().getServiceCalls, 1)', - ' assert.equal(safeAudioStats().currentRefCount, 2)', + ' // The observed initialization sidecar pins one canonical IUnknown in addition to the two wrappers.', + ' assert.equal(safeAudioStats().currentRefCount, 3)', ' safeAudioWrapper.release()', ' safeAudioFake.release()', ' assert.equal(safeAudioStats().currentRefCount, 0)', diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 0e52f8b8..ac820f87 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -170,6 +170,7 @@ test('package facades exactly partition native exports', (t) => { ]) const unsafeComNames = new Set([ ...safeComNames, + 'DynComBorrowedCopyPlan', 'DynCom', 'DynComDispatchInvokeResult', 'DynComInterface', diff --git a/bindings/js/package.json b/bindings/js/package.json index 22e568ea..b3d0aff1 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -93,6 +93,7 @@ "test": "npm run test:types && ava", "test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts", "test:native-completion": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/native-completion.e2e.ts", + "test:borrowed-copy": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/borrowed-copy.e2e.ts", "test:types": "npm run test:types:index && npm run test:types:raw", "test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts", "test:types:raw": "tsc --noEmit --project __test__/types/tsconfig.json", diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index daf19256..ce74b538 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -56,6 +56,7 @@ const opaqueComDeclarations = [ ] const comUnsafeExports = new Set([ ...comExports, + 'DynComBorrowedCopyPlan', 'DynCom', 'DynComDispatchInvokeResult', 'DynComInterface', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index debc22c3..f94cf16b 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -755,6 +755,7 @@ fn typed_buffer_info( "DynCom.buffer(): expected Buffer or TypedArray", )); } + let mut typed_array_type = 0; let mut length = 0usize; let mut data = std::ptr::null_mut(); @@ -803,6 +804,33 @@ fn typed_buffer_info( }) } +pub(super) fn stage_copy_bytes(value: Unknown) -> napi::Result> { + let info = typed_buffer_info(value.value().env, value.value().value)?; + if info.typed_array_type != napi::sys::TypedarrayType::uint8_array as i32 { + return Err(napi::Error::from_reason( + "Owned-copy input must be Buffer or Uint8Array", + )); + } + if info.byte_length > 64 * 1024 * 1024 { + return Err(napi::Error::from_reason( + "Owned-copy input exceeds the 64 MiB safety cap", + )); + } + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(info.byte_length) + .map_err(|_| napi::Error::from_reason("Unable to stage owned copy"))?; + if info.byte_length != 0 { + if info.pointer == 0 { + return Err(napi::Error::from_reason("Owned-copy input storage is null")); + } + bytes.extend_from_slice(unsafe { + std::slice::from_raw_parts(info.pointer as *const u8, info.byte_length) + }); + } + Ok(bytes) +} + fn com_buffer(value: Unknown) -> napi::Result { let env = value.value().env; let raw = value.value().value; @@ -1214,7 +1242,9 @@ fn adopt_com_pointer( value: &mut DynWinRTValue, iid: Option<&WinGUID>, ) -> napi::Result { + value.ensure_existing_com_apartment()?; let ptr = take_native_output_pointer(value, PointerProvenance::ComOutput, "COM interface")?; + let binding = value.6.take(); if ptr.is_null() { return Err(napi::Error::from_reason( "Owned COM interface output was null", @@ -1228,11 +1258,17 @@ fn adopt_com_pointer( .map_err(|error| napi::Error::from_reason(error.message())) .and_then(|mut value| { value.bind_current_com_apartment()?; + if binding.is_some() { + value.6 = binding; + } Ok(value) }), None => { let mut value = DynWinRTValue::new(adopted); value.bind_current_com_apartment()?; + if binding.is_some() { + value.6 = binding; + } Ok(value) } } @@ -2019,6 +2055,12 @@ impl DynComMethodSig { Self(dynwinrt::com::MethodSignature::new(&TABLE)) } + #[napi] + pub fn with_context_effect(&self, descriptor: String) -> napi::Result { + let effect = super::com_borrowed::parse_effect(&descriptor)?; + Ok(Self(self.0.clone().with_context_effect(effect))) + } + #[napi] pub fn add_in(&self, typ: &DynComType) -> Self { Self(self.0.clone().add_in(typ.0.clone())) @@ -2342,9 +2384,57 @@ impl DynComDispatchInvokeResult { #[napi] impl DynComMethodHandle { + fn invoke_managed( + &self, + obj: &DynWinRTValue, + args: Vec<&DynWinRTValue>, + ) -> napi::Result> { + if !self.0.has_context_effect() { + obj.ensure_tracked_com_idle()?; + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))? + .as_raw(); + return with_com_invocation_args(&args, |args| { + unsafe { self.0.invoke_values_with_output_kinds(raw, args) }.map_err(com_error) + }) + .map(|values| { + values + .into_iter() + .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) + .collect() + }); + } + let context = obj.com_context()?; + let view = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))? + .clone(); + let result = with_com_invocation_args(&args, |args| { + unsafe { dynwinrt::com::borrowed::invoke_managed(&self.0, &context, &view, args) } + .map_err(com_error) + })?; + Ok( + result + .values + .into_iter() + .map(|(value, kind)| { + let mut value = DynWinRTValue::from_com_value(value, kind); + if let Some(context) = result.output_context.as_ref() { + value.retain_com_context(context.clone())?; + } + Ok(value) + }) + .collect::>>()?, + ) + } + #[napi] pub fn get_string(&self, obj: &DynWinRTValue) -> napi::Result { obj.ensure_com_apartment()?; + obj.ensure_tracked_com_idle()?; let raw = obj .0 .as_object() @@ -2367,20 +2457,12 @@ impl DynComMethodHandle { "invoke() cannot discard multiple COM results; use invokeAll()", )); } - let raw = obj - .0 - .as_object() - .ok_or_else(|| napi::Error::from_reason("invoke() requires a COM object"))? - .as_raw(); - let mut results = with_com_invocation_args(&args, |args| { - unsafe { self.0.invoke_values_with_output_kinds(raw, args) } - .map_err(|error| napi::Error::from_reason(error.message())) - })?; - let (value, kind) = results.drain(..).next().unwrap_or(( - dynwinrt::com::Value::WinRt(dynwinrt::WinRTValue::I32(0)), - dynwinrt::com::PointerOutputKind::None, - )); - Ok(DynWinRTValue::from_com_value(value, kind)) + let mut results = self.invoke_managed(obj, args)?; + Ok( + results + .pop() + .unwrap_or_else(|| DynWinRTValue::new(dynwinrt::WinRTValue::I32(0))), + ) } #[napi] @@ -2389,22 +2471,7 @@ impl DynComMethodHandle { obj: &DynWinRTValue, args: Vec<&DynWinRTValue>, ) -> napi::Result> { - obj.ensure_com_apartment()?; - let raw = obj - .0 - .as_object() - .ok_or_else(|| napi::Error::from_reason("invokeAll() requires a COM object"))? - .as_raw(); - with_com_invocation_args(&args, |args| { - unsafe { self.0.invoke_values_with_output_kinds(raw, args) } - .map_err(|error| napi::Error::from_reason(error.message())) - }) - .map(|results| { - results - .into_iter() - .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) - .collect() - }) + self.invoke_managed(obj, args) } #[napi] @@ -2414,6 +2481,7 @@ impl DynComMethodHandle { args: Vec<&DynWinRTValue>, ) -> napi::Result { obj.ensure_com_apartment()?; + obj.ensure_tracked_com_idle()?; let raw = obj .0 .as_object() @@ -2471,6 +2539,7 @@ impl DynComRaw { ) -> napi::Result> { dispatch.entered.set(false); obj.ensure_com_apartment()?; + obj.ensure_tracked_com_idle()?; let raw = obj .0 .as_object() diff --git a/bindings/js/src/com_borrowed.rs b/bindings/js/src/com_borrowed.rs new file mode 100644 index 00000000..e6d77bfa --- /dev/null +++ b/bindings/js/src/com_borrowed.rs @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt::com::borrowed::{ + BorrowOwner, BorrowedCopyContract, BorrowedCopyPlan, CallContract, ContextEffect, CopyKind, + Extent, Finalization, MemoryAccess, Storage, +}; +use napi::bindgen_prelude::{BigInt, Buffer, Unknown}; +use napi_derive::napi; +use serde::Deserialize; +use windows::core::GUID; + +use super::{com, DynWinRTValue, TABLE}; + +const METADATA_HASH: &str = "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; + +fn invalid(message: impl Into) -> napi::Error { + napi::Error::from_reason(message) +} + +fn native_error(error: dynwinrt::Error) -> napi::Error { + invalid(error.message()) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EffectDescriptor { + version: u32, + effect: String, + metadata_sha256: String, + fingerprint: String, +} + +pub(super) fn parse_effect(value: &str) -> napi::Result { + let value: EffectDescriptor = serde_json::from_str(value) + .map_err(|e| invalid(format!("Invalid audio context descriptor: {e}")))?; + let (effect, fingerprint) = match value.effect.as_str() { + "audio-initialize" => ( + ContextEffect::AudioInitialize, + "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", + ), + "audio-initialize-shared" => ( + ContextEffect::AudioInitializeShared, + "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", + ), + "audio-get-service" => ( + ContextEffect::AudioGetService, + "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", + ), + _ => return Err(invalid("Unsupported audio context effect")), + }; + if value.version != 1 + || value.metadata_sha256 != METADATA_HASH + || value.fingerprint != fingerprint + { + return Err(invalid("Audio context evidence drift; regenerate bindings")); + } + Ok(effect) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Descriptor { + version: u32, + metadata_sha256: String, + access: String, + exposure: String, + owner: String, + acquired_hresult: i32, + empty_hresult: Option, + kind: String, + receiver: String, + acquire: CallDescriptor, + queries: Vec, + finalize: Option, + extent: String, + finalization: String, + sta_only: bool, + audio_origin_required: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CallDescriptor { + iid: String, + slot: usize, + storage: Vec, +} + +impl CallDescriptor { + fn contract(self) -> napi::Result { + Ok(CallContract { + iid: GUID::try_from(self.iid.as_str()).map_err(|_| invalid("Invalid borrowed-copy IID"))?, + slot: self.slot, + storage: self + .storage + .iter() + .map(|value| match value.as_str() { + "in-u32" => Ok(Storage::InU32), + "in-rect" => Ok(Storage::InRect), + "out-u32" => Ok(Storage::OutU32), + "out-u64" => Ok(Storage::OutU64), + "out-guid" => Ok(Storage::OutGuid), + "borrowed-bytes" => Ok(Storage::BorrowedBytes), + "owned-interface" => Ok(Storage::OwnedInterface), + _ => Err(invalid("Unsupported borrowed-copy native storage")), + }) + .collect::>()?, + }) + } +} + +fn parse_contract(value: &str) -> napi::Result { + let value: Descriptor = serde_json::from_str(value) + .map_err(|e| invalid(format!("Invalid borrowed-copy descriptor: {e}")))?; + if value.version != 1 + || value.metadata_sha256 != METADATA_HASH + || value.exposure != "owned-copy-only" + { + return Err(invalid( + "Borrowed-copy descriptor version/evidence/access drift", + )); + } + let kind = match value.kind.as_str() { + "audio-render" => CopyKind::AudioRender, + "audio-capture" => CopyKind::AudioCapture, + "bitmap-bgra8" => CopyKind::BitmapBgra8, + "media-buffer" => CopyKind::MediaBuffer, + _ => return Err(invalid("Unsupported borrowed-copy kind")), + }; + let extent = match value.extent.as_str() { + "initialized-frames" => Extent::InitializedFrames, + "capture-packet-frames" => Extent::CapturePacketFrames, + "native-bgra8-rows" => Extent::NativeBgra8Rows, + "native-current-and-max" => Extent::NativeCurrentAndMax, + _ => return Err(invalid("Unsupported borrowed-copy native extent")), + }; + let finalization = match value.finalization.as_str() { + "render-full-or-zero" => Finalization::RenderFullOrZero, + "capture-full-or-zero" => Finalization::CaptureFullOrZero, + "release-lock-reference" => Finalization::ReleaseLockReference, + "unlock" => Finalization::Unlock, + _ => return Err(invalid("Unsupported borrowed-copy finalizer")), + }; + let access = match value.access.as_str() { + "read" => MemoryAccess::Read, + "write" => MemoryAccess::Write, + "read-write" => MemoryAccess::ReadWrite, + _ => return Err(invalid("Unsupported borrowed-copy access")), + }; + let owner = match value.owner.as_str() { + "receiver" => BorrowOwner::Receiver, + "audio-service-origin" => BorrowOwner::AudioServiceOrigin, + "acquired-interface" => BorrowOwner::AcquiredInterface, + _ => return Err(invalid("Unsupported borrowed-copy owner")), + }; + Ok(BorrowedCopyContract { + kind, + extent, + finalization, + receiver: GUID::try_from(value.receiver.as_str()) + .map_err(|_| invalid("Invalid borrowed-copy receiver IID"))?, + acquire: value.acquire.contract()?, + queries: value + .queries + .into_iter() + .map(CallDescriptor::contract) + .collect::>()?, + finalize: value.finalize.map(CallDescriptor::contract).transpose()?, + sta_only: value.sta_only, + audio_origin_required: value.audio_origin_required, + access, + owner, + acquired_hresult: value.acquired_hresult, + empty_hresult: value.empty_hresult, + }) +} + +#[napi] +pub struct DynComBorrowedCopyPlan(BorrowedCopyPlan); + +#[napi(object)] +pub struct DynComCapturePacketCopy { + pub kind: String, + pub data: Option, + pub frames: u32, + pub flags: u32, + pub timestamps_valid: bool, + pub device_position: Option, + pub qpc_position: Option, +} + +#[napi(object)] +pub struct DynComBitmapCopy { + pub data: Buffer, + pub width: u32, + pub height: u32, +} + +#[napi] +impl DynComBorrowedCopyPlan { + #[napi] + pub fn prepare(descriptor: String) -> napi::Result { + BorrowedCopyPlan::prepare(&TABLE, parse_contract(&descriptor)?) + .map(Self) + .map_err(native_error) + } +} + +#[cfg(feature = "test-hooks")] +#[napi] +pub struct DynComBorrowedCopyTestFixture { + fixture: dynwinrt::com::borrowed::testing::CopyFixture, + owner: std::thread::ThreadId, +} + +#[cfg(feature = "test-hooks")] +impl DynComBorrowedCopyTestFixture { + fn check(&self) -> napi::Result<()> { + if self.owner != std::thread::current().id() { + return Err(invalid("Borrowed-copy fixture used on a different thread")); + } + Ok(()) + } +} + +#[cfg(feature = "test-hooks")] +#[napi] +impl DynComBorrowedCopyTestFixture { + #[napi(constructor)] + pub fn new() -> Self { + Self { + fixture: Default::default(), + owner: std::thread::current().id(), + } + } + + #[napi] + pub fn object(&self, kind: String) -> napi::Result { + self.check()?; + let object = self.fixture.object(&kind).map_err(native_error)?; + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Object(object)); + value.bind_current_com_apartment()?; + Ok(value) + } + + #[napi] + pub fn configure(&self, key: String, value: u32) -> napi::Result<()> { + self.check()?; + self.fixture.configure(&key, value).map_err(native_error) + } + + #[napi] + pub fn events(&self) -> napi::Result> { + self.check()?; + Ok(self.fixture.events()) + } + + #[napi] + pub fn bytes(&self) -> napi::Result { + self.check()?; + Ok(self.fixture.bytes().into()) + } + + #[napi] + pub fn release_owners(&mut self) -> napi::Result<()> { + self.check()?; + self.fixture.release_owners(); + Ok(()) + } + + #[napi] + pub fn install_callback_probe(&self, object: &DynWinRTValue) -> napi::Result<()> { + self.check()?; + object.ensure_com_apartment()?; + let object = object + .0 + .as_object() + .ok_or_else(|| invalid("Probe requires a managed COM sink"))?; + self + .fixture + .install_callback_probe(object) + .map_err(native_error) + } +} + +#[napi] +impl DynComBorrowedCopyPlan { + #[napi] + pub fn write_frames_copy( + &self, + object: &DynWinRTValue, + #[napi(ts_arg_type = "Buffer | Uint8Array")] data: Unknown, + ) -> napi::Result<()> { + let bytes = com::stage_copy_bytes(data)?; + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .write_frames_copy(&context, &view, &bytes) + .map_err(native_error) + } + + #[napi] + pub fn write_silence(&self, object: &DynWinRTValue, frames: f64) -> napi::Result<()> { + if !frames.is_finite() || frames < 0.0 || frames > u32::MAX as f64 || frames.fract() != 0.0 { + return Err(invalid("Silence frame count must be a u32 integer")); + } + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .write_silence(&context, &view, frames as u32) + .map_err(native_error) + } + + #[napi] + pub fn read_packet_copy( + &self, + object: &DynWinRTValue, + ) -> napi::Result> { + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .read_packet_copy(&context, &view) + .map(|packet| { + packet.map(|packet| DynComCapturePacketCopy { + kind: if packet.data.is_some() { + "data" + } else { + "silent" + } + .into(), + data: packet.data.map(Buffer::from), + frames: packet.frames, + flags: packet.flags, + timestamps_valid: packet.device_position.is_some(), + device_position: packet.device_position.map(BigInt::from), + qpc_position: packet.qpc_position.map(BigInt::from), + }) + }) + .map_err(native_error) + } + + #[napi] + pub fn read_copy(&self, object: &DynWinRTValue) -> napi::Result { + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .read_copy(&context, &view) + .map(Buffer::from) + .map_err(native_error) + } + + #[napi] + pub fn replace_copy( + &self, + object: &DynWinRTValue, + #[napi(ts_arg_type = "Buffer | Uint8Array")] data: Unknown, + ) -> napi::Result<()> { + let bytes = com::stage_copy_bytes(data)?; + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .replace_copy(&context, &view, &bytes) + .map_err(native_error) + } + + #[napi] + pub fn read_locked_bgra8_copy( + &self, + object: &DynWinRTValue, + rect: Vec, + ) -> napi::Result { + if rect.len() != 4 + || rect + .iter() + .any(|v| !v.is_finite() || v.fract() != 0.0 || *v < i32::MIN as f64 || *v > i32::MAX as f64) + { + return Err(invalid( + "Bitmap rectangle requires exactly four i32 integers", + )); + } + let rect = [ + rect[0] as i32, + rect[1] as i32, + rect[2] as i32, + rect[3] as i32, + ]; + let context = object.com_context()?; + let view = object + .0 + .as_object() + .ok_or_else(|| invalid("COM object is released"))? + .clone(); + self + .0 + .read_locked_bgra8_copy(&context, &view, rect) + .map(|copy| DynComBitmapCopy { + data: copy.data.into(), + width: copy.width, + height: copy.height, + }) + .map_err(native_error) + } +} diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 9b7b8758..be370c91 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -29,6 +29,7 @@ pub use com_raw::{ DynComRawStructLayout, DynComRawUnionLayout, }; mod async_promise; +mod com_borrowed; mod com_completion; #[cfg(feature = "test-hooks")] mod com_completion_test_hooks; @@ -966,12 +967,72 @@ pub struct DynWinRTValue( Option, Option, ); +// COM carriers check their owner before accessing/cloning the private Rc sidecar. +// Off-thread destruction leaks that sidecar and its COM owners instead of +// changing an Rc count or releasing an apartment reference on the wrong thread. unsafe impl Send for DynWinRTValue {} unsafe impl Sync for DynWinRTValue {} #[derive(Clone)] struct ComApartmentBinding { owner_thread: std::thread::ThreadId, + context: ComContextSlot, + identity_error: Option, +} + +type ComContextSlot = std::rc::Rc>>; + +thread_local! { + // Empty slots are pinned by their managed carriers' owned interface refs. + // Populated slots additionally own the core canonical-identity sidecar. + // Sharing slots at carrier creation keeps pre-existing independent aliases + // from forgetting provenance or poison when the first copier is released. + static COM_CONTEXT_SLOTS: std::cell::RefCell>>>> = + std::cell::RefCell::new(std::collections::HashMap::new()); +} + +impl ComApartmentBinding { + fn for_object(object: &IUnknown) -> Self { + let owner_thread = std::thread::current().id(); + let mut pointer = std::ptr::null_mut(); + let hr = unsafe { object.query(&IUnknown::IID, &mut pointer) }; + if hr.is_err() || pointer.is_null() { + return Self { + owner_thread, + context: Default::default(), + identity_error: Some(format!( + "COM canonical identity is unavailable (HRESULT 0x{:08X}, null={})", + hr.0 as u32, + pointer.is_null() + )), + }; + } + let canonical = unsafe { IUnknown::from_raw(pointer) }; + let key = canonical.as_raw().addr(); + let context = COM_CONTEXT_SLOTS.with(|slots| { + let mut slots = slots.borrow_mut(); + if let Some(slot) = slots.get(&key).and_then(std::rc::Weak::upgrade) { + return slot; + } + slots.retain(|_, slot| slot.strong_count() != 0); + let slot: ComContextSlot = Default::default(); + slots.insert(key, std::rc::Rc::downgrade(&slot)); + slot + }); + Self { + owner_thread, + context, + identity_error: None, + } + } + + fn ensure_identity(&self) -> napi::Result<()> { + if let Some(error) = &self.identity_error { + return Err(napi::Error::from_reason(error.clone())); + } + Ok(()) + } } impl DynWinRTValue { @@ -988,24 +1049,28 @@ impl DynWinRTValue { } pub(crate) fn bind_current_com_apartment(&mut self) -> napi::Result<()> { + let current = std::thread::current().id(); + if self + .6 + .as_ref() + .is_some_and(|binding| binding.owner_thread != current) + { + return Err(napi::Error::from_reason( + "Classic COM object is already bound to a different apartment thread", + )); + } if self.0.as_object().is_none() { return Err(napi::Error::from_reason( "Classic COM apartment binding requires a managed COM object", )); } - let current = std::thread::current().id(); - match &self.6 { - Some(binding) if binding.owner_thread != current => Err(napi::Error::from_reason( - "Classic COM object is already bound to a different apartment thread", - )), - Some(_) => Ok(()), - None => { - self.6 = Some(ComApartmentBinding { - owner_thread: current, - }); - Ok(()) - } + if self.6.is_none() { + self.6 = Some(ComApartmentBinding::for_object( + &self.0.as_object().expect("checked COM object"), + )); } + self.existing_com_context()?; + Ok(()) } pub(crate) fn ensure_com_apartment(&self) -> napi::Result<()> { @@ -1029,6 +1094,73 @@ impl DynWinRTValue { } } + fn com_context(&self) -> napi::Result { + self.ensure_com_apartment()?; + let binding = self.6.as_ref().expect("checked apartment"); + binding.ensure_identity()?; + if let Some(context) = binding.context.borrow().as_ref() { + return Ok(context.clone()); + } + let object = self + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM object is released"))?; + let context = dynwinrt::com::borrowed::Identity::for_object(&object) + .map_err(|error| napi::Error::from_reason(error.message()))?; + *binding.context.borrow_mut() = Some(context.clone()); + Ok(context) + } + + fn existing_com_context(&self) -> napi::Result> { + self.ensure_com_apartment()?; + let binding = self.6.as_ref().expect("checked apartment"); + binding.ensure_identity()?; + if let Some(context) = binding.context.borrow().as_ref() { + return Ok(Some(context.clone())); + } + if !dynwinrt::com::borrowed::has_live_contexts() + .map_err(|error| napi::Error::from_reason(error.message()))? + { + return Ok(None); + } + let object = self + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM object is released"))?; + let context = dynwinrt::com::borrowed::Identity::lookup(&object) + .map_err(|error| napi::Error::from_reason(error.message()))?; + *binding.context.borrow_mut() = context.clone(); + Ok(context) + } + + fn ensure_tracked_com_idle(&self) -> napi::Result<()> { + if let Some(context) = self.existing_com_context()? { + context + .ensure_idle() + .map_err(|error| napi::Error::from_reason(error.message()))?; + } + Ok(()) + } + + fn retain_com_context(&mut self, context: dynwinrt::com::borrowed::Identity) -> napi::Result<()> { + let object = match &self.0 { + dynwinrt::WinRTValue::Object(object) => object, + dynwinrt::WinRTValue::RawPtr(pointer) if self.2 == com::PointerProvenance::ComOutput => { + unsafe { IUnknown::from_raw_borrowed(pointer) } + .ok_or_else(|| napi::Error::from_reason("COM context output is null"))? + } + _ => { + return Err(napi::Error::from_reason( + "COM context requires an owned interface output", + )) + } + }; + let binding = ComApartmentBinding::for_object(object); + *binding.context.borrow_mut() = Some(context); + self.6 = Some(binding); + self.6.as_ref().unwrap().ensure_identity() + } + fn with_pointer_owner(value: dynwinrt::WinRTValue, owner: com::NativePointerOwner) -> Self { Self( value, @@ -1102,9 +1234,11 @@ impl DynWinRTValue { } else { com::PointerProvenance::None }; - let apartment = matches!(value, dynwinrt::WinRTValue::Object(_)).then(|| ComApartmentBinding { - owner_thread: std::thread::current().id(), - }); + let apartment = if let dynwinrt::WinRTValue::Object(object) = &value { + Some(ComApartmentBinding::for_object(object)) + } else { + None + }; Self(value, None, provenance, None, None, None, apartment) } @@ -1314,6 +1448,9 @@ impl Drop for DynWinRTValue { { let value = mem::replace(&mut self.0, dynwinrt::WinRTValue::Null); mem::forget(value); + if let Some(binding) = self.6.take() { + mem::forget(binding); + } return; } // After Application.Start returns, XAML has already torn down its thread @@ -1330,6 +1467,9 @@ impl Drop for DynWinRTValue { if let Some(value) = &mut self.5 { value.leak_for_shutdown(); } + if let Some(binding) = self.6.take() { + mem::forget(binding); + } } else { let _ = self.release_native_pointer_output(); } @@ -2916,6 +3056,11 @@ fn invoke_direct_js_callback( build_args: impl FnOnce(napi::sys::napi_env) -> napi::Result>, parse_result: impl FnOnce(napi::sys::napi_env, napi::sys::napi_value) -> napi::Result, ) -> napi::Result { + if dynwinrt::com::borrowed::callbacks_suppressed() { + return Err(napi::Error::from_reason( + "JavaScript callbacks are forbidden during a native borrowed-copy transaction", + )); + } if direct.lifecycle.is_closing() { return Err(napi::Error::from_reason( "Cannot invoke a callback while the Node environment is closing", diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index de2a977f..5b92adc4 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -53,6 +53,11 @@ features = [ criterion = { version = "0.5", features = ["html_reports"] } futures = "0.3.31" tokio = { version = "1.49.0", features = ["macros", "rt"] } + +[dev-dependencies.windows] +version = ">=0.59, <=0.62" +features = ["Win32_Graphics_Imaging", "Win32_Media_MediaFoundation"] + [[bench]] name = "bench" harness = false diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index ce8ec4a8..bb5bd6dd 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -29,6 +29,9 @@ use crate::{ #[path = "com_automation.rs"] pub(crate) mod automation; +#[path = "com_borrowed.rs"] +#[doc(hidden)] +pub mod borrowed; #[path = "com_completion.rs"] #[doc(hidden)] pub mod completion; @@ -5855,6 +5858,7 @@ pub struct MethodSignature { return_plan: ComReturnPlan, enumerator_next_vtable_index: Option, canonical_format_etc: Option, + context_effect: Option, } #[derive(Debug, Clone, Copy)] @@ -5871,6 +5875,7 @@ impl MethodSignature { return_plan: ComReturnPlan::HResult, enumerator_next_vtable_index: None, canonical_format_etc: None, + context_effect: None, } } @@ -6127,6 +6132,15 @@ impl MethodSignature { method_name: &str, vtable_index: usize, ) -> result::Result<()> { + if let Some(effect) = self.context_effect { + borrowed::validate_effect_signature( + self, + effect, + interface_iid, + method_name, + vtable_index, + )?; + } const IID_IDISPATCH: GUID = GUID::from_u128(0x00020400_0000_0000_c000_000000000046); if matches!(self.return_plan, ComReturnPlan::EnumeratorNextHResult) { let exact_contract = interface_iid != GUID::zeroed() @@ -6208,6 +6222,13 @@ impl MethodSignature { } fn build(self, vtable_index: usize) -> result::Result { + let context_hresult_plan = if self.context_effect.is_some() { + let mut captured = self.clone(); + captured.context_effect = None; + Some(captured.preserve_hresult().build(vtable_index)?.plan) + } else { + None + }; for parameter in &self.parameters { parameter.typ.validate_outbound_aggregate_policy()?; } @@ -6305,6 +6326,8 @@ impl MethodSignature { Ok(RegisteredMethod { plan: ComCallPlan::new(native, self.parameters, self.return_plan), callback_plan, + context_effect: self.context_effect, + context_hresult_plan, }) } } @@ -6787,6 +6810,8 @@ fn require_direction( struct RegisteredMethod { plan: ComCallPlan, callback_plan: CallbackMethodPlan, + context_effect: Option, + context_hresult_plan: Option, } type RegisteredMethods = BTreeMap)>; @@ -6893,6 +6918,11 @@ impl Interface { let mut backends = Vec::with_capacity(methods.len()); let mut plans = Vec::with_capacity(methods.len()); for (index, (&slot, (name, method))) in methods.iter().enumerate() { + if method.context_effect.is_some() { + return Err(invalid_argument( + "Context-effect methods cannot be implemented by a language callback", + )); + } if slot != self.base_slot + index { return Err(invalid_argument(format!( "COM sink method '{name}' uses non-contiguous vtable slot {slot}", @@ -6942,6 +6972,10 @@ impl std::fmt::Debug for MethodHandle { } impl MethodHandle { + pub fn has_context_effect(&self) -> bool { + self.0.context_effect.is_some() + } + pub fn result_count(&self) -> usize { self.0.plan.results.len() } diff --git a/crates/dynwinrt/src/com_borrowed.rs b/crates/dynwinrt/src/com_borrowed.rs new file mode 100644 index 00000000..5ba05f77 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed.rs @@ -0,0 +1,1426 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! COM-local owned-copy transactions. Native storage never leaves a transaction. +//! Interface-specific calls use completed MethodHandles/libffi; standard +//! IUnknown ownership and COM apartment queries use shared infrastructure. + +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + ffi::c_void, + ptr, + rc::{Rc, Weak}, + sync::{Arc, LazyLock, Mutex, Weak as SyncWeak}, + thread::{self, ThreadId}, +}; + +use windows::Win32::System::Com::{APTTYPE_MAINSTA, APTTYPE_STA, CoGetApartmentType}; +use windows_core::{GUID, HRESULT, IUnknown, Interface as _}; + +use super::{AudioFormatValue, InterfaceBase, MethodHandle, MethodSignature, Type, Value}; +use crate::{MetadataTable, WinRTValue, result}; + +#[cfg(any(test, feature = "test-hooks"))] +#[path = "com_borrowed_test_support.rs"] +pub mod testing; +#[cfg(test)] +#[path = "com_borrowed_tests.rs"] +mod tests; + +pub const AUDIO_CLIENT: GUID = GUID::from_u128(0x1cb9ad4c_dbfa_4c32_b178_c2f568a703b2); +pub const AUDIO_CLIENT2: GUID = GUID::from_u128(0x726778cd_f60a_4eda_82de_e47610cd78aa); +pub const AUDIO_CLIENT3: GUID = GUID::from_u128(0x7ed4ee07_8e67_4cd4_8c1a_2b7a5987ad42); +pub const AUDIO_RENDER: GUID = GUID::from_u128(0xf294acfc_3146_4483_a7bf_addca7c260e2); +pub const AUDIO_CAPTURE: GUID = GUID::from_u128(0xc8adbd64_e71e_48a0_a4de_185c395cd317); +pub const WIC_BITMAP: GUID = GUID::from_u128(0x00000121_a8f2_4877_ba0a_fd2b6645fb94); +pub const WIC_LOCK: GUID = GUID::from_u128(0x00000123_a8f2_4877_ba0a_fd2b6645fb94); +pub const MF_BUFFER: GUID = GUID::from_u128(0x045fa593_8799_42b8_bc8d_8968c6453507); +const BGRA8: GUID = GUID::from_u128(0x6fddc324_4e03_4bfe_b185_3d77768dc90f); +const BUFFER_EMPTY: i32 = 0x08890001; +const SILENT: u32 = 2; +const TIMESTAMP_ERROR: u32 = 4; +const EVENT_CALLBACK: u32 = 0x00040000; +const MAX_COPY_BYTES: usize = 64 * 1024 * 1024; + +fn error(message: impl AsRef) -> result::Error { + super::invalid_argument(message.as_ref()) +} + +thread_local! { + // An address is a key only while IdentityInner owns its canonical IUnknown. + // Weak entries neither keep native objects alive nor form client/service cycles. + static IDENTITIES: RefCell>> = RefCell::new(HashMap::new()); + static COPY_DEPTH: Cell = const { Cell::new(0) }; +} + +// Only pointer-free ownership tokens cross threads. All native references and +// mutable lifecycle/provenance state remain in the owner-thread Rc sidecar. +static IDENTITY_OWNERS: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn identity_owner(key: usize, claim: bool) -> result::Result>> { + let mut owners = IDENTITY_OWNERS.lock().map_err(|poison| { + drop(poison); + error("COM identity owner registry is poisoned") + })?; + if let Some(owner) = owners.get(&key).and_then(SyncWeak::upgrade) { + if *owner != thread::current().id() { + drop(owners); + return Err(error( + "COM borrowed-copy identity belongs to a different apartment thread", + )); + } + return Ok(Some(owner)); + } + if !claim { + return Ok(None); + } + owners.retain(|_, owner| owner.strong_count() != 0); + let owner = Arc::new(thread::current().id()); + owners.insert(key, Arc::downgrade(&owner)); + Ok(Some(owner)) +} + +pub fn callbacks_suppressed() -> bool { + COPY_DEPTH.with(|depth| depth.get() != 0) +} + +pub fn has_live_contexts() -> result::Result { + let owners = IDENTITY_OWNERS.lock().map_err(|poison| { + drop(poison); + error("COM identity owner registry is poisoned") + })?; + Ok(owners.values().any(|owner| owner.strong_count() != 0)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + Idle, + Acquiring, + Active, + Finalizing, + Poisoned, +} + +struct InitializedAudio { + format: AudioFormatValue, + share_mode: i32, + flags: u32, + block_align: Option, +} + +struct ServiceOrigin { + client: Identity, + // The canonical unknown is identity, not necessarily an IAudioClient view. + client_view: Rc, +} + +struct IdentityInner { + state: Cell, + initialized: RefCell>, + origin: RefCell>, + services: Cell, + same_identity_client_view: RefCell>>, + _owner_token: Arc, + // Drop the pointer-free registry token before this last field. An active + // address-key token can therefore never outlive the canonical native owner. + _canonical: IUnknown, +} + +/// Private sidecar retained by managed COM carriers, never by a global strong map. +/// Not Send/Sync: no apartment reference or Rc operation is allowed off its owner. +/// +/// ```compile_fail +/// fn require_send() {} +/// require_send::(); +/// ``` +/// ```compile_fail +/// fn require_sync() {} +/// require_sync::(); +/// ``` +#[derive(Clone)] +pub struct Identity { + owner: ThreadId, + inner: Rc, +} + +type AudioOwner = (Identity, Rc); + +impl Identity { + pub fn lookup(object: &IUnknown) -> result::Result> { + if !has_live_contexts()? { + return Ok(None); + } + let canonical = query(object, &IUnknown::IID)?; + let _owner = identity_owner(canonical.as_raw().addr(), false)?; + let inner = IDENTITIES.with(|entries| { + entries + .borrow() + .get(&canonical.as_raw().addr()) + .and_then(Weak::upgrade) + }); + Ok(inner.map(|inner| Self { + owner: thread::current().id(), + inner, + })) + } + + pub fn for_object(object: &IUnknown) -> result::Result { + let canonical = query(object, &IUnknown::IID)?; + let key = canonical.as_raw().addr(); + let existing = + IDENTITIES.with(|entries| entries.borrow().get(&key).and_then(Weak::upgrade)); + let inner = if let Some(existing) = existing { + existing + } else { + let owner_token = identity_owner(key, true)?.expect("claimed identity owner"); + let inner = Rc::new(IdentityInner { + _canonical: canonical, + state: Cell::new(State::Idle), + initialized: RefCell::new(None), + origin: RefCell::new(None), + services: Cell::new(0), + same_identity_client_view: RefCell::new(None), + _owner_token: owner_token, + }); + IDENTITIES.with(|entries| { + let mut entries = entries.borrow_mut(); + entries.retain(|_, entry| entry.strong_count() != 0); + entries.insert(key, Rc::downgrade(&inner)); + }); + inner + }; + Ok(Self { + owner: thread::current().id(), + inner, + }) + } + + pub fn ensure_thread(&self) -> result::Result<()> { + if self.owner != thread::current().id() { + return Err(error( + "Borrowed-copy context used from a different apartment thread", + )); + } + Ok(()) + } + + pub fn ensure_idle(&self) -> result::Result<()> { + self.ensure_thread()?; + match self.inner.state.get() { + State::Idle => {} + State::Poisoned => return Err(error("Borrowed-copy context is poisoned")), + _ => { + return Err(error( + "Borrowed-copy context is busy (reentrant operation rejected)", + )); + } + } + let origin = self + .inner + .origin + .borrow() + .as_ref() + .map(|origin| origin.client.clone()); + if let Some(origin) = origin { + origin.ensure_idle()?; + } + Ok(()) + } + + fn matches(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.inner, &other.inner) + } + + fn audio_owner(&self, service_iid: GUID) -> result::Result { + self.ensure_thread()?; + let role = if service_iid == AUDIO_RENDER { 1 } else { 2 }; + if self.inner.services.get() & role == 0 { + return Err(error( + "Audio copy requires an observed successful GetService for this interface", + )); + } + let origin = self + .inner + .origin + .borrow() + .as_ref() + .map(|origin| (origin.client.clone(), Rc::clone(&origin.client_view))); + if let Some(origin) = origin { + return Ok(origin); + } + let view = self.inner.same_identity_client_view.borrow().clone(); + if let Some(view) = view { + return Ok((self.clone(), view)); + } + Err(error( + "Audio copy requires an observed successful Initialize and GetService", + )) + } + + fn bind_service(&self, client: &Self, client_view: IUnknown, iid: GUID) -> result::Result<()> { + self.ensure_thread()?; + client.ensure_thread()?; + if client.inner.origin.borrow().is_some() { + return Err(error( + "An audio service cannot become another service's client origin", + )); + } + if self.matches(client) { + { + let mut view = self.inner.same_identity_client_view.borrow_mut(); + if view.is_none() { + *view = Some(Rc::new(client_view)); + } + } + self.inner + .services + .set(self.inner.services.get() | if iid == AUDIO_RENDER { 1 } else { 2 }); + return Ok(()); + } + // Never create A -> B -> A, or silently relabel an initialized client. + if self.inner.initialized.borrow().is_some() { + return Err(error("Conflicting audio service identity mapping")); + } + let mut origin = self.inner.origin.borrow_mut(); + let conflicting = origin + .as_ref() + .is_some_and(|existing| !existing.client.matches(client)); + if origin.is_none() { + *origin = Some(ServiceOrigin { + client: client.clone(), + client_view: Rc::new(client_view), + }); + } + drop(origin); + if conflicting { + return Err(error("Conflicting audio service origin")); + } + self.inner + .services + .set(self.inner.services.get() | if iid == AUDIO_RENDER { 1 } else { 2 }); + Ok(()) + } +} + +fn query(object: &IUnknown, iid: &GUID) -> result::Result { + let mut output = ptr::null_mut(); + unsafe { object.query(iid, &mut output).ok()? }; + if output.is_null() { + return Err(error("QueryInterface returned a required null interface")); + } + Ok(unsafe { IUnknown::from_raw(output) }) +} + +struct Transaction { + identities: Vec, + suppress_callbacks: bool, + finalizer: Option, + finished: bool, +} + +impl Transaction { + fn enter( + identity: &Identity, + owner: Option<&Identity>, + suppress: bool, + ) -> result::Result { + identity.ensure_idle()?; + let mut identities = vec![identity.clone()]; + if let Some(owner) = owner { + owner.ensure_idle()?; + if !owner.matches(identity) { + identities.push(owner.clone()); + } + } + for identity in &identities { + identity.inner.state.set(State::Acquiring); + } + if suppress { + COPY_DEPTH.with(|depth| depth.set(depth.get() + 1)); + } + Ok(Self { + identities, + suppress_callbacks: suppress, + finalizer: None, + finished: false, + }) + } + + fn acquired(&mut self, finalizer: Finalizer) { + // Arm before inspecting any native length/pointer or allocating copy storage. + self.finalizer = Some(finalizer); + self.set_state(State::Active); + } + + fn set_state(&self, state: State) { + for identity in &self.identities { + identity.inner.state.set(state); + } + } + + fn poison(&self) { + self.set_state(State::Poisoned); + } + + fn complete( + mut self, + result: result::Result, + commit: &[WinRTValue], + ) -> result::Result { + let cleanup = self.finalize(if result.is_ok() { Some(commit) } else { None }); + self.finished = true; + match (result, cleanup) { + (_, Err(cleanup)) => Err(cleanup), + (result, Ok(())) => result, + } + } + + fn finalize(&mut self, commit: Option<&[WinRTValue]>) -> result::Result<()> { + for identity in &self.identities { + identity.ensure_thread()?; + } + // Taking first prevents a failed finalizer from ever being retried by Drop. + let finalizer = self.finalizer.take(); + let poisoned = self + .identities + .iter() + .any(|id| id.inner.state.get() == State::Poisoned); + self.set_state(State::Finalizing); + let result = match finalizer { + Some(Finalizer::Call { + method, + view, + abort, + }) => exact_success(&method, &view, commit.unwrap_or(&abort)), + Some(Finalizer::Release(owner)) => { + drop(owner); + Ok(()) + } + None => Ok(()), + }; + self.set_state(if result.is_err() || poisoned { + State::Poisoned + } else { + State::Idle + }); + result + } +} + +impl Drop for Transaction { + fn drop(&mut self) { + if !self.finished { + let _ = self.finalize(None); + } + if self.suppress_callbacks { + COPY_DEPTH.with(|depth| depth.set(depth.get() - 1)); + } + } +} + +enum Finalizer { + Call { + method: MethodHandle, + view: IUnknown, + abort: Vec, + }, + Release(OwnedInterfaceCell), +} + +#[derive(Default)] +struct OwnedInterfaceCell(*mut c_void); + +impl Drop for OwnedInterfaceCell { + fn drop(&mut self) { + if !self.0.is_null() { + drop(unsafe { IUnknown::from_raw(self.0) }); + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CopyKind { + AudioRender, + AudioCapture, + BitmapBgra8, + MediaBuffer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Storage { + InU32, + InRect, + OutU32, + OutU64, + OutGuid, + BorrowedBytes, + OwnedInterface, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CallContract { + pub iid: GUID, + pub slot: usize, + pub storage: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Extent { + InitializedFrames, + CapturePacketFrames, + NativeBgra8Rows, + NativeCurrentAndMax, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Finalization { + RenderFullOrZero, + CaptureFullOrZero, + ReleaseLockReference, + Unlock, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemoryAccess { + Read, + Write, + ReadWrite, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BorrowOwner { + Receiver, + AudioServiceOrigin, + AcquiredInterface, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BorrowedCopyContract { + pub kind: CopyKind, + pub receiver: GUID, + pub acquire: CallContract, + pub queries: Vec, + pub finalize: Option, + pub extent: Extent, + pub finalization: Finalization, + pub sta_only: bool, + pub audio_origin_required: bool, + pub access: MemoryAccess, + pub owner: BorrowOwner, + pub acquired_hresult: i32, + pub empty_hresult: Option, +} + +impl BorrowedCopyContract { + pub fn expected(kind: CopyKind) -> Self { + use Storage::*; + let call = |iid, slot, storage: &[Storage]| CallContract { + iid, + slot, + storage: storage.to_vec(), + }; + match kind { + CopyKind::AudioRender => Self { + kind, + receiver: AUDIO_RENDER, + acquire: call(AUDIO_RENDER, 3, &[InU32, BorrowedBytes]), + queries: vec![call(AUDIO_CLIENT, 4, &[OutU32])], + finalize: Some(call(AUDIO_RENDER, 4, &[InU32, InU32])), + extent: Extent::InitializedFrames, + finalization: Finalization::RenderFullOrZero, + sta_only: false, + audio_origin_required: true, + access: MemoryAccess::Write, + owner: BorrowOwner::AudioServiceOrigin, + acquired_hresult: 0, + empty_hresult: None, + }, + CopyKind::AudioCapture => Self { + kind, + receiver: AUDIO_CAPTURE, + acquire: call( + AUDIO_CAPTURE, + 3, + &[BorrowedBytes, OutU32, OutU32, OutU64, OutU64], + ), + queries: vec![call(AUDIO_CLIENT, 4, &[OutU32])], + finalize: Some(call(AUDIO_CAPTURE, 4, &[InU32])), + extent: Extent::CapturePacketFrames, + finalization: Finalization::CaptureFullOrZero, + sta_only: false, + audio_origin_required: true, + access: MemoryAccess::Read, + owner: BorrowOwner::AudioServiceOrigin, + acquired_hresult: 0, + empty_hresult: Some(BUFFER_EMPTY), + }, + CopyKind::BitmapBgra8 => Self { + kind, + receiver: WIC_BITMAP, + acquire: call(WIC_BITMAP, 8, &[InRect, InU32, OwnedInterface]), + queries: vec![ + call(WIC_BITMAP, 3, &[OutU32, OutU32]), + call(WIC_LOCK, 3, &[OutU32, OutU32]), + call(WIC_LOCK, 4, &[OutU32]), + call(WIC_LOCK, 6, &[OutGuid]), + call(WIC_LOCK, 5, &[OutU32, BorrowedBytes]), + ], + finalize: None, + extent: Extent::NativeBgra8Rows, + finalization: Finalization::ReleaseLockReference, + sta_only: true, + audio_origin_required: false, + access: MemoryAccess::Read, + owner: BorrowOwner::AcquiredInterface, + acquired_hresult: 0, + empty_hresult: None, + }, + CopyKind::MediaBuffer => Self { + kind, + receiver: MF_BUFFER, + acquire: call(MF_BUFFER, 3, &[BorrowedBytes, OutU32, OutU32]), + queries: vec![call(MF_BUFFER, 6, &[InU32])], + finalize: Some(call(MF_BUFFER, 4, &[])), + extent: Extent::NativeCurrentAndMax, + finalization: Finalization::Unlock, + sta_only: false, + audio_origin_required: false, + access: MemoryAccess::ReadWrite, + owner: BorrowOwner::Receiver, + acquired_hresult: 0, + empty_hresult: None, + }, + } + } +} + +/// Prepared immutable calls and cleanup recipes. Does not own a native borrow. +pub struct BorrowedCopyPlan { + contract: BorrowedCopyContract, + acquire: MethodHandle, + queries: Vec, + finalize: Option, +} + +fn prepare( + table: &std::sync::Arc, + contract: &CallContract, +) -> result::Result { + // Output cells are deliberately lowered to addresses of private stable storage. + // The executor must not read them until the exact acquisition HRESULT is known. + let mut signature = MethodSignature::new(table).preserve_hresult(); + for storage in &contract.storage { + signature = signature.add_in(match storage { + Storage::InU32 => Type::winrt(table.u32_type()), + Storage::InRect + | Storage::OutU32 + | Storage::OutU64 + | Storage::OutGuid + | Storage::BorrowedBytes + | Storage::OwnedInterface => Type::pointer(), + }); + } + let interface = super::register_interface( + table, + "BorrowedCopyPlan", + contract.iid, + InterfaceBase::IUnknown, + ) + .add_method_at(contract.slot, "completed-copy-call", signature)?; + Ok(interface.method(contract.slot).expect("prepared method")) +} + +impl BorrowedCopyPlan { + pub fn prepare( + table: &std::sync::Arc, + contract: BorrowedCopyContract, + ) -> result::Result { + if contract != BorrowedCopyContract::expected(contract.kind) { + return Err(error( + "Unsupported borrowed-copy descriptor; regenerate bindings", + )); + } + let acquire = prepare(table, &contract.acquire)?; + let queries = contract + .queries + .iter() + .map(|call| prepare(table, call)) + .collect::>()?; + let finalize = contract + .finalize + .as_ref() + .map(|call| prepare(table, call)) + .transpose()?; + Ok(Self { + contract, + acquire, + queries, + finalize, + }) + } + + fn begin( + &self, + context: &Identity, + object: &IUnknown, + ) -> result::Result<(Transaction, IUnknown, Option)> { + context.ensure_idle()?; + if self.contract.sta_only { + let mut apartment = Default::default(); + let mut qualifier = Default::default(); + unsafe { CoGetApartmentType(&mut apartment, &mut qualifier)? }; + if apartment != APTTYPE_STA && apartment != APTTYPE_MAINSTA { + return Err(error( + "WIC borrowed-copy GetDataPointer requires an STA apartment", + )); + } + } + let origin = if self.contract.audio_origin_required { + Some(context.audio_owner(self.contract.receiver)?) + } else { + None + }; + let transaction = + Transaction::enter(context, origin.as_ref().map(|(identity, _)| identity), true)?; + if !context.matches(&Identity::for_object(object)?) { + return Err(error( + "Borrowed-copy context does not belong to this COM identity", + )); + } + let view = query(object, &self.contract.receiver)?; + Ok((transaction, view, origin)) + } + + fn audio_layout(&self, origin: &AudioOwner) -> result::Result { + let layout = { + let stored = origin.0.inner.initialized.borrow(); + stored.as_ref().map(|initialized| { + ( + initialized.block_align, + initialized.share_mode, + initialized.flags, + initialized.format.block_align() as usize, + ) + }) + }; + let (block, share_mode, flags, native_block) = layout + .ok_or_else(|| error("Audio client has no observed successful initialization"))?; + let block = block.ok_or_else(|| { + error("Initialized audio format is not a validated uncompressed frame layout") + })?; + if !(0..=1).contains(&share_mode) { + return Err(error("Unsupported initialized audio share mode")); + } + if self.contract.kind == CopyKind::AudioRender + && share_mode == 1 + && flags & EVENT_CALLBACK != 0 + { + return Err(error( + "Exclusive event-driven render copy is unsupported: zero-frame abort is invalid", + )); + } + // Keep immutable initialized format, not GetMixFormat or a caller blockAlign. + debug_assert_eq!(block, native_block); + Ok(block) + } + + fn audio_capacity(&self, origin: &AudioOwner) -> result::Result { + let mut capacity = 0u32; + exact_success(&self.queries[0], &origin.1, &[cell(&mut capacity)])?; + Ok(capacity) + } + + fn acquired_hresult(&self, transaction: &Transaction, hr: HRESULT) -> result::Result { + if hr.0 == self.contract.acquired_hresult { + Ok(true) + } else if self.contract.empty_hresult == Some(hr.0) { + Ok(false) + } else { + // Unknown success does not prove acquisition or authorize output reads. + transaction.poison(); + Err(error(format!( + "Unexpected acquisition HRESULT 0x{:08X}; context poisoned", + hr.0 as u32 + ))) + } + } + + pub fn write_frames_copy( + &self, + context: &Identity, + object: &IUnknown, + data: &[u8], + ) -> result::Result<()> { + self.write_audio(context, object, Some(data), 0) + } + + pub fn write_silence( + &self, + context: &Identity, + object: &IUnknown, + frames: u32, + ) -> result::Result<()> { + self.write_audio(context, object, None, frames) + } + + fn write_audio( + &self, + context: &Identity, + object: &IUnknown, + data: Option<&[u8]>, + silence_frames: u32, + ) -> result::Result<()> { + if self.contract.kind != CopyKind::AudioRender { + return Err(error( + "writeFramesCopy/writeSilence require a render copy plan", + )); + } + let (mut transaction, view, origin) = self.begin(context, object)?; + let origin = origin.as_ref().expect("audio origin"); + let block = self.audio_layout(origin)?; + let frames = if let Some(data) = data { + checked_extent(data.len())?; + if data.len() % block != 0 { + return Err(error( + "Audio data length must contain whole initialized-format frames", + )); + } + u32::try_from(data.len() / block).map_err(|_| error("Audio frame count overflow"))? + } else { + silence_frames + }; + let bytes = frame_bytes(frames, block)?; + if frames == 0 { + return transaction.complete(Ok(()), &[]); + } + if frames > self.audio_capacity(origin)? { + return Err(error("Audio frame count exceeds native buffer capacity")); + } + let finalizer = Finalizer::Call { + method: self.finalize.as_ref().expect("render finalizer").clone(), + view: view.clone(), + abort: vec![WinRTValue::U32(0), WinRTValue::U32(0)], + }; + let mut pointer = ptr::null_mut::(); + let hr = call( + &self.acquire, + &view, + &[WinRTValue::U32(frames), cell(&mut pointer)], + )?; + self.acquired_hresult(&transaction, hr)?; + transaction.acquired(finalizer); + let copied = if let Some(data) = data { + validate_pointer(pointer, bytes).map(|()| unsafe { + ptr::copy_nonoverlapping(data.as_ptr(), pointer, bytes); + }) + } else { + Ok(()) + }; + transaction.complete( + copied, + &[ + WinRTValue::U32(frames), + WinRTValue::U32(if data.is_none() { SILENT } else { 0 }), + ], + ) + } + + pub fn read_packet_copy( + &self, + context: &Identity, + object: &IUnknown, + ) -> result::Result> { + if self.contract.kind != CopyKind::AudioCapture { + return Err(error("readPacketCopy requires a capture copy plan")); + } + let (mut transaction, view, origin) = self.begin(context, object)?; + let origin = origin.as_ref().expect("audio origin"); + let block = self.audio_layout(origin)?; + let capacity = self.audio_capacity(origin)?; + let finalizer = Finalizer::Call { + method: self.finalize.as_ref().expect("capture finalizer").clone(), + view: view.clone(), + abort: vec![WinRTValue::U32(0)], + }; + let mut pointer = ptr::null_mut::(); + let (mut frames, mut flags, mut device, mut qpc) = (0u32, 0u32, 0u64, 0u64); + let hr = call( + &self.acquire, + &view, + &[ + cell(&mut pointer), + cell(&mut frames), + cell(&mut flags), + cell(&mut device), + cell(&mut qpc), + ], + )?; + if !self.acquired_hresult(&transaction, hr)? { + // No reads of any output cell, and no ReleaseBuffer, on BUFFER_EMPTY. + return transaction.complete(Ok(None), &[]); + } + transaction.acquired(finalizer); + let result = (|| { + if frames == 0 || frames > capacity { + return Err(error( + "Capture packet frames are outside native buffer capacity", + )); + } + let bytes = frame_bytes(frames, block)?; + let data = if flags & SILENT != 0 { + None + } else { + Some(copy_bytes(pointer, bytes)?) + }; + Ok(Some(CapturePacket { + data, + frames, + flags, + device_position: (flags & TIMESTAMP_ERROR == 0).then_some(device), + qpc_position: (flags & TIMESTAMP_ERROR == 0).then_some(qpc), + })) + })(); + transaction.complete(result, &[WinRTValue::U32(frames)]) + } + + pub fn read_copy(&self, context: &Identity, object: &IUnknown) -> result::Result> { + self.media_copy(context, object, None) + } + + pub fn replace_copy( + &self, + context: &Identity, + object: &IUnknown, + data: &[u8], + ) -> result::Result<()> { + checked_extent(data.len())?; + self.media_copy(context, object, Some(data)).map(|_| ()) + } + + fn media_copy( + &self, + context: &Identity, + object: &IUnknown, + data: Option<&[u8]>, + ) -> result::Result> { + if self.contract.kind != CopyKind::MediaBuffer { + return Err(error( + "readCopy/replaceCopy require a linear media-buffer plan", + )); + } + let (mut transaction, view, _) = self.begin(context, object)?; + let finalizer = Finalizer::Call { + method: self.finalize.as_ref().expect("media finalizer").clone(), + view: view.clone(), + abort: vec![], + }; + let mut pointer = ptr::null_mut::(); + let (mut maximum, mut current) = (0u32, 0u32); + let hr = call( + &self.acquire, + &view, + &[cell(&mut pointer), cell(&mut maximum), cell(&mut current)], + )?; + self.acquired_hresult(&transaction, hr)?; + transaction.acquired(finalizer); + let result = (|| { + if current > maximum { + return Err(error("Media buffer current length exceeds native maximum")); + } + if let Some(data) = data { + if data.len() > maximum as usize { + return Err(error("Replacement exceeds native media-buffer capacity")); + } + validate_pointer(pointer, data.len())?; + if !data.is_empty() { + unsafe { ptr::copy_nonoverlapping(data.as_ptr(), pointer, data.len()) }; + } + exact_success( + &self.queries[0], + &view, + &[WinRTValue::U32(data.len() as u32)], + )?; + Ok(vec![]) + } else { + copy_bytes(pointer, current as usize) + } + })(); + transaction.complete(result, &[]) + } + + pub fn read_locked_bgra8_copy( + &self, + context: &Identity, + object: &IUnknown, + rect: [i32; 4], + ) -> result::Result { + if self.contract.kind != CopyKind::BitmapBgra8 { + return Err(error("readLockedBgra8Copy requires a bitmap copy plan")); + } + let [x, y, width, height] = rect; + if x < 0 || y < 0 || width <= 0 || height <= 0 { + return Err(error( + "Bitmap rectangle must have nonnegative origin and positive dimensions", + )); + } + let right = x + .checked_add(width) + .ok_or_else(|| error("Bitmap rectangle overflow"))?; + let bottom = y + .checked_add(height) + .ok_or_else(|| error("Bitmap rectangle overflow"))?; + let (mut transaction, view, _) = self.begin(context, object)?; + let (mut bitmap_width, mut bitmap_height) = (0u32, 0u32); + exact_success( + &self.queries[0], + &view, + &[cell(&mut bitmap_width), cell(&mut bitmap_height)], + )?; + if right as u32 > bitmap_width || bottom as u32 > bitmap_height { + return Err(error("Bitmap rectangle exceeds native dimensions")); + } + let mut lock = OwnedInterfaceCell::default(); + let mut rect = rect; + let hr = call( + &self.acquire, + &view, + &[cell(&mut rect), WinRTValue::U32(1), cell(&mut lock.0)], + )?; + self.acquired_hresult(&transaction, hr)?; + let raw_lock = lock.0; + transaction.acquired(Finalizer::Release(lock)); + let result = (|| { + let lock = unsafe { IUnknown::from_raw_borrowed(&raw_lock) } + .ok_or_else(|| error("Bitmap Lock returned a required null lock"))?; + let (mut actual_width, mut actual_height, mut stride, mut count) = + (0u32, 0u32, 0u32, 0u32); + let mut format = GUID::zeroed(); + let mut pointer = ptr::null_mut::(); + exact_success( + &self.queries[1], + lock, + &[cell(&mut actual_width), cell(&mut actual_height)], + )?; + exact_success(&self.queries[2], lock, &[cell(&mut stride)])?; + exact_success(&self.queries[3], lock, &[cell(&mut format)])?; + if format != BGRA8 { + return Err(error("Bitmap copy supports only native 32bpp BGRA")); + } + if actual_width != width as u32 || actual_height != height as u32 { + return Err(error( + "Bitmap lock dimensions differ from the requested rectangle", + )); + } + exact_success( + &self.queries[4], + lock, + &[cell(&mut count), cell(&mut pointer)], + )?; + let row = (actual_width as usize) + .checked_mul(4) + .ok_or_else(|| error("Bitmap row overflow"))?; + let span = (actual_height as usize - 1) + .checked_mul(stride as usize) + .and_then(|n| n.checked_add(row)) + .ok_or_else(|| error("Bitmap span overflow"))?; + if row > stride as usize || span > count as usize { + return Err(error( + "Bitmap final-row span exceeds native byte count/stride", + )); + } + validate_pointer(pointer, span)?; + let length = row + .checked_mul(actual_height as usize) + .ok_or_else(|| error("Bitmap copy size overflow"))?; + let mut data = allocate(length)?; + for (index, target) in data.chunks_exact_mut(row).enumerate() { + unsafe { + ptr::copy_nonoverlapping( + pointer.add(index * stride as usize), + target.as_mut_ptr(), + row, + ) + }; + } + Ok(BitmapCopy { + data, + width: actual_width, + height: actual_height, + }) + })(); + transaction.complete(result, &[]) + } +} + +pub struct CapturePacket { + pub data: Option>, + pub frames: u32, + pub flags: u32, + pub device_position: Option, + pub qpc_position: Option, +} + +pub struct BitmapCopy { + pub data: Vec, + pub width: u32, + pub height: u32, +} + +fn cell(value: &mut T) -> WinRTValue { + WinRTValue::RawPtr((value as *mut T).cast()) +} + +fn call(method: &MethodHandle, view: &IUnknown, args: &[WinRTValue]) -> result::Result { + let result = unsafe { method.invoke(view.as_raw(), args) }?; + match result.as_slice() { + [WinRTValue::I32(value)] => Ok(HRESULT(*value)), + [WinRTValue::HResult(value)] => Ok(*value), + _ => Err(error("Borrowed-copy HRESULT call-plan result mismatch")), + } +} + +fn exact_success( + method: &MethodHandle, + view: &IUnknown, + args: &[WinRTValue], +) -> result::Result<()> { + let hr = call(method, view, args)?; + if hr.0 == 0 { + Ok(()) + } else { + Err(error(format!( + "Borrowed-copy call returned unexpected HRESULT 0x{:08X}", + hr.0 as u32 + ))) + } +} + +fn checked_extent(bytes: usize) -> result::Result<()> { + if bytes > MAX_COPY_BYTES || bytes > isize::MAX as usize { + return Err(error("Borrowed-copy extent exceeds the 64 MiB safety cap")); + } + Ok(()) +} + +fn frame_bytes(frames: u32, block: usize) -> result::Result { + let bytes = (frames as usize) + .checked_mul(block) + .ok_or_else(|| error("Audio byte extent overflow"))?; + checked_extent(bytes)?; + Ok(bytes) +} + +fn validate_pointer(pointer: *const u8, bytes: usize) -> result::Result<()> { + checked_extent(bytes)?; + if bytes != 0 && (pointer.is_null() || pointer.addr().checked_add(bytes).is_none()) { + return Err(error( + "Native borrowed buffer is null or its address extent overflows", + )); + } + Ok(()) +} + +fn allocate(length: usize) -> result::Result> { + checked_extent(length)?; + let mut output = Vec::new(); + output + .try_reserve_exact(length) + .map_err(|_| error("Unable to allocate owned copy"))?; + output.resize(length, 0); + Ok(output) +} + +fn copy_bytes(pointer: *const u8, bytes: usize) -> result::Result> { + validate_pointer(pointer, bytes)?; + let mut data = allocate(bytes)?; + if bytes != 0 { + unsafe { ptr::copy_nonoverlapping(pointer, data.as_mut_ptr(), bytes) }; + } + Ok(data) +} + +fn uncompressed_block_align(format: &AudioFormatValue) -> Option { + let bits = format.bits_per_sample(); + let mut tag = format.format_tag(); + if tag == 0xfffe { + let extra = format.extra_data(); + if extra.len() != 22 { + return None; + } + let valid = u16::from_le_bytes(extra[0..2].try_into().ok()?); + let mask = u32::from_le_bytes(extra[2..6].try_into().ok()?); + if valid == 0 + || valid > bits + || (mask != 0 && mask.count_ones() != u32::from(format.channels())) + { + return None; + } + let subformat = unsafe { ptr::read_unaligned(extra[6..22].as_ptr().cast::()) }; + tag = if subformat == GUID::from_u128(0x00000001_0000_0010_8000_00aa00389b71) { + 1 + } else if subformat == GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71) + && valid == bits + { + 3 + } else { + return None; + }; + } else if !format.extra_data().is_empty() { + return None; + } + if format.channels() == 0 + || format.samples_per_second() == 0 + || !(tag == 1 && matches!(bits, 8 | 16 | 24 | 32) || tag == 3 && matches!(bits, 32 | 64)) + { + return None; + } + let block = u32::from(format.channels()).checked_mul(u32::from(bits / 8))?; + if block == 0 + || block != u32::from(format.block_align()) + || format.samples_per_second().checked_mul(block)? != format.average_bytes_per_second() + { + return None; + } + Some(block as usize) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContextEffect { + AudioInitialize, + AudioInitializeShared, + AudioGetService, +} + +pub struct ManagedCallOutput { + pub values: Vec<(Value, super::PointerOutputKind)>, + pub output_context: Option, +} + +/// Executes the actual registered call; there is intentionally no "record success" +/// or attach-format API. The receiver and converted inputs remain pinned throughout. +/// +/// # Safety +/// The receiver and pointer-shaped inputs must satisfy the registered native ABI. +pub unsafe fn invoke_managed( + method: &MethodHandle, + context: &Identity, + view: &IUnknown, + args: &[Value], +) -> result::Result { + context.ensure_idle()?; + let transaction = method + .0 + .context_effect + .map(|_| Transaction::enter(context, None, true)) + .transpose()?; + if !context.matches(&Identity::for_object(view)?) { + return Err(error("Context effect receiver identity mismatch")); + } + let Some(effect) = method.0.context_effect else { + return Ok(ManagedCallOutput { + values: unsafe { method.invoke_values_with_output_kinds(view.as_raw(), args)? }, + output_context: None, + }); + }; + let transaction = transaction.expect("context effect transaction"); + let format_input = match effect { + ContextEffect::AudioInitialize => Some((4, 0, 1)), + ContextEffect::AudioInitializeShared => Some((2, usize::MAX, 0)), + ContextEffect::AudioGetService => None, + }; + let initialized = if let Some((format_index, mode_index, flags_index)) = format_input { + if context.inner.origin.borrow().is_some() { + return Err(error( + "An audio service identity cannot be independently initialized", + )); + } + let Some(Value::AudioFormat(format)) = args.get(format_index) else { + return Err(error( + "Audio initialization requires owned WAVEFORMATEX storage", + )); + }; + let mode = if mode_index == usize::MAX { + 0 + } else { + match args.get(mode_index) { + Some(Value::WinRt(WinRTValue::I32(value))) => *value, + _ => return Err(error("Audio share mode ABI mismatch")), + } + }; + let flags = match args.get(flags_index) { + Some(Value::WinRt(WinRTValue::U32(value))) => *value, + _ => return Err(error("Audio stream flags ABI mismatch")), + }; + Some(InitializedAudio { + format: format.clone(), + share_mode: mode, + flags, + block_align: uncompressed_block_align(format), + }) + } else { + None + }; + let iid = if effect == ContextEffect::AudioGetService { + let Some(Value::WinRt(WinRTValue::RawPtr(pointer))) = args.first() else { + return Err(error("GetService requires REFIID storage")); + }; + if pointer.is_null() { + return Err(error("GetService REFIID is required")); + } + Some(unsafe { ptr::read_unaligned(pointer.cast::()) }) + } else { + None + }; + let mut values = method + .0 + .context_hresult_plan + .as_ref() + .expect("validated context call") + .invoke_values_with_output_kinds(view.as_raw(), args)?; + let hresult = values.remove(0).0; + let hr = match hresult { + Value::WinRt(WinRTValue::I32(value)) => value, + Value::WinRt(WinRTValue::HResult(value)) => value.0, + _ => return Err(error("Context-effect HRESULT plan mismatch")), + }; + let mut service = if effect == ContextEffect::AudioGetService { + let raw = match values.first_mut() { + Some((Value::WinRt(WinRTValue::RawPtr(raw)), super::PointerOutputKind::Com)) => { + std::mem::replace(raw, ptr::null_mut()) + } + _ => return Err(error("GetService requires an owned interface output plan")), + }; + Some(OwnedInterfaceCell(raw)) + } else { + None + }; + if hr != 0 { + transaction.poison(); + return Err(error( + "Unexpected successful audio context HRESULT; provenance not recorded", + )); + } + if let Some(initialized) = initialized { + if context.inner.initialized.borrow().is_some() { + transaction.poison(); + return Err(error( + "Audio initialization succeeded twice; immutable provenance cannot be overwritten", + )); + } + *context.inner.initialized.borrow_mut() = Some(initialized); + } + let output_context = if let (Some(iid), Some(service)) = (iid, service.as_ref()) { + let object = unsafe { IUnknown::from_raw_borrowed(&service.0) } + .ok_or_else(|| error("GetService returned a required null interface"))?; + if iid == AUDIO_RENDER || iid == AUDIO_CAPTURE { + // A truthful QI pins the exact service view; never reinterpret the client. + let verified = query(object, &iid)?; + let identity = Identity::for_object(&verified)?; + identity.bind_service(context, query(view, &AUDIO_CLIENT)?, iid)?; + Some(identity) + } else { + None + } + } else { + None + }; + if let Some(service) = service.as_mut() { + let raw = std::mem::replace(&mut service.0, ptr::null_mut()); + values[0].0 = Value::WinRt(WinRTValue::RawPtr(raw)); + } + transaction.complete( + Ok(ManagedCallOutput { + values, + output_context, + }), + &[], + ) +} + +impl MethodSignature { + pub fn with_context_effect(mut self, effect: ContextEffect) -> Self { + self.context_effect = Some(effect); + self + } +} + +pub(super) fn validate_effect_signature( + signature: &MethodSignature, + effect: ContextEffect, + iid: GUID, + name: &str, + slot: usize, +) -> result::Result<()> { + use super::{ComParameterDirection as Direction, ComReturnPlan, PointerOutputKind}; + use crate::{TypeKind, native_call::ParameterType}; + let params = &signature.parameters; + let scalar = |index: usize, kind: TypeKind| { + params.get(index).is_some_and(|param| { + param.direction == Direction::In + && matches!(¶m.typ.abi, ParameterType::WinRT(typ) if typ.kind() == kind) + }) + }; + let pointer = |index: usize, direction: Direction| { + params.get(index).is_some_and(|param| { + param.direction == direction && matches!(param.typ.abi, ParameterType::Pointer) + }) + }; + let audio = |index: usize| { + params.get(index).is_some_and(|param| { + param.direction == Direction::In + && matches!( + param.typ.abi, + ParameterType::AudioFormat { + nullable_input: false + } + ) + && !param.nullable + }) + }; + let client = iid == AUDIO_CLIENT || iid == AUDIO_CLIENT2 || iid == AUDIO_CLIENT3; + let valid = matches!(signature.return_plan, ComReturnPlan::HResult) + && params.iter().all(|param| param.buffer.is_none()) + && match effect { + ContextEffect::AudioInitialize => { + client + && name == "Initialize" + && slot == 3 + && params.len() == 6 + && scalar(0, TypeKind::I32) + && scalar(1, TypeKind::U32) + && scalar(2, TypeKind::I64) + && scalar(3, TypeKind::I64) + && audio(4) + && pointer(5, Direction::In) + } + ContextEffect::AudioInitializeShared => { + iid == AUDIO_CLIENT3 + && name == "InitializeSharedAudioStream" + && slot == 20 + && params.len() == 4 + && scalar(0, TypeKind::U32) + && scalar(1, TypeKind::U32) + && audio(2) + && pointer(3, Direction::In) + } + ContextEffect::AudioGetService => { + client + && name == "GetService" + && slot == 14 + && params.len() == 2 + && pointer(0, Direction::In) + && pointer(1, Direction::Out) + && !params[0].nullable + && params[1].typ.pointer_output == PointerOutputKind::Com + } + }; + if valid { + Ok(()) + } else { + Err(error( + "Audio context effect does not match the exact IID/slot/ABI contract", + )) + } +} diff --git a/crates/dynwinrt/src/com_borrowed_test_support.rs b/crates/dynwinrt/src/com_borrowed_test_support.rs new file mode 100644 index 00000000..fc752768 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_test_support.rs @@ -0,0 +1,1076 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Deterministic, hardware-free native fixtures. Both interface views have +//! complete ABI-correct vtables, one refcount and truthful canonical IUnknown QI. + +use super::{ + AUDIO_CAPTURE, AUDIO_CLIENT, AUDIO_CLIENT2, AUDIO_CLIENT3, AUDIO_RENDER, AudioFormatValue, + MF_BUFFER, WIC_BITMAP, WIC_LOCK, error, result, +}; +use std::{ + cell::{Cell, RefCell, UnsafeCell}, + ffi::c_void, + ptr, + rc::Rc, +}; +use windows_core::{GUID, HRESULT, IUnknown, IUnknown_Vtbl, Interface as _}; + +const FAIL: HRESULT = HRESULT(0x80004005u32 as i32); +const INVALID: HRESULT = HRESULT(0x80070057u32 as i32); +const POINTER: HRESULT = HRESULT(0x80004003u32 as i32); +const NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); +const OK: HRESULT = HRESULT(0); + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Client, + Render, + Capture, + Bitmap, + Lock, + Media, +} + +#[repr(C)] +struct View { + vtable: *const c_void, + owner: *mut Owner, +} + +struct Owner { + views: [View; 2], + references: Cell, + kind: Kind, + control: Rc, + held: RefCell>, +} + +struct Control { + initialize_hr: Cell, + initialized: Cell, + format: RefCell>, + capacity: Cell, + render_active: Cell, + render_requested: Cell, + render_release_hr: Cell, + render_null: Cell, + render_acquire_hr: Cell, + capture_active: Cell, + capture_hr: Cell, + capture_frames: Cell, + capture_flags: Cell, + capture_null: Cell, + capture_release_hr: Cell, + service_wrong: Cell, + media_active: Cell, + media_max: Cell, + media_current: Cell, + media_lock_hr: Cell, + media_unlock_hr: Cell, + media_set_hr: Cell, + media_null: Cell, + wic_active: Cell, + wic_stride: Cell, + wic_count: Cell, + wic_lock_hr: Cell, + wic_null: Cell, + wic_wrong_format: Cell, + wic_query_hr: Cell, + bytes: UnsafeCell<[u8; 256]>, + events: RefCell>, + hook: RefCell>>, +} + +impl Default for Control { + fn default() -> Self { + Self { + initialize_hr: Cell::new(0), + initialized: Cell::new(false), + format: RefCell::new(None), + capacity: Cell::new(8), + render_active: Cell::new(false), + render_requested: Cell::new(0), + render_release_hr: Cell::new(0), + render_null: Cell::new(false), + render_acquire_hr: Cell::new(0), + capture_active: Cell::new(false), + capture_hr: Cell::new(0), + capture_frames: Cell::new(2), + capture_flags: Cell::new(0), + capture_null: Cell::new(false), + capture_release_hr: Cell::new(0), + service_wrong: Cell::new(false), + media_active: Cell::new(false), + media_max: Cell::new(16), + media_current: Cell::new(4), + media_lock_hr: Cell::new(0), + media_unlock_hr: Cell::new(0), + media_set_hr: Cell::new(0), + media_null: Cell::new(false), + wic_active: Cell::new(false), + wic_stride: Cell::new(12), + wic_count: Cell::new(20), + wic_lock_hr: Cell::new(0), + wic_null: Cell::new(false), + wic_wrong_format: Cell::new(false), + wic_query_hr: Cell::new(0), + bytes: UnsafeCell::new(std::array::from_fn(|i| i as u8)), + events: RefCell::new(vec![]), + hook: RefCell::new(None), + } + } +} + +impl Control { + fn event(&self, event: impl Into) { + let event = event.into(); + self.events.borrow_mut().push(event.clone()); + let hook = self.hook.borrow().clone(); + if let Some(hook) = hook { + hook(&event); + } + } + fn block(&self) -> usize { + self.format + .borrow() + .as_ref() + .map_or(4, |format| format.block_align() as usize) + } + fn bytes(&self) -> *mut u8 { + self.bytes.get().cast() + } +} + +unsafe fn owner<'a>(this: *mut c_void) -> &'a Owner { + unsafe { &*(*(this.cast::())).owner } +} + +unsafe extern "system" fn qi( + this: *mut c_void, + iid: *const GUID, + output: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || output.is_null() { + return POINTER; + } + unsafe { + *output = ptr::null_mut(); + let owner = owner(this); + let supported = *iid == IUnknown::IID + || match owner.kind { + Kind::Client => { + *iid == AUDIO_CLIENT || *iid == AUDIO_CLIENT2 || *iid == AUDIO_CLIENT3 + } + Kind::Render => *iid == AUDIO_RENDER, + Kind::Capture => *iid == AUDIO_CAPTURE, + Kind::Bitmap => { + *iid == WIC_BITMAP + || *iid == GUID::from_u128(0x00000120_a8f2_4877_ba0a_fd2b6645fb94) + } + Kind::Lock => *iid == WIC_LOCK, + Kind::Media => *iid == MF_BUFFER, + }; + if !supported { + return HRESULT(0x80004002u32 as i32); + } + let index = usize::from(*iid != IUnknown::IID); + *output = (&owner.views[index] as *const View).cast_mut().cast(); + add_ref(this); + OK + } +} + +unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let owner = unsafe { owner(this) }; + let count = owner.references.get() + 1; + owner.references.set(count); + count +} + +unsafe extern "system" fn release(this: *mut c_void) -> u32 { + unsafe { + let owner = owner(this); + let count = owner.references.get() - 1; + owner.references.set(count); + if count == 0 { + if owner.kind == Kind::Lock { + owner.control.wic_active.set(false); + owner.control.event("wic.release"); + } + owner.control.event(format!( + "drop.{}", + match owner.kind { + Kind::Client => "client", + Kind::Render => "render", + Kind::Capture => "capture", + Kind::Bitmap => "bitmap", + Kind::Lock => "lock", + Kind::Media => "media", + } + )); + drop(Box::from_raw((owner as *const Owner).cast_mut())); + } + count + } +} + +const UNKNOWN: IUnknown_Vtbl = IUnknown_Vtbl { + QueryInterface: qi, + AddRef: add_ref, + Release: release, +}; + +fn make(kind: Kind, control: &Rc, held: Vec) -> IUnknown { + let vtable = match kind { + Kind::Client => (&CLIENT_VTABLE as *const ClientVtable).cast(), + Kind::Render => (&RENDER_VTABLE as *const RenderVtable).cast(), + Kind::Capture => (&CAPTURE_VTABLE as *const CaptureVtable).cast(), + Kind::Bitmap => (&BITMAP_VTABLE as *const BitmapVtable).cast(), + Kind::Lock => (&LOCK_VTABLE as *const LockVtable).cast(), + Kind::Media => (&MEDIA_VTABLE as *const MediaVtable).cast(), + }; + let mut object = Box::new(Owner { + views: [ + View { + vtable, + owner: ptr::null_mut(), + }, + View { + vtable, + owner: ptr::null_mut(), + }, + ], + references: Cell::new(1), + kind, + control: control.clone(), + held: RefCell::new(held), + }); + let pointer = &mut *object as *mut Owner; + object.views[0].owner = pointer; + object.views[1].owner = pointer; + let output = (&mut object.views[1] as *mut View).cast(); + let _ = Box::into_raw(object); + unsafe { IUnknown::from_raw(output) } +} + +#[repr(C)] +struct ClientVtable { + base: IUnknown_Vtbl, + initialize: unsafe extern "system" fn( + *mut c_void, + i32, + u32, + i64, + i64, + *const u8, + *const GUID, + ) -> HRESULT, + size: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, + latency: unsafe extern "system" fn(*mut c_void, *mut i64) -> HRESULT, + padding: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, + format_supported: + unsafe extern "system" fn(*mut c_void, i32, *const u8, *mut *mut u8) -> HRESULT, + mix_format: unsafe extern "system" fn(*mut c_void, *mut *mut u8) -> HRESULT, + periods: unsafe extern "system" fn(*mut c_void, *mut i64, *mut i64) -> HRESULT, + start: unsafe extern "system" fn(*mut c_void) -> HRESULT, + stop: unsafe extern "system" fn(*mut c_void) -> HRESULT, + reset: unsafe extern "system" fn(*mut c_void) -> HRESULT, + set_event: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, + service: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT, + offload: unsafe extern "system" fn(*mut c_void, i32, *mut i32) -> HRESULT, + properties: unsafe extern "system" fn(*mut c_void, *const c_void) -> HRESULT, + limits: unsafe extern "system" fn(*mut c_void, *const u8, i32, *mut i64, *mut i64) -> HRESULT, + engine_periods: unsafe extern "system" fn( + *mut c_void, + *const u8, + *mut u32, + *mut u32, + *mut u32, + *mut u32, + ) -> HRESULT, + current_period: unsafe extern "system" fn(*mut c_void, *mut *mut u8, *mut u32) -> HRESULT, + initialize_shared: + unsafe extern "system" fn(*mut c_void, u32, u32, *const u8, *const GUID) -> HRESULT, +} + +unsafe fn initialize_native(this: *mut c_void, format: *const u8) -> HRESULT { + if format.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("audio.initialize"); + let hr = control.initialize_hr.get(); + if hr != 0 { + return HRESULT(hr); + } + if control.initialized.get() { + return HRESULT(0x88890002u32 as i32); + } + let extra = unsafe { u16::from_le_bytes([*format.add(16), *format.add(17)]) } as usize; + let bytes = unsafe { std::slice::from_raw_parts(format, 18 + extra) }.to_vec(); + let Ok(format) = AudioFormatValue::from_wave_format_ex(bytes) else { + return INVALID; + }; + // This fixture never returns storage larger than its physical array. + if usize::from(format.block_align()) + .checked_mul(control.capacity.get() as usize) + .is_none_or(|size| size > 256) + { + return INVALID; + } + *control.format.borrow_mut() = Some(format); + control.initialized.set(true); + OK +} + +unsafe extern "system" fn initialize( + this: *mut c_void, + _: i32, + _: u32, + _: i64, + _: i64, + format: *const u8, + _: *const GUID, +) -> HRESULT { + unsafe { initialize_native(this, format) } +} +unsafe extern "system" fn initialize_shared( + this: *mut c_void, + _: u32, + _: u32, + format: *const u8, + _: *const GUID, +) -> HRESULT { + unsafe { initialize_native(this, format) } +} +unsafe extern "system" fn size(this: *mut c_void, output: *mut u32) -> HRESULT { + if output.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("audio.capacity"); + unsafe { + *output = control.capacity.get(); + } + OK +} +unsafe extern "system" fn u32_zero(_: *mut c_void, output: *mut u32) -> HRESULT { + if output.is_null() { + return POINTER; + } + unsafe { + *output = 0; + } + OK +} +unsafe extern "system" fn latency(_: *mut c_void, output: *mut i64) -> HRESULT { + if output.is_null() { + return POINTER; + } + unsafe { + *output = 0; + } + OK +} +unsafe extern "system" fn format_supported( + _: *mut c_void, + _: i32, + _: *const u8, + output: *mut *mut u8, +) -> HRESULT { + if !output.is_null() { + unsafe { + *output = ptr::null_mut(); + } + } + OK +} +unsafe extern "system" fn mix_format(this: *mut c_void, output: *mut *mut u8) -> HRESULT { + if output.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("audio.mix"); + let format = AudioFormatValue::pcm(1, 48_000, 8).unwrap(); + let pointer = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(format.bytes().len()) }.cast::(); + if pointer.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + ptr::copy_nonoverlapping(format.bytes().as_ptr(), pointer, format.bytes().len()); + *output = pointer; + } + OK +} +unsafe extern "system" fn periods(_: *mut c_void, a: *mut i64, b: *mut i64) -> HRESULT { + unsafe { + if !a.is_null() { + *a = 0; + } + if !b.is_null() { + *b = 0; + } + } + OK +} +unsafe extern "system" fn simple(_: *mut c_void) -> HRESULT { + OK +} +unsafe extern "system" fn set_event(_: *mut c_void, _: *mut c_void) -> HRESULT { + OK +} +unsafe extern "system" fn service( + this: *mut c_void, + iid: *const GUID, + output: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || output.is_null() { + return POINTER; + } + unsafe { + *output = ptr::null_mut(); + let owner = owner(this); + owner.control.event("audio.service"); + if owner.control.service_wrong.get() { + add_ref(this); + *output = this; + return OK; + } + let target = { + let held = owner.held.borrow(); + if *iid == AUDIO_RENDER { + held.first().cloned() + } else if *iid == AUDIO_CAPTURE { + held.get(1).cloned() + } else { + None + } + }; + if let Some(target) = target { + target.query(iid, output) + } else { + qi(this, iid, output) + } + } +} +unsafe extern "system" fn offload(_: *mut c_void, _: i32, out: *mut i32) -> HRESULT { + if out.is_null() { + return POINTER; + } + unsafe { + *out = 0; + } + OK +} +unsafe extern "system" fn properties(_: *mut c_void, _: *const c_void) -> HRESULT { + OK +} +unsafe extern "system" fn limits( + this: *mut c_void, + _: *const u8, + _: i32, + a: *mut i64, + b: *mut i64, +) -> HRESULT { + unsafe { periods(this, a, b) } +} +unsafe extern "system" fn engine_periods( + _: *mut c_void, + _: *const u8, + a: *mut u32, + b: *mut u32, + c: *mut u32, + d: *mut u32, +) -> HRESULT { + unsafe { + for p in [a, b, c, d] { + if p.is_null() { + return POINTER; + } + *p = 1; + } + } + OK +} +unsafe extern "system" fn current_period( + this: *mut c_void, + format: *mut *mut u8, + period: *mut u32, +) -> HRESULT { + if period.is_null() { + return POINTER; + } + unsafe { + *period = 1; + mix_format(this, format) + } +} +static CLIENT_VTABLE: ClientVtable = ClientVtable { + base: UNKNOWN, + initialize, + size, + latency, + padding: u32_zero, + format_supported, + mix_format, + periods, + start: simple, + stop: simple, + reset: simple, + set_event, + service, + offload, + properties, + limits, + engine_periods, + current_period, + initialize_shared, +}; + +#[repr(C)] +struct RenderVtable { + base: IUnknown_Vtbl, + get: unsafe extern "system" fn(*mut c_void, u32, *mut *mut u8) -> HRESULT, + release: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT, +} +unsafe extern "system" fn render_get( + this: *mut c_void, + frames: u32, + output: *mut *mut u8, +) -> HRESULT { + if output.is_null() { + return POINTER; + } + unsafe { + *output = ptr::null_mut(); + } + let control = &unsafe { owner(this) }.control; + control.event(format!("render.acquire.{frames}")); + if frames == 0 + || frames > control.capacity.get() + || (frames as usize) + .checked_mul(control.block()) + .is_none_or(|n| n > 256) + { + return INVALID; + } + if control.render_active.get() { + return FAIL; + } + if control.render_acquire_hr.get() != 0 { + return HRESULT(control.render_acquire_hr.get()); + } + control.render_active.set(true); + control.render_requested.set(frames); + if !control.render_null.get() { + unsafe { + *output = control.bytes(); + } + } + OK +} +unsafe extern "system" fn render_release(this: *mut c_void, frames: u32, flags: u32) -> HRESULT { + let control = &unsafe { owner(this) }.control; + control.event(format!("render.release.{frames}.{flags}")); + if !control.render_active.get() + || (frames != 0 && frames != control.render_requested.get()) + || !matches!(flags, 0 | 2) + || (frames == 0 && flags != 0) + { + return INVALID; + } + if control.render_release_hr.get() != 0 { + return HRESULT(control.render_release_hr.get()); + } + control.render_active.set(false); + OK +} +static RENDER_VTABLE: RenderVtable = RenderVtable { + base: UNKNOWN, + get: render_get, + release: render_release, +}; + +#[repr(C)] +struct CaptureVtable { + base: IUnknown_Vtbl, + get: unsafe extern "system" fn( + *mut c_void, + *mut *mut u8, + *mut u32, + *mut u32, + *mut u64, + *mut u64, + ) -> HRESULT, + release: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, + next: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, +} +unsafe extern "system" fn capture_get( + this: *mut c_void, + data: *mut *mut u8, + frames: *mut u32, + flags: *mut u32, + device: *mut u64, + qpc: *mut u64, +) -> HRESULT { + if data.is_null() || frames.is_null() || flags.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("capture.acquire"); + let hr = control.capture_hr.get(); + if hr != 0 { + // Deliberately meaningless output cells on BUFFER_EMPTY. The caller must + // classify HRESULT without reading them, and must not release a packet. + unsafe { + *data = ptr::null_mut(); + *frames = u32::MAX; + *flags = u32::MAX; + } + return HRESULT(hr); + } + if control.capture_active.get() { + return FAIL; + } + if (control.capture_frames.get() as usize) + .checked_mul(control.block()) + .is_none_or(|n| n > 256) + { + return INVALID; + } + control.capture_active.set(true); + unsafe { + *data = if control.capture_null.get() { + ptr::null_mut() + } else { + control.bytes() + }; + *frames = control.capture_frames.get(); + *flags = control.capture_flags.get(); + if !device.is_null() { + *device = 123; + } + if !qpc.is_null() { + *qpc = 456; + } + } + OK +} +unsafe extern "system" fn capture_release(this: *mut c_void, frames: u32) -> HRESULT { + let control = &unsafe { owner(this) }.control; + control.event(format!("capture.release.{frames}")); + if !control.capture_active.get() || (frames != 0 && frames != control.capture_frames.get()) { + return INVALID; + } + if control.capture_release_hr.get() != 0 { + return HRESULT(control.capture_release_hr.get()); + } + control.capture_active.set(false); + OK +} +unsafe extern "system" fn capture_next(this: *mut c_void, output: *mut u32) -> HRESULT { + if output.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("capture.next"); + unsafe { + *output = control.capture_frames.get(); + } + OK +} +static CAPTURE_VTABLE: CaptureVtable = CaptureVtable { + base: UNKNOWN, + get: capture_get, + release: capture_release, + next: capture_next, +}; + +#[repr(C)] +struct BitmapVtable { + base: IUnknown_Vtbl, + size: unsafe extern "system" fn(*mut c_void, *mut u32, *mut u32) -> HRESULT, + format: unsafe extern "system" fn(*mut c_void, *mut GUID) -> HRESULT, + resolution: unsafe extern "system" fn(*mut c_void, *mut f64, *mut f64) -> HRESULT, + palette: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, + pixels: unsafe extern "system" fn(*mut c_void, *const i32, u32, u32, *mut u8) -> HRESULT, + lock: unsafe extern "system" fn(*mut c_void, *const i32, u32, *mut *mut c_void) -> HRESULT, + set_palette: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, + set_resolution: unsafe extern "system" fn(*mut c_void, f64, f64) -> HRESULT, +} +unsafe extern "system" fn bitmap_size( + _: *mut c_void, + width: *mut u32, + height: *mut u32, +) -> HRESULT { + if width.is_null() || height.is_null() { + return POINTER; + } + unsafe { + *width = 2; + *height = 2; + } + OK +} +unsafe extern "system" fn bitmap_format(this: *mut c_void, output: *mut GUID) -> HRESULT { + if output.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + unsafe { + *output = if control.wic_wrong_format.get() { + GUID::zeroed() + } else { + super::BGRA8 + }; + } + OK +} +unsafe extern "system" fn bitmap_resolution(_: *mut c_void, x: *mut f64, y: *mut f64) -> HRESULT { + if x.is_null() || y.is_null() { + return POINTER; + } + unsafe { + *x = 96.0; + *y = 96.0; + } + OK +} +unsafe extern "system" fn bitmap_pixels( + _: *mut c_void, + _: *const i32, + _: u32, + _: u32, + _: *mut u8, +) -> HRESULT { + NOTIMPL +} +unsafe extern "system" fn bitmap_set_resolution(_: *mut c_void, _: f64, _: f64) -> HRESULT { + OK +} +unsafe extern "system" fn bitmap_lock( + this: *mut c_void, + rect: *const i32, + flags: u32, + output: *mut *mut c_void, +) -> HRESULT { + if rect.is_null() || output.is_null() { + return POINTER; + } + unsafe { + *output = ptr::null_mut(); + } + let control = &unsafe { owner(this) }.control; + control.event(format!("wic.acquire.{flags}")); + let rect = unsafe { std::slice::from_raw_parts(rect, 4) }; + if flags != 1 || rect != [0, 0, 2, 2] || control.wic_active.get() { + return INVALID; + } + if !control.wic_null.get() { + control.wic_active.set(true); + let parent = unsafe { IUnknown::from_raw_borrowed(&this) } + .unwrap() + .clone(); + let lock = make(Kind::Lock, control, vec![parent]); + unsafe { + *output = lock.into_raw(); + } + } + HRESULT(control.wic_lock_hr.get()) +} +static BITMAP_VTABLE: BitmapVtable = BitmapVtable { + base: UNKNOWN, + size: bitmap_size, + format: bitmap_format, + resolution: bitmap_resolution, + palette: set_event, + pixels: bitmap_pixels, + lock: bitmap_lock, + set_palette: set_event, + set_resolution: bitmap_set_resolution, +}; + +#[repr(C)] +struct LockVtable { + base: IUnknown_Vtbl, + size: unsafe extern "system" fn(*mut c_void, *mut u32, *mut u32) -> HRESULT, + stride: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, + data: unsafe extern "system" fn(*mut c_void, *mut u32, *mut *mut u8) -> HRESULT, + format: unsafe extern "system" fn(*mut c_void, *mut GUID) -> HRESULT, +} +unsafe extern "system" fn lock_stride(this: *mut c_void, stride: *mut u32) -> HRESULT { + if stride.is_null() { + return POINTER; + } + unsafe { + *stride = owner(this).control.wic_stride.get(); + } + OK +} +unsafe extern "system" fn lock_data( + this: *mut c_void, + count: *mut u32, + output: *mut *mut u8, +) -> HRESULT { + if count.is_null() || output.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("wic.data"); + if control.wic_query_hr.get() != 0 { + return HRESULT(control.wic_query_hr.get()); + } + if control.wic_count.get() > 256 { + return INVALID; + } + unsafe { + *count = control.wic_count.get(); + *output = control.bytes(); + } + OK +} +static LOCK_VTABLE: LockVtable = LockVtable { + base: UNKNOWN, + size: bitmap_size, + stride: lock_stride, + data: lock_data, + format: bitmap_format, +}; + +#[repr(C)] +struct MediaVtable { + base: IUnknown_Vtbl, + lock: unsafe extern "system" fn(*mut c_void, *mut *mut u8, *mut u32, *mut u32) -> HRESULT, + unlock: unsafe extern "system" fn(*mut c_void) -> HRESULT, + current: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, + set_current: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, + maximum: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT, +} +unsafe extern "system" fn media_lock( + this: *mut c_void, + output: *mut *mut u8, + maximum: *mut u32, + current: *mut u32, +) -> HRESULT { + // Both optional length cells are deliberately required by this fixture so + // that a test cannot accidentally pass while omitting either native bound. + if output.is_null() || maximum.is_null() || current.is_null() { + return POINTER; + } + let control = &unsafe { owner(this) }.control; + control.event("media.acquire"); + if control.media_max.get() > 256 || control.media_active.get() { + return INVALID; + } + if control.media_lock_hr.get() != 0 { + return HRESULT(control.media_lock_hr.get()); + } + control.media_active.set(true); + unsafe { + *output = if control.media_null.get() { + ptr::null_mut() + } else { + control.bytes() + }; + *maximum = control.media_max.get(); + *current = control.media_current.get(); + } + OK +} +unsafe extern "system" fn media_unlock(this: *mut c_void) -> HRESULT { + let control = &unsafe { owner(this) }.control; + control.event("media.unlock"); + if !control.media_active.get() { + return INVALID; + } + if control.media_unlock_hr.get() != 0 { + return HRESULT(control.media_unlock_hr.get()); + } + control.media_active.set(false); + OK +} +unsafe extern "system" fn media_current(this: *mut c_void, output: *mut u32) -> HRESULT { + if output.is_null() { + return POINTER; + } + unsafe { + *output = owner(this).control.media_current.get(); + } + OK +} +unsafe extern "system" fn media_set(this: *mut c_void, length: u32) -> HRESULT { + let control = &unsafe { owner(this) }.control; + control.event(format!("media.length.{length}")); + if length > control.media_max.get() || length > 256 { + return INVALID; + } + if control.media_set_hr.get() != 0 { + return HRESULT(control.media_set_hr.get()); + } + control.media_current.set(length); + OK +} +unsafe extern "system" fn media_max(this: *mut c_void, output: *mut u32) -> HRESULT { + if output.is_null() { + return POINTER; + } + unsafe { + *output = owner(this).control.media_max.get(); + } + OK +} +static MEDIA_VTABLE: MediaVtable = MediaVtable { + base: UNKNOWN, + lock: media_lock, + unlock: media_unlock, + current: media_current, + set_current: media_set, + maximum: media_max, +}; + +pub struct CopyFixture { + objects: Vec, + control: Rc, +} + +impl Default for CopyFixture { + fn default() -> Self { + let control = Rc::new(Control::default()); + let render = make(Kind::Render, &control, vec![]); + let capture = make(Kind::Capture, &control, vec![]); + let client = make( + Kind::Client, + &control, + vec![render.clone(), capture.clone()], + ); + let bitmap = make(Kind::Bitmap, &control, vec![]); + let media = make(Kind::Media, &control, vec![]); + Self { + objects: vec![client, render, capture, bitmap, media], + control, + } + } +} + +impl CopyFixture { + pub fn object(&self, kind: &str) -> result::Result { + if kind == "mediaUnknown" { + return super::query(&self.object("media")?, &IUnknown::IID); + } + let index = match kind { + "client" => 0, + "render" => 1, + "capture" => 2, + "bitmap" => 3, + "media" => 4, + _ => return Err(error("Unknown borrowed-copy fixture object")), + }; + self.objects + .get(index) + .cloned() + .ok_or_else(|| error("Fixture owners have been released")) + } + pub fn release_owners(&mut self) { + self.objects.clear(); + } + pub fn configure(&self, key: &str, value: u32) -> result::Result<()> { + let c = &self.control; + match key { + "initializeHr" => c.initialize_hr.set(value as i32), + "externalInitialized" => c.initialized.set(value != 0), + "capacity" => c.capacity.set(value), + "renderNull" => c.render_null.set(value != 0), + "renderAcquireHr" => c.render_acquire_hr.set(value as i32), + "renderReleaseHr" => c.render_release_hr.set(value as i32), + "captureHr" => c.capture_hr.set(value as i32), + "captureFrames" => c.capture_frames.set(value), + "captureFlags" => c.capture_flags.set(value), + "captureNull" => c.capture_null.set(value != 0), + "captureReleaseHr" => c.capture_release_hr.set(value as i32), + "serviceWrong" => c.service_wrong.set(value != 0), + "mediaMax" => c.media_max.set(value), + "mediaCurrent" => c.media_current.set(value), + "mediaLockHr" => c.media_lock_hr.set(value as i32), + "mediaUnlockHr" => c.media_unlock_hr.set(value as i32), + "mediaSetHr" => c.media_set_hr.set(value as i32), + "mediaNull" => c.media_null.set(value != 0), + "wicStride" => c.wic_stride.set(value), + "wicCount" => c.wic_count.set(value), + "wicLockHr" => c.wic_lock_hr.set(value as i32), + "wicNull" => c.wic_null.set(value != 0), + "wicWrongFormat" => c.wic_wrong_format.set(value != 0), + "wicQueryHr" => c.wic_query_hr.set(value as i32), + _ => return Err(error("Unknown borrowed-copy fixture setting")), + } + Ok(()) + } + pub fn events(&self) -> Vec { + self.control.events.borrow().clone() + } + pub fn bytes(&self) -> Vec { + unsafe { (&*self.control.bytes.get()).to_vec() } + } + #[cfg(test)] + pub fn share_render_service(&self, other: &Self) { + let target = other.object("render").unwrap(); + let client = self.object("client").unwrap(); + let owner = unsafe { owner(client.as_raw()) }; + let old = std::mem::replace(&mut owner.held.borrow_mut()[0], target); + drop(old); + } + pub fn install_callback_probe(&self, sink: IUnknown) -> result::Result<()> { + const IID: GUID = GUID::from_u128(0x5bbdf51f_3e8d_40c5_ad0f_d8b341172d12); + let sink = super::query(&sink, &IID)?; + let table = crate::MetadataTable::new(); + let method = super::super::register_interface( + &table, + "borrowed-test-callback", + IID, + super::InterfaceBase::IUnknown, + ) + .add_method_at( + 3, + "Probe", + super::MethodSignature::new(&table).preserve_hresult(), + )? + .method(3) + .unwrap(); + let weak = Rc::downgrade(&self.control); + *self.control.hook.borrow_mut() = Some(Rc::new(move |event| { + if event.starts_with("render.acquire.") { + let rejected = unsafe { method.invoke(sink.as_raw(), &[]) }.is_err(); + if let Some(control) = weak.upgrade() { + control + .events + .borrow_mut() + .push(format!("callback.rejected.{rejected}")); + } + } + })); + Ok(()) + } + #[cfg(test)] + pub fn hook(&self, hook: Option>) { + *self.control.hook.borrow_mut() = hook; + } +} + +#[test] +fn borrowed_copy_fixture_vtables_have_exact_sdk_slots_on_every_pointer_width() { + use std::mem::{offset_of, size_of}; + let pointer = size_of::<*const c_void>(); + assert_eq!(size_of::(), 21 * pointer); + assert_eq!(offset_of!(ClientVtable, initialize), 3 * pointer); + assert_eq!(offset_of!(ClientVtable, service), 14 * pointer); + assert_eq!(offset_of!(ClientVtable, initialize_shared), 20 * pointer); + assert_eq!(size_of::(), 5 * pointer); + assert_eq!(size_of::(), 6 * pointer); + assert_eq!(size_of::(), 11 * pointer); + assert_eq!(offset_of!(BitmapVtable, lock), 8 * pointer); + assert_eq!(size_of::(), 7 * pointer); + assert_eq!(offset_of!(LockVtable, data), 5 * pointer); + assert_eq!(size_of::(), 8 * pointer); + assert_eq!(offset_of!(MediaVtable, set_current), 6 * pointer); +} diff --git a/crates/dynwinrt/src/com_borrowed_tests.rs b/crates/dynwinrt/src/com_borrowed_tests.rs new file mode 100644 index 00000000..b4249aa9 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_tests.rs @@ -0,0 +1,755 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::testing::CopyFixture; +use super::*; + +fn plan(kind: CopyKind) -> BorrowedCopyPlan { + BorrowedCopyPlan::prepare(&MetadataTable::new(), BorrowedCopyContract::expected(kind)).unwrap() +} + +fn effect_method(effect: ContextEffect) -> MethodHandle { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table); + let (iid, slot, name, signature) = match effect { + ContextEffect::AudioInitialize => ( + AUDIO_CLIENT, + 3, + "Initialize", + signature + .add_in(Type::winrt(table.i32_type())) + .add_in(Type::winrt(table.u32_type())) + .add_in(Type::winrt(table.i64_type())) + .add_in(Type::winrt(table.i64_type())) + .add_in(Type::audio_format()) + .add_nullable_in(Type::pointer()), + ), + ContextEffect::AudioInitializeShared => ( + AUDIO_CLIENT3, + 20, + "InitializeSharedAudioStream", + signature + .add_in(Type::winrt(table.u32_type())) + .add_in(Type::winrt(table.u32_type())) + .add_in(Type::audio_format()) + .add_nullable_in(Type::pointer()), + ), + ContextEffect::AudioGetService => ( + AUDIO_CLIENT, + 14, + "GetService", + signature + .add_in(Type::pointer()) + .add_out(Type::owned_com_pointer()), + ), + }; + super::super::register_interface(&table, "context-test", iid, InterfaceBase::IUnknown) + .add_method_at(slot, name, signature.with_context_effect(effect)) + .unwrap() + .method(slot) + .unwrap() +} + +fn initialize_with( + fixture: &CopyFixture, + context: &Identity, + format: AudioFormatValue, + mode: i32, + flags: u32, + shared3: bool, +) -> result::Result<()> { + let effect = if shared3 { + ContextEffect::AudioInitializeShared + } else { + ContextEffect::AudioInitialize + }; + let value = |v| Value::WinRt(v); + let args = if shared3 { + vec![ + value(WinRTValue::U32(flags)), + value(WinRTValue::U32(2)), + Value::AudioFormat(format), + value(WinRTValue::RawPtr(ptr::null_mut())), + ] + } else { + vec![ + value(WinRTValue::I32(mode)), + value(WinRTValue::U32(flags)), + value(WinRTValue::I64(100)), + value(WinRTValue::I64(0)), + Value::AudioFormat(format), + value(WinRTValue::RawPtr(ptr::null_mut())), + ] + }; + unsafe { + invoke_managed( + &effect_method(effect), + context, + &fixture.object("client")?, + &args, + ) + } + .map(|_| ()) +} + +fn initialized(fixture: &CopyFixture, mode: i32, flags: u32) -> Identity { + let context = Identity::for_object(&fixture.object("client").unwrap()).unwrap(); + initialize_with( + fixture, + &context, + AudioFormatValue::pcm(2, 48_000, 16).unwrap(), + mode, + flags, + false, + ) + .unwrap(); + context +} + +fn service( + fixture: &CopyFixture, + client: &Identity, + mut iid: GUID, +) -> result::Result<(IUnknown, Identity)> { + let mut result = unsafe { + invoke_managed( + &effect_method(ContextEffect::AudioGetService), + client, + &fixture.object("client")?, + &[Value::WinRt(cell(&mut iid))], + ) + }?; + let (Value::WinRt(WinRTValue::RawPtr(pointer)), super::super::PointerOutputKind::Com) = + result.values.remove(0) + else { + panic!("service output"); + }; + Ok(( + unsafe { IUnknown::from_raw(pointer) }, + result.output_context.unwrap(), + )) +} + +fn count(fixture: &CopyFixture, event: &str) -> usize { + fixture + .events() + .iter() + .filter(|entry| entry.starts_with(event)) + .count() +} + +#[test] +fn borrowed_copy_descriptor_drift_and_effect_signature_reject_before_dispatch() { + for kind in [ + CopyKind::AudioRender, + CopyKind::AudioCapture, + CopyKind::BitmapBgra8, + CopyKind::MediaBuffer, + ] { + let mut descriptor = BorrowedCopyContract::expected(kind); + descriptor.acquire.slot += 1; + assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); + let mut descriptor = BorrowedCopyContract::expected(kind); + descriptor.acquire.storage.clear(); + assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); + let mut descriptor = BorrowedCopyContract::expected(kind); + descriptor.audio_origin_required = !descriptor.audio_origin_required; + assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); + } + let table = MetadataTable::new(); + let signature = + MethodSignature::new(&table).with_context_effect(ContextEffect::AudioInitialize); + assert!( + super::super::register_interface(&table, "bad", AUDIO_CLIENT, InterfaceBase::IUnknown) + .add_method_at(3, "Initialize", signature) + .is_err() + ); +} + +#[test] +fn borrowed_copy_audio_format_proof_uses_initialized_not_mix_layout() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0x80000000); // AUTOCONVERTPCM + let table = MetadataTable::new(); + let mix = + super::super::register_interface(&table, "mix", AUDIO_CLIENT, InterfaceBase::IUnknown) + .add_method_at( + 8, + "GetMixFormat", + MethodSignature::new(&table).add_out(Type::audio_format()), + ) + .unwrap(); + let result = unsafe { + mix.method(8) + .unwrap() + .invoke_values_with_output_kinds(fixture.object("client").unwrap().as_raw(), &[]) + } + .unwrap(); + let Value::AudioFormat(mix) = &result[0].0 else { + panic!() + }; + assert_eq!(mix.block_align(), 1); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &render, &[9, 8, 7, 6, 5, 4, 3, 2]) + .unwrap(); + assert_eq!(&fixture.bytes()[..8], &[9, 8, 7, 6, 5, 4, 3, 2]); + assert!(fixture.events().contains(&"render.acquire.2".into())); + assert!(fixture.events().contains(&"render.release.2.0".into())); +} + +#[test] +fn borrowed_copy_audio_requires_both_observed_successful_effects() { + let fixture = CopyFixture::default(); + let render = fixture.object("render").unwrap(); + let render_context = Identity::for_object(&render).unwrap(); + assert!( + plan(CopyKind::AudioRender) + .write_frames_copy(&render_context, &render, &[0; 4]) + .is_err() + ); + let client = Identity::for_object(&fixture.object("client").unwrap()).unwrap(); + fixture.configure("initializeHr", 0x80004005).unwrap(); + assert!( + initialize_with( + &fixture, + &client, + AudioFormatValue::pcm(2, 48_000, 16).unwrap(), + 0, + 0, + false + ) + .is_err() + ); + assert!(client.inner.initialized.borrow().is_none()); + fixture.configure("externalInitialized", 1).unwrap(); + fixture.configure("initializeHr", 0).unwrap(); + assert!( + initialize_with( + &fixture, + &client, + AudioFormatValue::pcm(2, 48_000, 16).unwrap(), + 0, + 0, + false + ) + .is_err() + ); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + assert!( + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &render, &[0; 4]) + .is_err() + ); + assert_eq!(count(&fixture, "render.acquire"), 0); +} + +#[test] +fn borrowed_copy_audio_failed_reinitialization_cannot_overwrite_provenance() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + assert!( + initialize_with( + &fixture, + &client, + AudioFormatValue::pcm(1, 44_100, 8).unwrap(), + 1, + 4, + false + ) + .is_err() + ); + let stored = client.inner.initialized.borrow(); + let stored = stored.as_ref().unwrap(); + assert_eq!(stored.format.block_align(), 4); + assert_eq!((stored.share_mode, stored.flags), (0, 0)); +} + +#[test] +fn borrowed_copy_audio_shared_initialization_and_unsupported_format() { + let fixture = CopyFixture::default(); + let context = Identity::for_object(&fixture.object("client").unwrap()).unwrap(); + initialize_with( + &fixture, + &context, + AudioFormatValue::pcm(2, 48_000, 16).unwrap(), + 9, + 4, + true, + ) + .unwrap(); + assert_eq!( + context + .inner + .initialized + .borrow() + .as_ref() + .unwrap() + .share_mode, + 0 + ); + let (capture, origin) = service(&fixture, &context, AUDIO_CAPTURE).unwrap(); + assert_eq!( + plan(CopyKind::AudioCapture) + .read_packet_copy(&origin, &capture) + .unwrap() + .unwrap() + .data + .unwrap() + .len(), + 8 + ); + let fixture = CopyFixture::default(); + let context = Identity::for_object(&fixture.object("client").unwrap()).unwrap(); + let compressed = AudioFormatValue::wave_format_ex(2, 2, 48_000, 100, 4, 4, vec![1; 6]).unwrap(); + initialize_with(&fixture, &context, compressed, 0, 0, false).unwrap(); + let (render, origin) = service(&fixture, &context, AUDIO_RENDER).unwrap(); + assert!( + plan(CopyKind::AudioRender) + .write_frames_copy(&origin, &render, &[0; 4]) + .is_err() + ); + assert_eq!(count(&fixture, "render.acquire"), 0); +} + +#[test] +fn borrowed_copy_identity_aliasing_and_context_lifetime_are_canonical() { + let mut fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + let unknown = query(&render, &IUnknown::IID).unwrap(); + assert_ne!( + unknown.as_raw(), + render.as_raw(), + "fixture provides distinct canonical and service views" + ); + let alias = Identity::for_object(&unknown).unwrap(); + assert!(context.matches(&alias)); + drop(context); + drop(client); + fixture.release_owners(); + assert_eq!(count(&fixture, "drop.client"), 0); + plan(CopyKind::AudioRender) + .write_frames_copy(&alias, &unknown, &[3; 8]) + .unwrap(); + drop(alias); + assert_eq!(count(&fixture, "drop.client"), 1); + drop(render); + drop(unknown); + assert_eq!(count(&fixture, "drop.render"), 1); +} + +#[test] +fn borrowed_copy_rejects_wrong_service_or_forged_context() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + fixture.configure("serviceWrong", 1).unwrap(); + assert!(service(&fixture, &client, AUDIO_RENDER).is_err()); + assert_eq!(count(&fixture, "render.acquire"), 0); + fixture.configure("serviceWrong", 0).unwrap(); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + let other = CopyFixture::default().object("render").unwrap(); + assert!( + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &other, &[0; 4]) + .is_err() + ); + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &render, &[0; 4]) + .unwrap(); + let other_client = CopyFixture::default(); + let other_context = initialized(&other_client, 0, 0); + other_client.share_render_service(&fixture); + assert!(service(&other_client, &other_context, AUDIO_RENDER).is_err()); + // The rejected mapping cannot disturb the original service provenance. + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &render, &[0; 4]) + .unwrap(); +} + +#[test] +fn borrowed_copy_render_zero_silence_bounds_and_abort() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + let plan = plan(CopyKind::AudioRender); + plan.write_frames_copy(&context, &render, &[]).unwrap(); + plan.write_silence(&context, &render, 0).unwrap(); + assert_eq!(count(&fixture, "render.acquire"), 0); + assert_eq!(count(&fixture, "audio.capacity"), 0); + assert!(plan.write_frames_copy(&context, &render, &[0; 3]).is_err()); + assert!(plan.write_silence(&context, &render, 9).is_err()); + fixture.configure("renderNull", 1).unwrap(); + plan.write_silence(&context, &render, 2).unwrap(); + assert!(fixture.events().contains(&"render.release.2.2".into())); + assert!(plan.write_frames_copy(&context, &render, &[0; 8]).is_err()); + assert!(fixture.events().contains(&"render.release.0.0".into())); + context.ensure_idle().unwrap(); + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 1, EVENT_CALLBACK); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + assert!(plan.write_frames_copy(&context, &render, &[0; 4]).is_err()); + assert_eq!(count(&fixture, "render.acquire"), 0); +} + +#[test] +fn borrowed_copy_capture_empty_silent_timestamps_and_exclusive_packets() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 1, 0); + let (capture, context) = service(&fixture, &client, AUDIO_CAPTURE).unwrap(); + let plan = plan(CopyKind::AudioCapture); + fixture.configure("captureHr", BUFFER_EMPTY as u32).unwrap(); + assert!(plan.read_packet_copy(&context, &capture).unwrap().is_none()); + assert_eq!(count(&fixture, "capture.release"), 0); + fixture.configure("captureHr", 0).unwrap(); + fixture.configure("captureNull", 1).unwrap(); + fixture + .configure("captureFlags", SILENT | TIMESTAMP_ERROR) + .unwrap(); + let packet = plan.read_packet_copy(&context, &capture).unwrap().unwrap(); + assert!(packet.data.is_none()); + assert_eq!(packet.frames, 2); + assert!(packet.device_position.is_none() && packet.qpc_position.is_none()); + fixture.configure("captureNull", 0).unwrap(); + fixture.configure("captureFlags", 1).unwrap(); + let packet = plan.read_packet_copy(&context, &capture).unwrap().unwrap(); + assert_eq!(packet.data.unwrap(), (0..8).collect::>()); + assert_eq!( + (packet.device_position, packet.qpc_position), + (Some(123), Some(456)) + ); + assert_eq!(count(&fixture, "capture.next"), 0); + assert_eq!(count(&fixture, "capture.release.2"), 2); +} + +#[test] +fn borrowed_copy_capture_validation_zero_abort_and_unknown_success_poison() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + let (capture, context) = service(&fixture, &client, AUDIO_CAPTURE).unwrap(); + let plan = plan(CopyKind::AudioCapture); + fixture.configure("captureFrames", 9).unwrap(); + assert!(plan.read_packet_copy(&context, &capture).is_err()); + fixture.configure("captureFrames", 2).unwrap(); + fixture.configure("captureNull", 1).unwrap(); + assert!(plan.read_packet_copy(&context, &capture).is_err()); + assert_eq!(count(&fixture, "capture.release.0"), 2); + fixture.configure("captureHr", 2).unwrap(); + assert!(plan.read_packet_copy(&context, &capture).is_err()); + assert!(context.ensure_idle().is_err()); + assert_eq!(count(&fixture, "capture.release"), 2); +} + +#[test] +fn borrowed_copy_reentrancy_guards_precede_acquire_and_finalization() { + let fixture = CopyFixture::default(); + let client = initialized(&fixture, 0, 0); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + let rejected = Rc::new(Cell::new(0)); + let checked = rejected.clone(); + let alias = context.clone(); + let client_alias = client.clone(); + fixture.hook(Some(Rc::new(move |event| { + if event.starts_with("render.") { + if alias.ensure_idle().is_err() + && client_alias.ensure_idle().is_err() + && callbacks_suppressed() + { + checked.set(checked.get() + 1); + } + } + }))); + plan(CopyKind::AudioRender) + .write_frames_copy(&context, &render, &[0; 4]) + .unwrap(); + fixture.hook(None); + assert_eq!(rejected.get(), 2); + assert!(!callbacks_suppressed()); + context.ensure_idle().unwrap(); +} + +#[test] +fn borrowed_copy_cleanup_failures_are_exactly_once_and_poison_all_aliases() { + for (kind, service_iid, setting, prefix) in [ + ( + CopyKind::AudioRender, + Some(AUDIO_RENDER), + "renderReleaseHr", + "render.release", + ), + ( + CopyKind::AudioCapture, + Some(AUDIO_CAPTURE), + "captureReleaseHr", + "capture.release", + ), + (CopyKind::MediaBuffer, None, "mediaUnlockHr", "media.unlock"), + ] { + let fixture = CopyFixture::default(); + let (object, context, client) = if let Some(iid) = service_iid { + let client = initialized(&fixture, 0, 0); + let (object, context) = service(&fixture, &client, iid).unwrap(); + (object, context, Some(client)) + } else { + let object = fixture.object("media").unwrap(); + let context = Identity::for_object(&object).unwrap(); + (object, context, None) + }; + fixture.configure(setting, 0x80004005).unwrap(); + let plan = plan(kind); + let invoke = || match kind { + CopyKind::AudioRender => plan.write_frames_copy(&context, &object, &[0; 4]), + CopyKind::AudioCapture => plan.read_packet_copy(&context, &object).map(|_| ()), + CopyKind::MediaBuffer => plan.read_copy(&context, &object).map(|_| ()), + CopyKind::BitmapBgra8 => unreachable!(), + }; + assert!(invoke().is_err()); + assert!(invoke().is_err()); + assert_eq!(count(&fixture, prefix), 1); + if let Some(client) = client { + assert!(client.ensure_idle().is_err()); + } + drop(context); + assert_eq!(count(&fixture, prefix), 1); + } +} + +#[test] +fn borrowed_copy_wic_short_final_row_stride_changes_and_cleanup() { + super::super::initialize_apartment(super::super::ApartmentType::SingleThreaded).unwrap(); + let fixture = CopyFixture::default(); + let bitmap = fixture.object("bitmap").unwrap(); + let context = Identity::for_object(&bitmap).unwrap(); + let plan = plan(CopyKind::BitmapBgra8); + let copy = plan + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .unwrap(); + assert_eq!(copy.data, (0..8).chain(12..20).collect::>()); + assert_eq!((copy.width, copy.height), (2, 2)); + fixture.configure("wicStride", 8).unwrap(); + fixture.configure("wicCount", 16).unwrap(); + assert_eq!( + plan.read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .unwrap() + .data, + (0..16).collect::>() + ); + fixture.configure("wicCount", 15).unwrap(); + assert!( + plan.read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + fixture.configure("wicStride", 7).unwrap(); + assert!( + plan.read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + fixture.configure("wicWrongFormat", 1).unwrap(); + assert!( + plan.read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.release"), 5); + assert!( + !fixture + .events() + .iter() + .any(|event| event.contains("unlock")) + ); + assert!( + plan.read_locked_bgra8_copy(&context, &bitmap, [0, 0, 3, 2]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.acquire"), 5); +} + +#[test] +fn borrowed_copy_wic_failure_owned_output_and_mta_restriction() { + std::thread::spawn(|| { + super::super::initialize_apartment(super::super::ApartmentType::SingleThreaded).unwrap(); + let fixture = CopyFixture::default(); + let bitmap = fixture.object("bitmap").unwrap(); + let context = Identity::for_object(&bitmap).unwrap(); + fixture.configure("wicLockHr", 0x80004005).unwrap(); + assert!( + plan(CopyKind::BitmapBgra8) + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.release"), 1); + fixture.configure("wicLockHr", 0).unwrap(); + fixture.configure("wicQueryHr", 0x80004005).unwrap(); + assert!( + plan(CopyKind::BitmapBgra8) + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.release"), 2); + context.ensure_idle().unwrap(); + }) + .join() + .unwrap(); + super::super::initialize_apartment(super::super::ApartmentType::MultiThreaded).unwrap(); + let fixture = CopyFixture::default(); + let bitmap = fixture.object("bitmap").unwrap(); + let context = Identity::for_object(&bitmap).unwrap(); + assert!( + plan(CopyKind::BitmapBgra8) + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.acquire"), 0); +} + +#[test] +fn borrowed_copy_media_native_lengths_owned_results_and_setlength_failures() { + let fixture = CopyFixture::default(); + let media = fixture.object("media").unwrap(); + let context = Identity::for_object(&media).unwrap(); + let plan = plan(CopyKind::MediaBuffer); + let original = plan.read_copy(&context, &media).unwrap(); + plan.replace_copy(&context, &media, &[8, 9, 10]).unwrap(); + assert_eq!(plan.read_copy(&context, &media).unwrap(), [8, 9, 10]); + assert_eq!(original, [0, 1, 2, 3]); + assert!(plan.replace_copy(&context, &media, &[0; 17]).is_err()); + fixture.configure("mediaCurrent", 17).unwrap(); + assert!(plan.read_copy(&context, &media).is_err()); + fixture.configure("mediaCurrent", 3).unwrap(); + fixture.configure("mediaSetHr", 0x80004005).unwrap(); + assert!(plan.replace_copy(&context, &media, &[4; 4]).is_err()); + assert_eq!( + count(&fixture, "media.acquire"), + count(&fixture, "media.unlock") + ); + // Writes may already have changed bytes when SetCurrentLength fails. + assert_eq!(&fixture.bytes()[..4], &[4; 4]); + fixture.configure("mediaSetHr", 0).unwrap(); + fixture.configure("mediaCurrent", 0).unwrap(); + fixture.configure("mediaNull", 1).unwrap(); + assert!(plan.read_copy(&context, &media).unwrap().is_empty()); + fixture.configure("mediaLockHr", 0x80004005).unwrap(); + let releases = count(&fixture, "media.unlock"); + assert!(plan.read_copy(&context, &media).is_err()); + assert_eq!(count(&fixture, "media.unlock"), releases); +} + +#[test] +fn borrowed_copy_wrong_thread_rejects_without_dispatch_or_release() { + let fixture = CopyFixture::default(); + let object = fixture.object("media").unwrap(); + let context = Identity::for_object(&object).unwrap(); + let address = (&context as *const Identity).addr(); + // Test-only cross-thread probe calls the guard, which reads only ThreadId + // before rejecting. No Rc operation or apartment reference is touched there. + let rejected = std::thread::spawn(move || unsafe { + (&*(address as *const Identity)).ensure_thread().is_err() + }) + .join() + .unwrap(); + assert!(rejected); + assert!(fixture.events().is_empty()); + let key = context.inner._canonical.as_raw().addr(); + let rejected_claim = std::thread::spawn(move || identity_owner(key, true).is_err()) + .join() + .unwrap(); + assert!( + rejected_claim, + "independent cross-thread rewrapping cannot create a second gate" + ); + assert!(fixture.events().is_empty()); + plan(CopyKind::MediaBuffer) + .read_copy(&context, &object) + .unwrap(); +} + +#[test] +fn borrowed_copy_uncompressed_layout_and_checked_extents() { + assert_eq!( + uncompressed_block_align(&AudioFormatValue::pcm(2, 48_000, 16).unwrap()), + Some(4) + ); + let malformed = AudioFormatValue::wave_format_ex(1, 2, 48_000, 96_000, 2, 16, vec![]).unwrap(); + assert_eq!(uncompressed_block_align(&malformed), None); + let mut extra = vec![16, 0, 3, 0, 0, 0]; + extra.extend_from_slice(&[1, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113]); + let extensible = + AudioFormatValue::wave_format_ex(0xfffe, 2, 48_000, 192_000, 4, 16, extra.clone()).unwrap(); + assert_eq!(uncompressed_block_align(&extensible), Some(4)); + extra[0] = 17; + assert_eq!( + uncompressed_block_align( + &AudioFormatValue::wave_format_ex(0xfffe, 2, 48_000, 192_000, 4, 16, extra).unwrap() + ), + None + ); + assert!(frame_bytes(u32::MAX, 4).is_err()); + assert!(frame_bytes(2, usize::MAX).is_err()); + assert!(validate_pointer(ptr::null(), 1).is_err()); + assert!(validate_pointer(ptr::null(), 0).is_ok()); +} + +#[test] +fn borrowed_copy_live_stock_windows_wic_and_linear_mf() -> result::Result<()> { + use windows::Win32::{ + Graphics::Imaging::{ + CLSID_WICImagingFactory, GUID_WICPixelFormat32bppBGRA, IWICImagingFactory, + }, + Media::MediaFoundation::MFCreateMemoryBuffer, + System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance}, + }; + super::super::initialize_apartment(super::super::ApartmentType::SingleThreaded)?; + // SDK adapters are confined to test acquisition. All buffer transactions + // below execute the same completed MethodHandles as generated JavaScript. + let factory: IWICImagingFactory = + unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)? }; + let pixels = [7u8; 16]; + let bitmap = + unsafe { factory.CreateBitmapFromMemory(2, 2, &GUID_WICPixelFormat32bppBGRA, 8, &pixels)? }; + let bitmap = bitmap.cast::()?; + let context = Identity::for_object(&bitmap)?; + let copy = + plan(CopyKind::BitmapBgra8).read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 2])?; + assert_eq!(copy.data, pixels); + let media = unsafe { MFCreateMemoryBuffer(16)? }.cast::()?; + let context = Identity::for_object(&media)?; + let media_plan = plan(CopyKind::MediaBuffer); + media_plan.replace_copy(&context, &media, &[1, 2, 3, 4])?; + assert_eq!(media_plan.read_copy(&context, &media)?, [1, 2, 3, 4]); + Ok(()) +} + +#[test] +fn borrowed_copy_unknown_initialization_and_finalizer_successes_fail_closed() { + let fixture = CopyFixture::default(); + let context = Identity::for_object(&fixture.object("client").unwrap()).unwrap(); + fixture.configure("initializeHr", 1).unwrap(); + assert!( + initialize_with( + &fixture, + &context, + AudioFormatValue::pcm(2, 48_000, 16).unwrap(), + 0, + 0, + false, + ) + .is_err() + ); + assert!(context.inner.initialized.borrow().is_none()); + assert!(context.ensure_idle().is_err()); + + let fixture = CopyFixture::default(); + let context = initialized(&fixture, 0, 0); + let (render, service_context) = service(&fixture, &context, AUDIO_RENDER).unwrap(); + fixture.configure("renderReleaseHr", 1).unwrap(); + let plan = plan(CopyKind::AudioRender); + assert!( + plan.write_frames_copy(&service_context, &render, &[0; 4]) + .is_err() + ); + assert!( + plan.write_frames_copy(&service_context, &render, &[0; 4]) + .is_err() + ); + assert_eq!(count(&fixture, "render.release"), 1); + assert!(context.ensure_idle().is_err()); +} diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index ec439e61..6284f7f3 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -434,13 +434,13 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,333 | -| `exact_registry_dependent` | 364 | +| `standard_derived` | 5,332 | +| `exact_registry_dependent` | 365 | | **Total** | **5,697** | -The registry contains **506 declared entries**, all 506 match the pinned -metadata, and 415 distinct entries are consumed by safe plans. Safe plans have -671 entry/interface dependencies and 417 family/interface dependencies. +The registry contains **532 declared entries**, all 532 match the pinned +metadata, and 431 distinct entries are consumed by complete safe plans. These plans have +693 entry/interface dependencies and 424 family/interface dependencies. Per-interface dependency-set totals also include 5,983 metadata-attribute dependencies and 26,134 COM-standard-rule dependencies. @@ -458,6 +458,8 @@ dependencies and 26,134 COM-standard-rule dependencies. | `counted-buffer` | 16 | | `semantic-hresult` | 3 | | `compound-dispatch` | 1 | +| `borrowed-storage` | 15 | +| `contextual-effect` | 7 | Family rollups deliberately count each interface once per family: @@ -479,6 +481,19 @@ Family rollups deliberately count each interface once per family: | `shell.flag-selected-string.v1` | 1 | 1 | 3 | | `wmi.conditional-output.v1` | 7 | 7 | 1 | | `audio.conditional-output.v1` | 1 | 1 | 3 | +| `audio.context-effect.v1` | 3 | 3 | 3 | +| `buffers.borrowed-copy.v1` | 23 | 13 | 4 | + +The new selectors are defined in +[`com_borrowed_metadata.rs`](../../tools/dynwinrt-codegen/src/com_borrowed_metadata.rs). +They preserve full method fingerprints, exact declaring IID/slot, citations, +and the pinned Win32Metadata SHA256. Three effects observe actual successful +Audio initialization/GetService calls; 23 entries validate the storage and +complete vtable evidence used by the copy plans. WIC's previously complete +interface remains complete, now with an exact-evidence copy augmentation. +The Audio render/capture and linear MF copy-only facades remain **excluded** +from the complete-interface count. Their useful copy operations are not a +claim that their unrestricted native methods are safely projected. Universal rule dependencies are: @@ -526,14 +541,15 @@ controlled contract-family ablation, remains later registry migration work. The strict contract data schema and its registry `manifest.json` remain version 2. The capability summary is version 3, and generated unsafe support -manifests are version 11. +manifests are version 12. Seven WMI conditional-output entries and 149 output-ownership entries are -JSON-backed; the other 350 registered entries remain code-defined. All code and +JSON-backed; the other 376 registered entries remain code-defined. All code and data entries use the same selector-derived `entryId`, typed `familyId`, selector/fingerprint/citation catalog, and pinned-metadata validation path. -Separately, PR1 raises the generated COM file-ownership manifest -`com/.dynwinrt-com-manifest.json` from version 2 to version 3. Generated safe +Separately, PR1 raised the generated COM file-ownership manifest +`com/.dynwinrt-com-manifest.json` from version 2 to version 3; borrowed-copy +context effects now require version 4. Generated safe classes must register descriptors for the public runtime `/com` `projectAs` entrypoint and typed `IMMDevice.activate` through private `/com/unsafe` helpers. Delete existing generated bindings and completely regenerate every diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index d67a3b38..a6200663 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -445,10 +445,10 @@ Generation emits `generated/com/unsafe/support.json`: ```json { - "schemaVersion": 11, + "schemaVersion": 12, "interfaces": [ { - "schemaVersion": 11, + "schemaVersion": 12, "metadata": { "setSha256": "...", "files": ["..."], diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 55b5bf76..7a17f502 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -241,6 +241,175 @@ reads the default speaker endpoint's channel count through the real export. Caller/UI-thread requirements remain those of [ActivateAudioInterfaceAsync](https://learn.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-activateaudiointerfaceasync). +## Bounded borrowed-buffer copies + +Audio, WIC, and linear Media Foundation storage share a COM-local +`BorrowedCopyPlan`. These are **synchronous owned-copy transactions**, not +native-backed Node `Buffer`/`ArrayBuffer` views or caller-asserted pointer leases. +They preserve the metadata → semantic contract → completed MethodHandle/libffi +call → projection boundary. The runtime contains no per-interface SDK calling +adapter; typed SDK acquisition is confined to stock-Windows tests. + +| Generated receiver | Owned-copy operations | Extent and finalization | +| --- | --- | --- | +| `IAudioRenderClient` | `writeFramesCopy(data)`, `writeSilence(frames)` | Frames use the format from observed successful initialization and must fit native `GetBufferSize`. Release the complete request, or zero frames on abort. | +| `IAudioCaptureClient` | `readPacketCopy()` | Native packet frames × proven initialized block alignment, bounded by native capacity. Return an owned data packet, a tagged silent packet, or `null` for empty. Release the full packet after copying, zero on abort. | +| `IWICBitmap` | `readLockedBgra8Copy(rect)` | Acquire a READ lock, obtain native size/stride/pixel format/byte count, copy row pixels without padding, release the owned lock reference. | +| `IMFMediaBuffer` | `readCopy()`, `replaceCopy(data)` | Request both native current and maximum lengths. Copy current bytes, or replace within maximum and call `SetCurrentLength`; always Unlock after successful Lock. | + +Render/capture and MF are explicitly **copy-only facades**, not complete native +interface projections. They do not expose `GetBuffer`, `ReleaseBuffer`, `Lock`, +or `Unlock` independently. WIC retains its previously complete native interface +surface (including acquisition of an opaque owned lock) and adds the copy +operation. An external lock never gains byte access or writable rights from +this operation. The complete safe census remains **5,697 / 7,929**; it does not +count the three copy-only facades as newly complete interfaces. + +### Private context and lifecycle + +The plan describes receiver IID, acquire method, private output-cell storage, +native extent source, access, owner, normal/abort finalizers, and apartment +prerequisites. All signatures and cleanup recipes are prepared before native +acquisition. Output cells are private stable storage, not language values: the +executor cannot read them before the transaction classifies the HRESULT. + +```text +Idle -> Acquiring -> Active -> Finalizing -> Idle + \ unexpected success / cleanup failure -> Poisoned +``` + +The canonical-IUnknown sidecar is private to COM carriers. Owner-thread +registry entries are weak; each live sidecar strongly retains its canonical +identity, preventing stale address-key reuse. A second process-local weak map +contains only pointer-free owner-thread tokens and rejects independent +cross-thread claims for the same canonical identity. No native reference or +Rc state crosses that map, and no registry lock spans native dispatch. +Managed COM carriers also share an initially empty context slot from creation, +pinned by their owned references. Thus aliases created before the first copy +still retain its later provenance or poison after the first copier is released, +without adding a canonical-reference pin to unrelated ordinary COM calls. +A service retains its originating +client context and exact client interface view, without a reverse sidecar +reference or cycle. QI, `projectAs`, and independently rewrapped aliases recover +the same context while any managed holder retains it. Conflicting mappings +fail closed. + +The receiver and required owner gates enter `Acquiring` **before** native +dispatch. No registry/state lock is held across a native call. A successful +acquire arms cleanup before pointer/range validation or allocation. Direct JS +callback entry is rejected while the synchronous transaction is in progress; +no JS callback receives a borrow. Finalization is taken exactly once before it +runs. Failure poisons the shared context, suppresses all output bytes, and +never triggers a speculative Drop retry. Writes are **not** promised atomic +rollback, particularly if `SetCurrentLength` fails after copying. + +Operations reject off the owning thread before touching native references. +Wrong-thread COM carrier destruction retains the existing leak-rather-than- +wrong-apartment-release policy, including the private sidecar. + +### Audio initialization is the extent proof + +Only actual successful calls carrying the exact metadata effect can record +provenance: + +* `IAudioClient::Initialize`, slot 3, format argument 4, share-mode argument 0, + stream-flags argument 1; +* `IAudioClient3::InitializeSharedAudioStream`, slot 20, format argument 2, + stream-flags argument 0, implicit shared mode; +* `IAudioClient::GetService`, slot 14, binds the returned render/capture + service to that client only after actual native success and verified service QI. + +These effects are inherited by the generated `IAudioClient2`/`IAudioClient3` +views. Failed or `AUDCLNT_E_ALREADY_INITIALIZED` calls neither create nor +overwrite the immutable record. There is no attach-format, assume-initialized, +or record-success API. An externally initialized client without observed +provenance cannot use the copy operations. `GetMixFormat` and a caller's +`blockAlign` are not proof: `AUTOCONVERTPCM` can make the initialized format +different from the engine mix format even in shared mode. + +Copy capability is granted only for validated PCM 8/16/24/32-bit containers, +IEEE float 32/64-bit containers, and supported 22-byte +WAVEFORMATEXTENSIBLE equivalents. Channels, valid/container bits, optional +channel mask, block alignment, sample rate and average byte rate must agree. +Other valid WAVEFORMATEX values retain initialization support but do not grant +byte-copy capability. Checked arithmetic and a 64 MiB operation cap restrict, +but never establish, a native extent. + +For render, IID `f294acfc-3146-4483-a7bf-addca7c260e2`, the plan uses GetBuffer +slot 3 and ReleaseBuffer slot 4. Input is staged into owned Rust bytes before +acquisition; frames are derived from that byte count. Zero requests do not +acquire/release a buffer. Silence uses `AUDCLNT_BUFFERFLAGS_SILENT` without +touching the payload pointer. **Exclusive event-driven render is excluded** +because a zero-frame abort is not valid for that mode. + +For capture, IID `c8adbd64-e71e-48a0-a4de-185c395cd317`, GetBuffer slot 3 has five +output cells, and ReleaseBuffer is slot 4. The exact semantic-HRESULT override +recognizes only S_OK as acquisition and `AUDCLNT_S_BUFFER_EMPTY` as no +acquisition. Empty returns without reading any output cell or releasing a +packet. Unknown success poisons rather than guessing. SILENT ignores the data +pointer, including NULL; TIMESTAMP_ERROR makes timestamps unavailable. +The plan never calls shared-only GetNextPacketSize, so it also handles +exclusive capture. Automated capture coverage is **fake-only**, never hardware +recording. + +### WIC and MF limits + +`IWICBitmap` IID `00000121-a8f2-4877-ba0a-fd2b6645fb94` uses absolute slot 8 +Lock with an explicit validated rectangle and fixed READ flags=1. +Its owned `IWICBitmapLock` IID `00000123-a8f2-4877-ba0a-fd2b6645fb94` supplies +GetSize/Stride/DataPointer/PixelFormat at slots 3/4/5/6. +The current apartment must be STA because GetDataPointer is unavailable in +MTA. Only BGRA8 GUID `6fddc324-4e03-4bfe-b185-3d77768dc90f` is accepted. +The last-row span `(height - 1) * stride + width * 4` must fit the native byte +count; final-row padding is not required or read. The returned Buffer contains +packed rows. There is no invented Unlock: cleanup releases the acquired lock. + +`IMFMediaBuffer` IID `045fa593-8799-42b8-bc8d-8968c6453507` uses Lock/Unlock at +slots 3/4 and SetCurrentLength at slot 6. Both Lock length outputs are requested, +`current <= max` is checked, and the returned pointer is never freed with +CoTaskMemFree. Lock is not native cross-thread synchronization: the gate +coordinates this library's aliases, not arbitrary external users. +General signed-pitch/plane `IMF2DBuffer`/`IMF2DBuffer2` views remain unsupported. +Caller-provided height or stride is never treated as native memory bounds. + +### Evidence and regeneration + +[`com_borrowed_metadata.rs`](../../tools/dynwinrt-codegen/src/com_borrowed_metadata.rs) +contains all 26 exact selectors, full source fingerprints and Microsoft +citations. The configured metadata must include Win32Metadata +**71.0.14-preview**, SHA256 +`B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`. +The complete inherited interfaces and required owner/lock dependencies are +validated, not just acquisition methods. Runtime descriptors are versioned and +closed; absent/drifted signatures, storage roles, prerequisites or finalizers +fail before acquisition. Renderers only serialize the projected IR. + +COM file-ownership manifest **4** and unsafe support schema **12** require deletion and full regeneration +of older output. Do not mix pre-effect audio wrappers with new copy facades. +Coverage includes native fake tear-offs with complete SDK-correct vtables, +truthful QI, alias/context lifetime, failed initialization and differing mix +formats, no-JS reentrancy, exact-once poisoned cleanup, all packet states, +WIC final-row/stride cases, MF failure paths, and live stock-Windows WIC/MF. +Both x64 and live i686 execute the same runtime tests. + +Retained PR3 validation: + +| Check | Result | +| --- | --- | +| Core + codegen suites | All pass, including WinRT snapshots and 306 core / 421 codegen / 66 CLI unit tests; the existing WinAppSDK-dependent initialization test remains ignored. | +| Borrowed-copy native ABI | 20 tests pass on x64 and 20 on live i686; i686 N-API binding compile passes. | +| Node functional regressions | 89 pass, including eight copy scenarios, ten one-shot scenarios, existing generated ownership contracts, package/type checks and callback regressions. | +| Stock-Windows E2E | 38 WinRT and 17 Classic COM scenarios pass. WIC and linear MF copy transactions also pass against real OS objects in the native suite. | +| Census determinism | Two independent runs produce seven byte-identical artifacts; the complete count remains 5,697. | + +The separate WinUI scheduled-start test has a timing-sensitive 1,000 ms +`nextTick` assertion. AVA runs intermittently exceeded it on this host. +An exact build of parent commit `247383c` reproduced the same failure +(1,729.8 ms); the current build also passed in isolation. Three paired direct +runs of the unchanged harness passed for both parent and current runtimes +(roughly 132–150 ms). No timing threshold, WinUI implementation, or +preceding-PR invariant was relaxed. + ## Size of Windows.Win32.winmd The counts below are exact for @@ -637,8 +806,9 @@ Separate WinRT and COM invocations may target the same output directory in either order. The generated package manifest is rebuilt from both domains without adding COM exports to the WinRT root. -PR1 raises the generated COM file-ownership manifest -`com/.dynwinrt-com-manifest.json` from version 2 to **version 3**. Every +PR1 raised the generated COM file-ownership manifest +`com/.dynwinrt-com-manifest.json` from version 2 to version 3. Borrowed-copy +context effects now require **version 4**. Every generated safe class now registers a descriptor through private `@microsoft/dynwinrt/com/unsafe` helpers. Public `projectAs` remains on the runtime `@microsoft/dynwinrt/com` entrypoint, and generated diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 8ea51c7f..5b8f46eb 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -5,8 +5,9 @@ GUIDs, IIDs, CLSIDs, and REFIIDs. > **Status: preview, under active development.** Generated bindings are > available for interfaces whose complete ABI, layout, ownership, and cleanup -> contracts are validated. Unsupported interfaces fail closed instead of -> emitting a partial wrapper. See +> contracts are validated. Unsupported native methods fail closed. The explicitly +> bounded borrowed-copy facades below expose only their documented transactions +> and are not counted as complete interface support. See > [Classic COM support](../../architecture/classic-com-support.md) for the > current coverage baseline and known gaps. @@ -135,13 +136,14 @@ Generated output is placed in `generated/com/`. Internally, the `.js` files impo value types from `@microsoft/dynwinrt/com`. The generator records files per top-level COM root in -`generated/com/.dynwinrt-com-manifest.json`, currently version 3. Within the +`generated/com/.dynwinrt-com-manifest.json`, currently version 4. Within the same manifest version, regenerating a root removes files it no longer owns, while files shared with or generated by other roots remain intact. -**PR1 upgrade requirement:** version 3 replaces version 2 because every -generated safe COM class now registers a descriptor for `projectAs` and typed -endpoint activation. Delete the existing generated bindings directory and +**Upgrade requirement:** PR1 introduced version 3 for registered `projectAs` +and typed endpoint activation. Borrowed-copy support requires version 4 so +every selected audio initialization/GetService wrapper carries its context +effects. Delete the existing generated bindings directory and completely regenerate all selected roots with the matching updated runtime and codegen. There is no in-place migration: do not edit the manifest version, regenerate only one old root, or mix old and new generated classes. @@ -731,6 +733,73 @@ a default speaker endpoint and only activates `IAudioEndpointVolume` and reads its channel count; it does not record audio, access a microphone, or modify endpoint settings. +### 5.7 Borrowed native storage: use owned copies + +Generate the Audio client and copy receivers together. After upgrading to +COM manifest **4** / unsafe support schema **12**, delete the old generated output and regenerate it in +full; do not combine old audio initialization wrappers with new copy facades. + +```powershell +npx dynwinrt-codegen generate --winmd $winmd ` + --class-name Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.Media.Audio.IAudioRenderClient,Windows.Win32.Media.Audio.IAudioCaptureClient,Windows.Win32.Graphics.Imaging.IWICBitmap,Windows.Win32.Media.MediaFoundation.IMFMediaBuffer ` + --output .\generated +``` + +Audio requires the format from an **observed successful initialization**. +For a managed `IAudioClient` obtained through endpoint or one-shot activation: + +```js +import { projectAs } from "@microsoft/dynwinrt/com"; +import { IAudioRenderClient } from "./generated/com/index.js"; + +const format = client.getMixFormat(); +// GetMixFormat alone is not proof. This actual successful call records the +// exact format passed to Initialize, including when conversion flags are used. +client.initialize(0, 0, 200000n, 0n, format, null); + +const nativeService = client.getService(IAudioRenderClient.IID.toString()); +const render = projectAs(nativeService, IAudioRenderClient); +nativeService.release(); +try { + render.writeSilence(client.getBufferSize()); // e.g. prefill before Start + // render.writeFramesCopy(ownedPcmBytes); // whole initialized-format frames +} finally { + render.release(); +} +``` + +Copies need no caller block alignment or lifetime assertion. Services retain +their correct originating client/context even after its wrapper is released. +QI/projectAs aliases share the gate and failure state. An externally initialized +client without an observed initialization is rejected; there is no +`assumeInitialized` or attach-format escape hatch. + +| Receiver | API | Owned result / restriction | +| --- | --- | --- | +| `IAudioRenderClient` | `writeFramesCopy(Buffer \| Uint8Array)` | Derives whole frames from bytes; native capacity is authoritative. | +| `IAudioRenderClient` | `writeSilence(frames)` | Uses native SILENT semantics; zero requests do not acquire. Exclusive event-driven render is unsupported. | +| `IAudioCaptureClient` | `readPacketCopy()` | `null` for empty, or a packet with `kind`, `frames`, `flags`, `timestampsValid`, optional timestamps and owned `data`. Silent packets have no data Buffer. | +| `IWICBitmap` | `readLockedBgra8Copy({x,y,width,height})` | STA-only, native 32bpp BGRA, packed owned `data` plus native `width`/`height`. Padding is not copied. | +| `IMFMediaBuffer` | `readCopy()` / `replaceCopy(data)` | Linear storage only; use native current/max lengths and always Unlock. | + +WIC and MF accept already acquired managed interface values through `projectAs`; +this feature does not add arbitrary DLL exports or new acquisition factories. +WIC's existing owned-lock acquisition remains available, but an arbitrary lock +does not acquire byte-access or writable rights through the copy API. + +These operations are synchronous, with a 64 MiB per-operation safety cap. +No JS callback runs within a transaction, and no native address/backing store is +returned. SharedArrayBuffer and detached inputs are rejected before acquisition. +Cleanup failure throws, discards copy results and permanently poisons the +shared context; it is not retried by a finalizer. Writes may have taken effect +before a later error, so do not assume transactional rollback. + +Render/capture and MF are intentionally copy-only facades, not complete native +interfaces. General `IMF2DBuffer`/`IMF2DBuffer2` pitch/plane access and writable +external WIC locks are not supported. See the +[exact lifecycle/evidence contract](../../architecture/classic-com-support.md#bounded-borrowed-buffer-copies) +for supported formats, HRESULT handling, and validation. + ## 6. JavaScript projections of common native types | Native semantics | JavaScript/TypeScript | diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 03abd89e..78826204 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -374,21 +374,31 @@ classifies all 5,697 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,333 | -| `exact_registry_dependent` | 364 | +| `standard_derived` | 5,332 | +| `exact_registry_dependent` | 365 | -The registry declares 506 selector-specific entries; all 506 match pinned -metadata, 415 distinct entries are safe-consumed, and safe plans contain 671 -entry/interface plus 417 family/interface dependencies. They also consume +The registry declares 532 selector-specific entries; all 532 match pinned +metadata, 431 distinct entries are consumed by complete safe plans, which contain 693 +entry/interface plus 424 family/interface dependencies. They also consume 5,983 metadata-attribute and 26,134 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, borrowed-handle 54, ownership 182, parameter-direction 45, bounded-two-call 16, counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 4, -semantic-HRESULT 3, and compound-dispatch 1. Complete per-entry status, +semantic-HRESULT 3, compound-dispatch 1, borrowed-storage 15, and contextual-effect 7. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. These are dependency counts, not net contribution; no ablation claim is made. +Borrowed buffers now have synchronous **owned-copy** transactions for WASAPI +render/capture, STA WIC BGRA8 locks, and linear `IMFMediaBuffer`. Audio requires +observed successful initialization and GetService provenance; external +initialization alone grants no copy capability. Render/capture and linear MF +remain copy-only facades and do not increase the safe-complete census. WIC +preserves its existing native methods and adds a read-copy operation. +Exclusive event-driven render, native-backed JS views, writable external WIC +locks, and general signed-pitch/plane `IMF2DBuffer`/`IMF2DBuffer2` access remain +unsupported. See [the bounded copy contract](../architecture/classic-com-support.md#bounded-borrowed-buffer-copies). + Generic scalar BSTR output/replacement and 24 `STANDARD_NEXT` enumerator entries remain typed COM standard rules. Twenty-five safe interfaces consume the generic enumerator rule because one contract is inherited. diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index ddc73724..808f2d03 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -13,7 +13,7 @@ "raw_manual_contract": "Pointer ABI execution is expressible, but the caller must supply listed semantic/lifetime facts or externally created pointee storage. Missing layout for caller-created readable/writable T* storage is not manual; it is blocked.", "raw_metadata_complete": "Every outbound ABI fact is present and expressible by the Phase 1 raw runtime.", "raw_runtime_blocked": "At least one inherited or declared method uses a target ABI shape rejected by the current raw runtime.", - "safe_complete": "Existing complete safe generator succeeds for the full inherited interface.", + "safe_complete": "Complete safe generation succeeds for the full inherited interface; bounded copy-only facades are excluded.", "standard_derived": "A safe-complete interface whose validated plan consumes only WinMD facts and universal COM standard rules." }, "reason_definitions": { @@ -84,20 +84,22 @@ "safe_incomplete": 2232, "safeEvidence": { "safeComplete": 5697, - "standardDerived": 5333, - "exactRegistryDependent": 364, + "standardDerived": 5332, + "exactRegistryDependent": 365, "metadataFactOccurrences": 5983, "comStandardFactOccurrences": 26134, - "registeredExactEntries": 506, - "metadataMatchedExactEntries": 506, - "safeConsumedExactEntries": 415, - "exactEntryInterfaceDependencies": 671, - "exactFamilyInterfaceDependencies": 417, + "registeredExactEntries": 532, + "metadataMatchedExactEntries": 532, + "safeConsumedExactEntries": 431, + "exactEntryInterfaceDependencies": 693, + "exactFamilyInterfaceDependencies": 424, "byContractKind": { "borrowed-handle": 54, + "borrowed-storage": 15, "bounded-two-call": 16, "compound-dispatch": 1, "conditional-output": 10, + "contextual-effect": 7, "counted-buffer": 16, "enumerator-next": 74, "flag-selected-buffer": 3, @@ -109,6 +111,9 @@ }, "byEntryId": { "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": 3, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getservice.slot-14.v1": 3, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.initialize.slot-3.v1": 3, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.initializesharedaudiostream.slot-20.v1": 1, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.iesisdbcasresponseevent.2017cb03dc0f4c2483ca36307b2cd19f.getresponsedata.slot-11.param-0-pbdata.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.ieslicenserenewalresultevent.d5a48ef5a81b4df0acaa5e35e7ea45d4.getentitlementtoken.slot-17.param-0-pbdata.v1": 1, @@ -291,6 +296,19 @@ "automation.safearray.entry.windows-win32-ui-accessibility.iuiautomationtextedittextchangedeventhandler.92faa680e7044156931ae32d5bb38f3f.handletextedittextchangedevent.slot-3.param-2-eventstrings.v1": 1, "automation.safearray.entry.windows-win32-ui-accessibility.iuiautomationtextrange.a543cc6af4ae494b8239c814481187a8.getboundingrectangles.slot-10.param-0-boundingrects.v1": 3, "automation.safearray.entry.windows-win32-ui-accessibility.iuiautomationtextrange3.6a315d6955124c2e85f053fce6dd4bc2.getattributevalues.slot-24.param-2-attributevalues.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.lock.slot-8.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.setpalette.slot-9.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.setresolution.slot-10.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getdatapointer.slot-5.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getpixelformat.slot-6.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getsize.slot-3.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getstride.slot-4.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.copypalette.slot-6.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.copypixels.slot-7.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getpixelformat.slot-4.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getresolution.slot-5.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getsize.slot-3.v1": 1, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getbuffersize.slot-4.v1": 3, "buffers.bounded-two-call.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getblob.slot-15.v1": 15, "buffers.bounded-two-call.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.getrecorderguid.slot-4.param-0-pbyuniqueid.v1": 1, "buffers.counted-buffer.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.init.slot-3.param-0-pbyuniqueid.v1": 1, @@ -526,8 +544,10 @@ }, "byFamilyId": { "audio.conditional-output.v1": 3, + "audio.context-effect.v1": 3, "automation.idispatch-invoke.v1": 1, "automation.safearray.v1": 121, + "buffers.borrowed-copy.v1": 4, "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, @@ -579,6 +599,60 @@ "safeConsumed": true, "interfaceDependencies": 3 }, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getservice.slot-14.v1": { + "familyId": "audio.context-effect.v1", + "contractKind": "contextual-effect", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetService", + "slot": 14, + "parameter": null + }, + "sourceFingerprint": "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getservice", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.initialize.slot-3.v1": { + "familyId": "audio.context-effect.v1", + "contractKind": "contextual-effect", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "Initialize", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-initialize", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, + "audio.context-effect.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.initializesharedaudiostream.slot-20.v1": { + "familyId": "audio.context-effect.v1", + "contractKind": "contextual-effect", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient3", + "iid": "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42", + "method": "InitializeSharedAudioStream", + "slot": 20, + "parameter": null + }, + "sourceFingerprint": "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": { "familyId": "automation.idispatch-invoke.v1", "contractKind": "compound-dispatch", @@ -4986,6 +5060,420 @@ "safeConsumed": false, "interfaceDependencies": 0 }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.lock.slot-8.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "Lock", + "slot": 8, + "parameter": null + }, + "sourceFingerprint": "BE432E367AC62157C546DB3F21AE11B89025F930D4AE397ECC5B6A6F2016D154", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-lock", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.setpalette.slot-9.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "SetPalette", + "slot": 9, + "parameter": null + }, + "sourceFingerprint": "D714FBE65EE1E239F04D9046C2270572CC8DE81094FCE549D81FF50242BC6F8F", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setpalette", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmap.00000121a8f24877ba0afd2b6645fb94.setresolution.slot-10.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "SetResolution", + "slot": 10, + "parameter": null + }, + "sourceFingerprint": "394965547E9C14CB338B9AD84677C27CA1D54BF22E4CDBA79A46D26F31C25EB6", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setresolution", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getdatapointer.slot-5.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetDataPointer", + "slot": 5, + "parameter": null + }, + "sourceFingerprint": "FB4F6B8BD302FCA2BB91B231BF957E10D37AC979C39A88992E2526E53349F66C", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getdatapointer", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getpixelformat.slot-6.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetPixelFormat", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "A065B19968592FDA319A1A9DAC7EC1EB51CE63F5D3FFA62C6DD38E92742065E6", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getpixelformat", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getsize.slot-3.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetSize", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "5FBF3161D277C77796793A167F68999C7B678A182FCBB823CD721DC4BAC83F64", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getsize", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmaplock.00000123a8f24877ba0afd2b6645fb94.getstride.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetStride", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "0DC2598054C7BCB1D19940355D5BE568D508B332E269D00956BAF22DC854F799", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getstride", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.copypalette.slot-6.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "CopyPalette", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "CBBEDB597008ED4EA9032EE361F19AC676DA973DA93A1CB8B0B7D67E24CA4A8C", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypalette", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.copypixels.slot-7.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "CopyPixels", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "78BA461831509B5574CB3F8485FE071B875E1AA1FF4ABC4EBB4ADE74A1AE0A9A", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypixels", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getpixelformat.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetPixelFormat", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "D45F675B2B76A3A9BE908AFBAC03BF4CEC2BD5D8162C1BF28F01FA558B2B6F98", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getpixelformat", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getresolution.slot-5.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetResolution", + "slot": 5, + "parameter": null + }, + "sourceFingerprint": "3545A1714671B8C7223BF21693848300001272CDD14E1BE6C188680EA5BD75DD", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getresolution", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-graphics-imaging.iwicbitmapsource.00000120a8f24877ba0afd2b6645fb94.getsize.slot-3.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetSize", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "F0CBF53A188710273FE737C1A06CDA40FA799C4326F3CA9BF68988E5072B5DA2", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getsize", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudiocaptureclient.c8adbd64e71e48a0a4de185c395cd317.getbuffer.slot-3.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "GetBuffer", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "DDD954B2807361F2D50D38C8054846A02577E820B6D42E0B82130F785AA3E370", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudiocaptureclient.c8adbd64e71e48a0a4de185c395cd317.getnextpacketsize.slot-5.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "GetNextPacketSize", + "slot": 5, + "parameter": null + }, + "sourceFingerprint": "C540B744DB900C7D5EDAD03422FC17E7034A822832F4A39DC2DD8519B0978209", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getnextpacketsize", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudiocaptureclient.c8adbd64e71e48a0a4de185c395cd317.releasebuffer.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "ReleaseBuffer", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "82D3C575E5031A345E01026F01E600C8887B081DF6F79CA514B49B78F01E5E17", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-releasebuffer", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getbuffersize.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetBufferSize", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "9F0C09DD69B785A9B4A339ECD2A1970E8574BDBA0F173E3ACF630407A9AB14BE", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getbuffersize", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudiorenderclient.f294acfc31464483a7bfaddca7c260e2.getbuffer.slot-3.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioRenderClient", + "iid": "f294acfc-3146-4483-a7bf-addca7c260e2", + "method": "GetBuffer", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "E99E87341B5820E896608A563B67ABCF2A0F9BD833202788950D9FAE8F69E2DB", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-getbuffer", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-audio.iaudiorenderclient.f294acfc31464483a7bfaddca7c260e2.releasebuffer.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioRenderClient", + "iid": "f294acfc-3146-4483-a7bf-addca7c260e2", + "method": "ReleaseBuffer", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "C79B7868B7940E7D879DC90CA1BAC56E386DA7C8E0F7790DFAB7FB8971E0D767", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-releasebuffer", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-mediafoundation.imfmediabuffer.045fa593879942b8bc8d8968c6453507.getcurrentlength.slot-5.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "GetCurrentLength", + "slot": 5, + "parameter": null + }, + "sourceFingerprint": "AABA562CD26F16571A75D54894E001700500994E98949B4E7A7DA1B6CDE61862", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getcurrentlength", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-mediafoundation.imfmediabuffer.045fa593879942b8bc8d8968c6453507.getmaxlength.slot-7.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "GetMaxLength", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "738D4850D037E6B9F76F28C7D0403B4D9BDF97F3B04C9B8E5A0EFBA18A3A962C", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getmaxlength", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-mediafoundation.imfmediabuffer.045fa593879942b8bc8d8968c6453507.lock.slot-3.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "Lock", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "1B9E2C63825F73EE5599F05E9EA180D52FD22F02EDD33BB23028711DDF335172", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-lock", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-mediafoundation.imfmediabuffer.045fa593879942b8bc8d8968c6453507.setcurrentlength.slot-6.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "SetCurrentLength", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "75AB892B1685032D840B1E5FECB9CD9A87F8E1865492D24796996674372864CA", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-setcurrentlength", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, + "buffers.borrowed-copy.entry.windows-win32-media-mediafoundation.imfmediabuffer.045fa593879942b8bc8d8968c6453507.unlock.slot-4.v1": { + "familyId": "buffers.borrowed-copy.v1", + "contractKind": "borrowed-storage", + "selector": { + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "Unlock", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "83FB2903C23EBD4BB98C182C6575135225ABD0C3EA78183CDADFB3B027B8107B", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-unlock", + "registered": true, + "metadataMatched": true, + "safeConsumed": false, + "interfaceDependencies": 0 + }, "buffers.bounded-two-call.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getblob.slot-15.v1": { "familyId": "buffers.bounded-two-call.v1", "contractKind": "bounded-two-call", @@ -10861,7 +11349,7 @@ "interfaceDependencies": 1 } }, - "countSemantics": "registeredExactEntries counts declared selector-specific entries; metadataMatchedExactEntries counts entries matched against pinned metadata; safeConsumedExactEntries counts distinct entries used by safe plans; exactEntryInterfaceDependencies counts every safe entry/interface pair; exactFamilyInterfaceDependencies counts each family once per safe interface. None is a net-contribution or ablation count." + "countSemantics": "registeredExactEntries counts declared selector-specific entries; metadataMatchedExactEntries counts entries matched against pinned metadata; safeConsumedExactEntries counts distinct entries used by complete-interface safe plans; exactEntryInterfaceDependencies counts every complete-safe entry/interface pair; exactFamilyInterfaceDependencies counts each family once per complete-safe interface. Copy-only facade dependencies are registered and metadata-matched but are excluded from complete-interface consumption counts. None is a net-contribution or ablation count." }, "targets": { "arm64": { diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 556a9d5c..7a0d55f1 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -1183,7 +1183,7 @@ Windows.Win32.Graphics.GdiPlus,IImageBytes,025d1823-6c7d-447b-bbdb-a3cbc3dfa2fc, Windows.Win32.Graphics.Imaging.D2D,IWICImageEncoder,04c75bf8-3ce1-473b-acc5-3cc4f5e94999,true,standard_derived, Windows.Win32.Graphics.Imaging.D2D,IWICImagingFactory2,7b816b45-1996-4476-b132-de9e247c8af0,true,standard_derived, Windows.Win32.Graphics.Imaging.D2D,IWICImagingFactory3,489b3d8b-624a-4258-b678-7eece70f299d,true,standard_derived, -Windows.Win32.Graphics.Imaging,IWICBitmap,00000121-a8f2-4877-ba0a-fd2b6645fb94,true,standard_derived, +Windows.Win32.Graphics.Imaging,IWICBitmap,00000121-a8f2-4877-ba0a-fd2b6645fb94,true,exact_registry_dependent, Windows.Win32.Graphics.Imaging,IWICBitmapClipper,e4fbcf03-223d-4e81-9333-d635556dd1b5,true,standard_derived, Windows.Win32.Graphics.Imaging,IWICBitmapCodecInfo,e87a44c4-b76e-4c47-8b09-298eb12a2714,false,,safe_projection_incomplete Windows.Win32.Graphics.Imaging,IWICBitmapCodecProgressNotification,64c1024e-c3cf-4462-8078-88c2b11c46d9,false,,external_pointee_storage diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 502e13c2..0bb45559 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -14,8 +14,6 @@ use crate::com_metadata::{ RawParamDirection, RawSafeArrayOwnership, RawStringEncoding, }; -use super::generate_com_interface_files; - pub const OFFICIAL_METADATA_VERSION: &str = "71.0.14-preview"; pub const OFFICIAL_METADATA_SHA256: &str = "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; @@ -643,7 +641,7 @@ fn build_report( registered_entry_records.extend(crate::com_metadata::collect_exact_registry_entries( interface, )); - let safe_result = generate_com_interface_files(interface, winmd); + let safe_result = super::generate_complete_com_interface_files(interface, winmd); let safe_complete = safe_result.is_ok(); let safe_error = safe_result .err() @@ -2852,7 +2850,7 @@ fn summarize( by_metadata_attribute, by_standard_rule_id, exact_entry_status, - count_semantics: "registeredExactEntries counts declared selector-specific entries; metadataMatchedExactEntries counts entries matched against pinned metadata; safeConsumedExactEntries counts distinct entries used by safe plans; exactEntryInterfaceDependencies counts every safe entry/interface pair; exactFamilyInterfaceDependencies counts each family once per safe interface. None is a net-contribution or ablation count.".into(), + count_semantics: "registeredExactEntries counts declared selector-specific entries; metadataMatchedExactEntries counts entries matched against pinned metadata; safeConsumedExactEntries counts distinct entries used by complete-interface safe plans; exactEntryInterfaceDependencies counts every complete-safe entry/interface pair; exactFamilyInterfaceDependencies counts each family once per complete-safe interface. Copy-only facade dependencies are registered and metadata-matched but are excluded from complete-interface consumption counts. None is a net-contribution or ablation count.".into(), }; CapabilitySummary { @@ -2862,7 +2860,7 @@ fn summarize( definitions: BTreeMap::from([ ( "safe_complete".into(), - "Existing complete safe generator succeeds for the full inherited interface.".into(), + "Complete safe generation succeeds for the full inherited interface; bounded copy-only facades are excluded.".into(), ), ( "standard_derived".into(), @@ -4562,8 +4560,8 @@ mod tests { assert_eq!(report.summary.safe_complete, 5_697); assert_eq!(report.summary.safe_incomplete, 2_232); assert_eq!(report.summary.safe_evidence.safe_complete, 5_697); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_333); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 364); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_332); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 365); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4577,36 +4575,38 @@ mod tests { report.summary.safe_evidence.com_standard_fact_occurrences, 26_134 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 506); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 532); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 506 + 532 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 415 + 431 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 671 + 693 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 417 + 424 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, BTreeMap::from([ ("borrowed-handle".into(), 54), + ("borrowed-storage".into(), 15), ("bounded-two-call".into(), 16), ("compound-dispatch".into(), 1), ("conditional-output".into(), 10), + ("contextual-effect".into(), 7), ("counted-buffer".into(), 16), ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), @@ -4641,7 +4641,7 @@ mod tests { report.summary.safe_evidence.by_family_id["automation.idispatch-invoke.v1"], 1 ); - assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 415); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 431); assert!( report .summary @@ -4686,7 +4686,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 415 + 431 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 30e5f8f1..1ca28a85 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -17,7 +17,7 @@ use super::capability::{ }; use super::javascript::naming::camel_case; -pub const UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 11; +pub const UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 12; #[derive(Debug, Clone)] pub struct UnsafeGeneratedOutput { @@ -68,7 +68,7 @@ pub fn measure_stage2_coverage(winmd_paths: &str) -> Result, pub(super) sink: Option, + pub(super) borrowed_storage: Option, pub(super) evidence_dependencies: crate::contract_registry::EvidenceDependencies, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ProjectedBorrowedStorage { + pub copy: Option, + pub context_effects: std::collections::BTreeMap, + pub copy_only: bool, + pub evidence_dependencies: crate::contract_registry::EvidenceDependencies, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ProjectedBorrowedCopy { + pub descriptor: String, + pub operations: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ProjectedBorrowedOperation { + pub name: &'static str, + pub runtime_method: &'static str, + pub arguments: CopyArguments, + pub result: CopyResult, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum CopyArguments { + None, + Bytes, + Frames, + Rectangle, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum CopyResult { + Void, + Bytes, + Packet, + Bitmap, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ProjectedComCoclass { pub(super) name: String, diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index 8dd4fde7..82cad9c5 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -252,6 +252,13 @@ fn com_esm_to_cjs(esm: &str, namespace: &str) -> String { fn render_js(meta: &ProjectedComInterface) -> String { let mut out = String::new(); out.push_str("// Generated by dynwinrt-codegen — do not edit\n"); + if meta + .borrowed_storage + .as_ref() + .is_some_and(|storage| storage.copy_only) + { + out.push_str("// Bounded owned-copy facade; not a complete native interface projection.\n"); + } let runtime_imports = if matches!(meta.activation, ActivationPlan::WinRtFactory { .. }) { "DynCom, DynComMethodSig, DynWinRtValue, WinGuid" } else { @@ -261,6 +268,18 @@ fn render_js(meta: &ProjectedComInterface) -> String { "import {{ {runtime_imports}, __registerComProjection, __comProjectionIid, projectAs }} from '{}';\n", com_runtime_import_name_for_module(&meta.namespace) )); + if let Some(copy) = meta + .borrowed_storage + .as_ref() + .and_then(|storage| storage.copy.as_ref()) + { + let descriptor = + serde_json::to_string(©.descriptor).expect("validated copy descriptor"); + out.push_str(&format!( + "import {{ DynComBorrowedCopyPlan }} from '{}';\nlet _borrowedCopyPlan;\nconst _getBorrowedCopyPlan = () => _borrowedCopyPlan ??= DynComBorrowedCopyPlan.prepare({descriptor});\n", + com_runtime_import_name_for_module(&meta.namespace) + )); + } for en in &meta.referenced_enums { let import = relative_module_specifier(&meta.namespace, &meta.name, &en.namespace, &en.name); @@ -362,11 +381,20 @@ fn render_js(meta: &ProjectedComInterface) -> String { .methods .iter() .map(|method| { + let mut signature = build_method_sig_js(method); + if let Some(effect) = meta + .borrowed_storage + .as_ref() + .and_then(|storage| storage.context_effects.get(&method.vtable_index)) + { + signature.push_str(&format!( + ".withContextEffect({})", + serde_json::to_string(effect).expect("validated context descriptor") + )); + } format!( " .addMethodAt({}, '{}', {})\n", - method.vtable_index, - method.name, - build_method_sig_js(method) + method.vtable_index, method.name, signature ) }) .collect::(); @@ -414,6 +442,22 @@ fn render_js(meta: &ProjectedComInterface) -> String { render_sink_implementation_js(&mut out, meta, &wrap_owned, &get_iface_var); } out.push_str(" /** Release the underlying native COM reference. Safe to call more than once. */\n release() {\n this._obj.release();\n }\n"); + if let Some(copy) = meta + .borrowed_storage + .as_ref() + .and_then(|storage| storage.copy.as_ref()) + { + use super::super::ir::CopyArguments; + for operation in ©.operations { + let (parameters, arguments) = match operation.arguments { + CopyArguments::None => ("", ""), + CopyArguments::Bytes => ("data", ", data"), + CopyArguments::Frames => ("frames", ", frames"), + CopyArguments::Rectangle => ("rect", ", [rect.x, rect.y, rect.width, rect.height]"), + }; + out.push_str(&format!(" {}({parameters}) {{\n return _getBorrowedCopyPlan().{}(this._obj{arguments});\n }}\n", operation.name, operation.runtime_method)); + } + } match &meta.activation { ActivationPlan::None => {} ActivationPlan::Coclass { .. } => {} @@ -2308,6 +2352,19 @@ fn unwrap_dynamic_iid_result_js( fn render_dts(meta: &ProjectedComInterface) -> String { let mut out = String::new(); out.push_str("// Generated by dynwinrt-codegen — do not edit\n"); + if meta + .borrowed_storage + .as_ref() + .is_some_and(|storage| storage.copy.is_some()) + { + out.push_str("import type { Buffer } from 'node:buffer';\n"); + if meta.borrowed_storage.as_ref().unwrap().copy_only { + out.push_str( + "/** Bounded owned-copy projection, not a complete native interface surface. */\n", + ); + } + out.push_str("/** Copy operations never expose native-backed views or caller-asserted lifetime. */\n"); + } let public_types = if meta.sink.is_some() { "DynComImplementation, WinGuid" } else { @@ -2492,6 +2549,32 @@ fn render_dts(meta: &ProjectedComInterface) -> String { )); } out.push_str(" /** Release the underlying native COM reference. Safe to call more than once. */\n release(): void;\n"); + if let Some(copy) = meta + .borrowed_storage + .as_ref() + .and_then(|storage| storage.copy.as_ref()) + { + use super::super::ir::{CopyArguments, CopyResult}; + for operation in ©.operations { + let parameters = match operation.arguments { + CopyArguments::None => "", + CopyArguments::Bytes => "data: Buffer | Uint8Array", + CopyArguments::Frames => "frames: number", + CopyArguments::Rectangle => { + "rect: { readonly x: number; readonly y: number; readonly width: number; readonly height: number }" + } + }; + let result = match operation.result { + CopyResult::Void => "void", + CopyResult::Bytes => "Buffer", + CopyResult::Bitmap => "{ data: Buffer; width: number; height: number }", + CopyResult::Packet => { + "({ kind: 'data' | 'silent'; data?: Buffer; frames: number; flags: number; timestampsValid: boolean; devicePosition?: bigint; qpcPosition?: bigint }) | null" + } + }; + out.push_str(&format!(" /** Synchronous owned-copy transaction; finalization failure throws and poisons this context. */\n {}({parameters}): {result};\n", operation.name)); + } + } let mut emitted_groups = std::collections::HashSet::new(); for method in &meta.methods { if let Some(overload) = &method.overload { diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index fd0c0031..39c87a33 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -37,6 +37,7 @@ fn renderer_api_accepts_only_projected_ir() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("registerIUnknownInterface")); @@ -157,6 +158,7 @@ fn renderer_serializes_validated_com_sink_plan() { ], }), evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -413,6 +415,7 @@ fn renderer_serializes_direct_and_void_com_sink_returns() { ], }), evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -517,6 +520,7 @@ fn renderer_projects_borrowed_hwnd_output_as_numeric_handle() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -586,6 +590,7 @@ fn canonical_iunknown_arrays_use_managed_values_without_nominal_wrappers() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); assert!( @@ -632,6 +637,7 @@ fn renderer_projects_bstr_replacement_as_a_string_roundtrip() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -680,6 +686,7 @@ fn renderer_allows_null_only_for_nullable_bstr_inputs() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -800,6 +807,7 @@ fn renderer_keeps_dynamic_iid_native_order_and_all_results() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }) .unwrap(); @@ -856,6 +864,7 @@ fn renderer_emits_distinct_by_value_variant_inputs() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -911,6 +920,7 @@ fn typed_buffer_scalar_aliases_are_collected_for_declarations() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; assert_eq!( @@ -996,6 +1006,7 @@ fn renderer_serializes_fixed_capacity_bytes_from_projected_ir() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -1102,6 +1113,7 @@ fn parallel_arrays_use_semantic_element_counts_and_guid_conversion() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -1231,6 +1243,7 @@ fn renderer_emits_tagged_unions_and_automation_runtime_transfers() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let output = render_com_interface(&projected).unwrap(); @@ -1312,6 +1325,7 @@ fn renderer_emits_explicit_idispatch_invoke_options_and_compound_types() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }) .unwrap(); @@ -1364,6 +1378,7 @@ fn coclass_renderer_uses_new_and_runtime_query_interface_views() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let coclass = ProjectedComCoclass { name: "Test".into(), @@ -1417,6 +1432,7 @@ fn coclass_renderer_rejects_exact_canonical_interface_path_collisions() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let first = interface("Tests.FooBar", "00000000-0000-0000-0000-000000000001"); let second = interface("Tests.Foo-Bar", "00000000-0000-0000-0000-000000000002"); @@ -1451,6 +1467,7 @@ fn renderer_returns_invalid_referenced_identity_errors() { }], sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let error = render_com_interface(&projected).unwrap_err(); diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index 484ed31a..84045cbf 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -154,6 +154,7 @@ pub fn generate_com_interface_files( if !generated.insert((namespace.clone(), name.clone())) { continue; } + let referenced = crate::com_metadata::parse_com_interface(winmd_paths, &namespace, &name) .ok_or_else(|| { format!("owning array element interface {namespace}.{name} could not be resolved") @@ -180,6 +181,20 @@ pub fn generate_com_interface_files( Ok(output) } +/// Bounded copy facades must never be counted as complete native interfaces. +pub fn generate_complete_com_interface_files( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result { + let output = generate_com_interface_files(meta, winmd_paths)?; + if crate::com_metadata::borrowed::is_copy_only(meta) { + return Err( + "Bounded owned-copy projection only; full native interface remains unsupported".into(), + ); + } + Ok(output) +} + fn enumerator_interface_refs( projected: &ir::ProjectedComInterface, ) -> std::collections::BTreeSet<(String, String)> { diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs b/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs new file mode 100644 index 00000000..7ead9f77 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::com_metadata::{ComInterfaceMeta, borrowed as evidence}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum CopyFamily { + AudioRender, + AudioCapture, + BitmapBgra8, + MediaBuffer, +} + +#[derive(serde::Serialize)] +pub(in crate::codegen::com) struct NativeCall { + iid: &'static str, + slot: usize, + storage: Vec<&'static str>, +} + +#[derive(serde::Serialize)] +pub(in crate::codegen::com) struct BorrowedCopyPlan { + version: u32, + metadata_sha256: &'static str, + access: &'static str, + exposure: &'static str, + owner: &'static str, + acquired_hresult: i32, + empty_hresult: Option, + kind: &'static str, + receiver: &'static str, + acquire: NativeCall, + queries: Vec, + finalize: Option, + extent: &'static str, + finalization: &'static str, + sta_only: bool, + audio_origin_required: bool, +} + +pub(in crate::codegen::com) struct ValidatedStorage { + pub copy: Option<(CopyFamily, BorrowedCopyPlan)>, + pub effects: Vec<(usize, &'static evidence::Evidence)>, + pub dependencies: crate::contract_registry::EvidenceDependencies, +} + +pub(in crate::codegen::com) fn validate( + meta: &ComInterfaceMeta, + paths: &str, +) -> Result, String> { + if !evidence::is_audio_context(meta) && !evidence::is_bounded_copy(meta) { + return Ok(None); + } + evidence::require_metadata_hash(paths)?; + evidence::validate_interface(meta)?; + let mut dependencies = crate::com_metadata::collect_evidence_dependencies(meta); + if evidence::is_audio_context(meta) { + let effects = meta + .raw_methods + .as_ref() + .expect("validated raw evidence") + .iter() + .filter_map(|raw| evidence::evidence_for(raw).transpose()) + .collect::, _>>()? + .into_iter() + .filter(|entry| entry.effect.is_some()) + .map(|entry| (entry.slot, entry)) + .collect(); + return Ok(Some(ValidatedStorage { + copy: None, + effects, + dependencies, + })); + } + let family = match ( + meta.interface.namespace.as_str(), + meta.interface.name.as_str(), + ) { + (evidence::AUDIO, "IAudioRenderClient") => CopyFamily::AudioRender, + (evidence::AUDIO, "IAudioCaptureClient") => CopyFamily::AudioCapture, + (evidence::WIC, "IWICBitmap") => CopyFamily::BitmapBgra8, + (evidence::MF, "IMFMediaBuffer") => CopyFamily::MediaBuffer, + _ => return Err("Unknown borrowed-storage family".into()), + }; + let dependency = if family == CopyFamily::BitmapBgra8 { + Some((evidence::WIC, "IWICBitmapLock")) + } else if matches!(family, CopyFamily::AudioRender | CopyFamily::AudioCapture) { + Some((evidence::AUDIO, "IAudioClient")) + } else { + None + }; + if let Some((namespace, name)) = dependency { + let dependency = crate::com_metadata::parse_com_interface(paths, namespace, name) + .ok_or_else(|| format!("Borrowed-copy dependency {namespace}.{name} is absent"))?; + evidence::validate_interface(&dependency)?; + for entry in evidence::catalog_entries(&dependency) { + dependencies.add_exact(entry.entry_id, entry.family_id, entry.contract_kind); + } + } + let call = |iid, slot, storage: &[&'static str]| NativeCall { + iid, + slot, + storage: storage.to_vec(), + }; + let (kind, receiver, acquire, queries, finalize, extent, finalization) = match family { + CopyFamily::AudioRender => ( + "audio-render", + evidence::RENDER_IID, + call(evidence::RENDER_IID, 3, &["in-u32", "borrowed-bytes"]), + vec![call(evidence::CLIENT_IID, 4, &["out-u32"])], + Some(call(evidence::RENDER_IID, 4, &["in-u32", "in-u32"])), + "initialized-frames", + "render-full-or-zero", + ), + CopyFamily::AudioCapture => ( + "audio-capture", + evidence::CAPTURE_IID, + call( + evidence::CAPTURE_IID, + 3, + &["borrowed-bytes", "out-u32", "out-u32", "out-u64", "out-u64"], + ), + vec![call(evidence::CLIENT_IID, 4, &["out-u32"])], + Some(call(evidence::CAPTURE_IID, 4, &["in-u32"])), + "capture-packet-frames", + "capture-full-or-zero", + ), + CopyFamily::BitmapBgra8 => ( + "bitmap-bgra8", + evidence::BITMAP_IID, + call( + evidence::BITMAP_IID, + 8, + &["in-rect", "in-u32", "owned-interface"], + ), + vec![ + call(evidence::BITMAP_IID, 3, &["out-u32", "out-u32"]), + call(evidence::LOCK_IID, 3, &["out-u32", "out-u32"]), + call(evidence::LOCK_IID, 4, &["out-u32"]), + call(evidence::LOCK_IID, 6, &["out-guid"]), + call(evidence::LOCK_IID, 5, &["out-u32", "borrowed-bytes"]), + ], + None, + "native-bgra8-rows", + "release-lock-reference", + ), + CopyFamily::MediaBuffer => ( + "media-buffer", + evidence::MF_IID, + call( + evidence::MF_IID, + 3, + &["borrowed-bytes", "out-u32", "out-u32"], + ), + vec![call(evidence::MF_IID, 6, &["in-u32"])], + Some(call(evidence::MF_IID, 4, &[])), + "native-current-and-max", + "unlock", + ), + }; + Ok(Some(ValidatedStorage { + effects: vec![], + dependencies, + copy: Some(( + family, + BorrowedCopyPlan { + version: 1, + metadata_sha256: evidence::METADATA_SHA256, + exposure: "owned-copy-only", + access: match family { + CopyFamily::AudioRender => "write", + CopyFamily::AudioCapture | CopyFamily::BitmapBgra8 => "read", + CopyFamily::MediaBuffer => "read-write", + }, + owner: match family { + CopyFamily::AudioRender | CopyFamily::AudioCapture => "audio-service-origin", + CopyFamily::BitmapBgra8 => "acquired-interface", + CopyFamily::MediaBuffer => "receiver", + }, + acquired_hresult: 0, + empty_hresult: (family == CopyFamily::AudioCapture).then_some(0x08890001), + kind, + receiver, + acquire, + queries, + finalize, + extent, + finalization, + sta_only: family == CopyFamily::BitmapBgra8, + audio_origin_required: matches!( + family, + CopyFamily::AudioRender | CopyFamily::AudioCapture + ), + }, + )), + })) +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs index 488f00ba..eff0e222 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs @@ -12,6 +12,7 @@ #![allow(dead_code)] pub(super) mod abi; +pub(super) mod borrowed; pub(super) mod contract; pub(super) mod diagnostics; pub(super) mod ids; diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs b/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs new file mode 100644 index 00000000..198955ad --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::super::{ + ir::{ + CopyArguments, CopyResult, ProjectedBorrowedCopy, ProjectedBorrowedOperation, + ProjectedBorrowedStorage, + }, + model::borrowed::{CopyFamily, ValidatedStorage}, +}; + +pub(super) fn project(storage: ValidatedStorage) -> Result { + let copy_only = storage + .copy + .as_ref() + .is_some_and(|(family, _)| *family != CopyFamily::BitmapBgra8); + let context_effects = storage + .effects + .into_iter() + .map(|(slot, evidence)| { + Ok(( + slot, + serde_json::to_string(&serde_json::json!({ + "version": 1, + "effect": evidence.effect, + "metadata_sha256": crate::com_metadata::borrowed::METADATA_SHA256, + "fingerprint": evidence.fingerprint, + })) + .map_err(|error| error.to_string())?, + )) + }) + .collect::>()?; + let copy = storage + .copy + .map(|(family, plan)| { + let op = |name, arguments, result| ProjectedBorrowedOperation { + name, + runtime_method: name, + arguments, + result, + }; + let operations = match family { + CopyFamily::AudioRender => vec![ + op("writeFramesCopy", CopyArguments::Bytes, CopyResult::Void), + op("writeSilence", CopyArguments::Frames, CopyResult::Void), + ], + CopyFamily::AudioCapture => vec![op( + "readPacketCopy", + CopyArguments::None, + CopyResult::Packet, + )], + CopyFamily::BitmapBgra8 => vec![op( + "readLockedBgra8Copy", + CopyArguments::Rectangle, + CopyResult::Bitmap, + )], + CopyFamily::MediaBuffer => vec![ + op("readCopy", CopyArguments::None, CopyResult::Bytes), + op("replaceCopy", CopyArguments::Bytes, CopyResult::Void), + ], + }; + Ok::<_, String>(ProjectedBorrowedCopy { + descriptor: serde_json::to_string(&plan).map_err(|error| error.to_string())?, + operations, + }) + }) + .transpose()?; + Ok(ProjectedBorrowedStorage { + copy, + context_effects, + copy_only, + evidence_dependencies: storage.dependencies, + }) +} + +#[cfg(test)] +mod tests { + use crate::codegen::com::{ + generate_com_interface_files, generate_complete_com_interface_files, + }; + use crate::com_metadata::{borrowed as evidence, parse_com_interface}; + + #[test] + fn borrowed_copy_projection_is_bounded_and_renderer_is_ir_driven() { + let Ok(paths) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + for (namespace, name, public_methods) in [ + ( + evidence::AUDIO, + "IAudioRenderClient", + vec!["writeFramesCopy", "writeSilence"], + ), + ( + evidence::AUDIO, + "IAudioCaptureClient", + vec!["readPacketCopy"], + ), + (evidence::WIC, "IWICBitmap", vec!["readLockedBgra8Copy"]), + ( + evidence::MF, + "IMFMediaBuffer", + vec!["readCopy", "replaceCopy"], + ), + ] { + let metadata = parse_com_interface(&paths, namespace, name).unwrap(); + let output = generate_com_interface_files(&metadata, &paths).unwrap(); + for method in public_methods { + assert!(output.js.contains(&format!(" {method}("))); + assert!(output.dts.contains(&format!(" {method}("))); + } + if evidence::is_copy_only(&metadata) { + assert!( + !output.js.contains(".addMethodAt("), + "copy-only wrapper must not publish unsafe native methods" + ); + assert!(!output.dts.contains("lock(") && !output.dts.contains("getBuffer(")); + assert!(generate_complete_com_interface_files(&metadata, &paths).is_err()); + } else { + assert!( + output.dts.contains("lock("), + "preserve IWICBitmap's existing safe owned-lock acquisition" + ); + assert!(generate_complete_com_interface_files(&metadata, &paths).is_ok()); + } + let mut projected = super::super::project_com_interface(&metadata, &paths).unwrap(); + let copy = projected + .borrowed_storage + .as_mut() + .unwrap() + .copy + .as_mut() + .unwrap(); + copy.operations[0].name = "renamedTransaction"; + let rendered = + crate::codegen::com::javascript::render::render_com_interface(&projected).unwrap(); + assert!(rendered.js.contains(" renamedTransaction(")); + assert!(rendered.dts.contains(" renamedTransaction(")); + assert!(!rendered.js.contains("asPointerBigint")); + } + for name in ["IAudioClient", "IAudioClient2", "IAudioClient3"] { + let metadata = parse_com_interface(&paths, evidence::AUDIO, name).unwrap(); + let projected = super::super::project_com_interface(&metadata, &paths).unwrap(); + assert!(projected.borrowed_storage.as_ref().unwrap().copy.is_none()); + assert_eq!( + projected + .borrowed_storage + .as_ref() + .unwrap() + .context_effects + .len(), + if name == "IAudioClient3" { 3 } else { 2 } + ); + let output = generate_complete_com_interface_files(&metadata, &paths).unwrap(); + assert!(output.js.contains(".withContextEffect(")); + assert!( + output.js.contains("audio-initialize") && output.js.contains("audio-get-service") + ); + assert!(output.dts.contains("getMixFormat(")); + } + for name in ["IMF2DBuffer", "IMF2DBuffer2"] { + let metadata = parse_com_interface(&paths, evidence::MF, name).unwrap(); + assert!(generate_com_interface_files(&metadata, &paths).is_err()); + } + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs index 772fdf99..4cc04418 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs @@ -85,6 +85,7 @@ fn project_legacy_interface( referenced_enums, sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; Ok(projected) } diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index fc19175b..aaccc8d9 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod borrowed; mod interop; mod legacy_diagnostics; mod legacy_types; @@ -44,10 +45,36 @@ pub(super) fn project_com_interface( meta: &ComInterfaceMeta, winmd_paths: &str, ) -> Result { + let storage = model::borrowed::validate(meta, winmd_paths)? + .map(borrowed::project) + .transpose()?; + if storage.as_ref().is_some_and(|storage| storage.copy_only) { + let mut projected = project_com_reference_interface(meta)?; + projected.evidence_dependencies = storage.as_ref().unwrap().evidence_dependencies.clone(); + projected.borrowed_storage = storage; + return Ok(projected); + } let validated = model::validate_interface(meta) .map_err(|error| diagnostic_compatibility(meta, winmd_paths, error))?; - project_validated_interface(&validated, winmd_paths) - .map_err(|error| diagnostic_compatibility(meta, winmd_paths, error)) + let mut projected = project_validated_interface(&validated, winmd_paths) + .map_err(|error| diagnostic_compatibility(meta, winmd_paths, error))?; + if storage + .as_ref() + .is_some_and(|storage| !storage.context_effects.is_empty()) + { + projected.sink = None; + } + if let Some(storage) = storage.as_ref() { + for (id, family) in &storage.evidence_dependencies.exact_entry_families { + projected.evidence_dependencies.add_exact( + id.clone(), + *family, + storage.evidence_dependencies.exact_entry_kinds[id], + ); + } + } + projected.borrowed_storage = storage; + Ok(projected) } pub(super) fn project_com_reference_interface( @@ -69,6 +96,7 @@ pub(super) fn project_com_reference_interface( activation: ActivationPlan::None, referenced_enums: Vec::new(), sink: None, + borrowed_storage: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; validate_projected_surface_names(&projected)?; @@ -172,6 +200,7 @@ fn project_validated_interface( activation, referenced_enums, sink, + borrowed_storage: None, evidence_dependencies, }; validate_projected_surface_names(&projected)?; @@ -3755,6 +3784,7 @@ mod tests { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; let error = validate_projected_surface_names(&interface).unwrap_err(); @@ -3900,6 +3930,7 @@ mod tests { ], sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, }; assert!(validate_projected_surface_names(&interface).is_err()); @@ -3935,6 +3966,7 @@ mod tests { #[test] fn coclass_rejects_conflicting_enum_filenames() { let interface = |name: &str, namespace: &str| ProjectedComInterface { + borrowed_storage: None, name: name.into(), namespace: "Tests".into(), iid: "00000000-0000-0000-c000-000000000046".into(), diff --git a/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs b/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs new file mode 100644 index 00000000..9859fc60 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs @@ -0,0 +1,525 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Exact storage/context evidence. These selectors are not general pointer rules. + +use super::{ComInterfaceMeta, RawComMethod, raw_method_fingerprint}; +use crate::contract_registry::{ + ContractKind, ExactEntrySelector, ExactFamilyId, ExactRegistryEntry, +}; +use sha2::{Digest, Sha256}; + +pub const METADATA_SHA256: &str = + "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; +pub const AUDIO: &str = "Windows.Win32.Media.Audio"; +pub const WIC: &str = "Windows.Win32.Graphics.Imaging"; +pub const MF: &str = "Windows.Win32.Media.MediaFoundation"; +pub const CLIENT_IID: &str = "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2"; +pub const CLIENT2_IID: &str = "726778cd-f60a-4eda-82de-e47610cd78aa"; +pub const CLIENT3_IID: &str = "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42"; +pub const RENDER_IID: &str = "f294acfc-3146-4483-a7bf-addca7c260e2"; +pub const CAPTURE_IID: &str = "c8adbd64-e71e-48a0-a4de-185c395cd317"; +pub const BITMAP_IID: &str = "00000121-a8f2-4877-ba0a-fd2b6645fb94"; +pub const LOCK_IID: &str = "00000123-a8f2-4877-ba0a-fd2b6645fb94"; +pub const MF_IID: &str = "045fa593-8799-42b8-bc8d-8968c6453507"; + +#[derive(Debug)] +pub struct Evidence { + pub namespace: &'static str, + pub interface: &'static str, + pub iid: &'static str, + pub method: &'static str, + pub slot: usize, + pub fingerprint: &'static str, + pub effect: Option<&'static str>, + pub citation: &'static str, +} + +macro_rules! storage { + ($ns:expr, $interface:literal, $iid:expr, $method:literal, $slot:literal, $hash:literal, $citation:literal) => { + Evidence { + namespace: $ns, + interface: $interface, + iid: $iid, + method: $method, + slot: $slot, + fingerprint: $hash, + effect: None, + citation: $citation, + } + }; +} + +// Fingerprints include native layouts, directions, optional/Const flags, +// NativeArrayInfo, return convention and all existing exact-contract evidence. +pub const EVIDENCE: &[Evidence] = &[ + Evidence { + namespace: AUDIO, + interface: "IAudioClient", + iid: CLIENT_IID, + method: "Initialize", + slot: 3, + fingerprint: "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", + effect: Some("audio-initialize"), + citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-initialize", + }, + Evidence { + namespace: AUDIO, + interface: "IAudioClient", + iid: CLIENT_IID, + method: "GetService", + slot: 14, + fingerprint: "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", + effect: Some("audio-get-service"), + citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getservice", + }, + Evidence { + namespace: AUDIO, + interface: "IAudioClient3", + iid: CLIENT3_IID, + method: "InitializeSharedAudioStream", + slot: 20, + fingerprint: "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", + effect: Some("audio-initialize-shared"), + citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream", + }, + storage!( + AUDIO, + "IAudioClient", + CLIENT_IID, + "GetBufferSize", + 4, + "9F0C09DD69B785A9B4A339ECD2A1970E8574BDBA0F173E3ACF630407A9AB14BE", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getbuffersize" + ), + storage!( + AUDIO, + "IAudioRenderClient", + RENDER_IID, + "GetBuffer", + 3, + "E99E87341B5820E896608A563B67ABCF2A0F9BD833202788950D9FAE8F69E2DB", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-getbuffer" + ), + storage!( + AUDIO, + "IAudioRenderClient", + RENDER_IID, + "ReleaseBuffer", + 4, + "C79B7868B7940E7D879DC90CA1BAC56E386DA7C8E0F7790DFAB7FB8971E0D767", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-releasebuffer" + ), + storage!( + AUDIO, + "IAudioCaptureClient", + CAPTURE_IID, + "GetBuffer", + 3, + "DDD954B2807361F2D50D38C8054846A02577E820B6D42E0B82130F785AA3E370", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer" + ), + storage!( + AUDIO, + "IAudioCaptureClient", + CAPTURE_IID, + "ReleaseBuffer", + 4, + "82D3C575E5031A345E01026F01E600C8887B081DF6F79CA514B49B78F01E5E17", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-releasebuffer" + ), + storage!( + AUDIO, + "IAudioCaptureClient", + CAPTURE_IID, + "GetNextPacketSize", + 5, + "C540B744DB900C7D5EDAD03422FC17E7034A822832F4A39DC2DD8519B0978209", + "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getnextpacketsize" + ), + storage!( + WIC, + "IWICBitmapSource", + "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "GetSize", + 3, + "F0CBF53A188710273FE737C1A06CDA40FA799C4326F3CA9BF68988E5072B5DA2", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getsize" + ), + storage!( + WIC, + "IWICBitmapSource", + "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "GetPixelFormat", + 4, + "D45F675B2B76A3A9BE908AFBAC03BF4CEC2BD5D8162C1BF28F01FA558B2B6F98", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getpixelformat" + ), + storage!( + WIC, + "IWICBitmapSource", + "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "GetResolution", + 5, + "3545A1714671B8C7223BF21693848300001272CDD14E1BE6C188680EA5BD75DD", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getresolution" + ), + storage!( + WIC, + "IWICBitmapSource", + "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "CopyPalette", + 6, + "CBBEDB597008ED4EA9032EE361F19AC676DA973DA93A1CB8B0B7D67E24CA4A8C", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypalette" + ), + storage!( + WIC, + "IWICBitmapSource", + "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "CopyPixels", + 7, + "78BA461831509B5574CB3F8485FE071B875E1AA1FF4ABC4EBB4ADE74A1AE0A9A", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypixels" + ), + storage!( + WIC, + "IWICBitmap", + BITMAP_IID, + "Lock", + 8, + "BE432E367AC62157C546DB3F21AE11B89025F930D4AE397ECC5B6A6F2016D154", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-lock" + ), + storage!( + WIC, + "IWICBitmap", + BITMAP_IID, + "SetPalette", + 9, + "D714FBE65EE1E239F04D9046C2270572CC8DE81094FCE549D81FF50242BC6F8F", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setpalette" + ), + storage!( + WIC, + "IWICBitmap", + BITMAP_IID, + "SetResolution", + 10, + "394965547E9C14CB338B9AD84677C27CA1D54BF22E4CDBA79A46D26F31C25EB6", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setresolution" + ), + storage!( + WIC, + "IWICBitmapLock", + LOCK_IID, + "GetSize", + 3, + "5FBF3161D277C77796793A167F68999C7B678A182FCBB823CD721DC4BAC83F64", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getsize" + ), + storage!( + WIC, + "IWICBitmapLock", + LOCK_IID, + "GetStride", + 4, + "0DC2598054C7BCB1D19940355D5BE568D508B332E269D00956BAF22DC854F799", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getstride" + ), + storage!( + WIC, + "IWICBitmapLock", + LOCK_IID, + "GetDataPointer", + 5, + "FB4F6B8BD302FCA2BB91B231BF957E10D37AC979C39A88992E2526E53349F66C", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getdatapointer" + ), + storage!( + WIC, + "IWICBitmapLock", + LOCK_IID, + "GetPixelFormat", + 6, + "A065B19968592FDA319A1A9DAC7EC1EB51CE63F5D3FFA62C6DD38E92742065E6", + "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getpixelformat" + ), + storage!( + MF, + "IMFMediaBuffer", + MF_IID, + "Lock", + 3, + "1B9E2C63825F73EE5599F05E9EA180D52FD22F02EDD33BB23028711DDF335172", + "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-lock" + ), + storage!( + MF, + "IMFMediaBuffer", + MF_IID, + "Unlock", + 4, + "83FB2903C23EBD4BB98C182C6575135225ABD0C3EA78183CDADFB3B027B8107B", + "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-unlock" + ), + storage!( + MF, + "IMFMediaBuffer", + MF_IID, + "GetCurrentLength", + 5, + "AABA562CD26F16571A75D54894E001700500994E98949B4E7A7DA1B6CDE61862", + "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getcurrentlength" + ), + storage!( + MF, + "IMFMediaBuffer", + MF_IID, + "SetCurrentLength", + 6, + "75AB892B1685032D840B1E5FECB9CD9A87F8E1865492D24796996674372864CA", + "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-setcurrentlength" + ), + storage!( + MF, + "IMFMediaBuffer", + MF_IID, + "GetMaxLength", + 7, + "738D4850D037E6B9F76F28C7D0403B4D9BDF97F3B04C9B8E5A0EFBA18A3A962C", + "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getmaxlength" + ), +]; + +impl Evidence { + pub(crate) fn entry(&self) -> ExactRegistryEntry { + let family = if self.effect.is_some() { + ExactFamilyId::AudioContext + } else { + ExactFamilyId::BorrowedCopy + }; + let selector = ExactEntrySelector { + namespace: self.namespace.into(), + interface: self.interface.into(), + iid: self.iid.into(), + method: self.method.into(), + slot: self.slot, + parameter: None, + }; + ExactRegistryEntry { + entry_id: selector.entry_id(family), selector, family_id: family, + contract_kind: if self.effect.is_some() { ContractKind::ContextualEffect } else { ContractKind::BorrowedStorage }, + source_fingerprint: self.fingerprint.into(), + reason: if self.effect.is_some() { + "Only the actual successful metadata-described native call may create immutable initialization or service-origin provenance" + } else { + "Bounded owned-copy storage/extent/finalization plan; native borrowed bytes and unsupported methods are not public" + }.into(), + citation: self.citation.into(), + } + } +} + +pub fn evidence_for(raw: &RawComMethod) -> Result, String> { + let selected = EVIDENCE.iter().find(|entry| { + entry.namespace == raw.declaring_namespace + && entry.interface == raw.declaring_interface + && entry.method == raw.metadata_name + }); + if let Some(entry) = selected + && (entry.iid != raw.declaring_iid + || entry.slot != raw.vtable_index + || entry.fingerprint != raw_method_fingerprint(raw)) + { + return Err(format!( + "Borrowed-copy/context evidence drift: {}.{}::{}", + entry.namespace, entry.interface, entry.method + )); + } + Ok(selected) +} + +pub fn is_audio_context(meta: &ComInterfaceMeta) -> bool { + meta.interface.namespace == AUDIO + && matches!( + meta.interface.name.as_str(), + "IAudioClient" | "IAudioClient2" | "IAudioClient3" + ) +} + +pub fn is_bounded_copy(meta: &ComInterfaceMeta) -> bool { + matches!( + ( + meta.interface.namespace.as_str(), + meta.interface.name.as_str() + ), + (AUDIO, "IAudioRenderClient" | "IAudioCaptureClient") + | (WIC, "IWICBitmap") + | (MF, "IMFMediaBuffer") + ) +} + +pub fn is_copy_only(meta: &ComInterfaceMeta) -> bool { + is_bounded_copy(meta) && meta.interface.name != "IWICBitmap" +} + +pub(crate) fn catalog_entries(meta: &ComInterfaceMeta) -> Vec { + if !is_audio_context(meta) + && !is_bounded_copy(meta) + && !(meta.interface.namespace == WIC && meta.interface.name == "IWICBitmapLock") + { + return vec![]; + } + meta.raw_methods + .as_deref() + .unwrap_or_default() + .iter() + .filter_map(|raw| evidence_for(raw).ok().flatten()) + .map(Evidence::entry) + .collect() +} + +pub fn require_metadata_hash(paths: &str) -> Result<(), String> { + // Hash only relevant projections, not every interface in a census. Unknown + // metadata versions need reviewed selectors, never a name-based fallback. + let matching = paths + .split(';') + .filter(|path| !path.trim().is_empty()) + .any(|path| { + std::fs::read(path) + .ok() + .is_some_and(|bytes| format!("{:X}", Sha256::digest(bytes)) == METADATA_SHA256) + }); + if matching { + Ok(()) + } else { + Err("Borrowed-copy plans require the pinned Win32Metadata 71.0.14-preview SHA256".into()) + } +} + +pub fn validate_interface(meta: &ComInterfaceMeta) -> Result<(), String> { + let (iid, bases, base_iids, own_start, last) = match ( + meta.interface.namespace.as_str(), + meta.interface.name.as_str(), + ) { + (AUDIO, "IAudioClient") => (CLIENT_IID, vec!["IUnknown"], vec![], 3, 14), + (AUDIO, "IAudioClient2") => ( + CLIENT2_IID, + vec!["IAudioClient", "IUnknown"], + vec![CLIENT_IID], + 15, + 17, + ), + (AUDIO, "IAudioClient3") => ( + CLIENT3_IID, + vec!["IAudioClient2", "IAudioClient", "IUnknown"], + vec![CLIENT2_IID, CLIENT_IID], + 18, + 20, + ), + (AUDIO, "IAudioRenderClient") => (RENDER_IID, vec!["IUnknown"], vec![], 3, 4), + (AUDIO, "IAudioCaptureClient") => (CAPTURE_IID, vec!["IUnknown"], vec![], 3, 5), + (WIC, "IWICBitmap") => ( + BITMAP_IID, + vec!["IWICBitmapSource", "IUnknown"], + vec!["00000120-a8f2-4877-ba0a-fd2b6645fb94"], + 8, + 10, + ), + (WIC, "IWICBitmapLock") => (LOCK_IID, vec!["IUnknown"], vec![], 3, 6), + (MF, "IMFMediaBuffer") => (MF_IID, vec!["IUnknown"], vec![], 3, 7), + _ => return Err("Not an exact borrowed-copy/context interface".into()), + }; + let methods = meta + .raw_methods + .as_deref() + .ok_or("Borrowed-copy/context raw evidence is absent")?; + if meta.interface.iid != iid + || !meta.is_iunknown_rooted + || meta.base_offset != 3 + || meta.own_methods_start != own_start + || meta.base_chain != bases + || meta.base_iids != base_iids + || meta.interface.generic_piid.is_some() + || !meta.interface.generic_args.is_empty() + || methods.len() != last - 2 + || meta.interface.methods.len() != methods.len() + || methods + .iter() + .enumerate() + .any(|(index, raw)| raw.vtable_index != index + 3) + { + return Err(format!( + "Borrowed-copy/context identity or complete vtable drift: {}", + meta.interface.name + )); + } + for raw in methods { + let entry = evidence_for(raw)?; + if !is_audio_context(meta) && entry.is_none() { + return Err(format!( + "Absent borrowed-storage evidence at slot {}", + raw.vtable_index + )); + } + } + if is_audio_context(meta) { + for slot in [3, 4, 14].into_iter().chain((last == 20).then_some(20)) { + let raw = &methods[slot - 3]; + if evidence_for(raw)?.is_none() { + return Err(format!("Absent audio context evidence at slot {slot}")); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn borrowed_copy_metadata_evidence_and_fail_closed_drift() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + require_metadata_hash(&winmd).unwrap(); + for (namespace, name) in [ + (AUDIO, "IAudioClient3"), + (AUDIO, "IAudioRenderClient"), + (AUDIO, "IAudioCaptureClient"), + (WIC, "IWICBitmap"), + (WIC, "IWICBitmapLock"), + (MF, "IMFMediaBuffer"), + ] { + let meta = super::super::parse_com_interface(&winmd, namespace, name).unwrap(); + validate_interface(&meta).unwrap(); + let mut drift = meta.clone(); + drift.raw_methods = None; + assert!(validate_interface(&drift).is_err()); + let mut drift = meta.clone(); + drift.interface.iid = CLIENT_IID.into(); + assert!(validate_interface(&drift).is_err()); + for index in 0..meta.raw_methods.as_ref().unwrap().len() { + if evidence_for(&meta.raw_methods.as_ref().unwrap()[index]) + .unwrap() + .is_none() + { + continue; + } + let mut drift = meta.clone(); + drift.raw_methods.as_mut().unwrap()[index] + .params + .iter_mut() + .for_each(|param| param.optional = !param.optional); + if !drift.raw_methods.as_ref().unwrap()[index].params.is_empty() { + assert!(validate_interface(&drift).is_err(), "{name} slot {index}"); + } + let mut drift = meta.clone(); + drift.raw_methods.as_mut().unwrap()[index].vtable_index += 1; + assert!(validate_interface(&drift).is_err()); + } + } + assert!(require_metadata_hash("").is_err()); + } +} diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 1436346f..5cfe34d7 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -11,6 +11,8 @@ pub use crate::contract_registry::ContractKind as RawContractKind; pub use crate::contract_registry::ExactFamilyId as RawExactFamilyId; use crate::types::TypeMeta; +#[path = "com_borrowed_metadata.rs"] +pub mod borrowed; #[path = "com_completion_metadata.rs"] pub mod completion; @@ -1189,6 +1191,9 @@ pub(crate) fn collect_evidence_dependencies( use crate::contract_registry::{ComStandardRule, EvidenceDependencies}; let mut dependencies = EvidenceDependencies::default(); + for entry in borrowed::catalog_entries(interface) { + dependencies.add_exact(entry.entry_id, entry.family_id, entry.contract_kind); + } dependencies.add_standard(ComStandardRule::IUnknownIdentityRefcount); dependencies.add_standard(ComStandardRule::QueryInterfaceOutputPlusOne); if interface.coclass_clsid.is_some() { @@ -1297,7 +1302,7 @@ pub(crate) fn collect_exact_registry_entries( ) -> Vec { use crate::contract_registry::{ExactEntrySelector, ExactRegistryEntry}; - let mut entries = Vec::new(); + let mut entries = borrowed::catalog_entries(interface); for method in interface.raw_methods.as_deref().unwrap_or_default() { let method_fingerprint = method .exact_interface_output_call diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index 3d7a7f57..a6fe921c 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -38,6 +38,8 @@ pub enum ContractKind { NullInput, ParameterDirection, FlagSelectedBuffer, + BorrowedStorage, + ContextualEffect, } impl ContractKind { @@ -56,6 +58,8 @@ impl ContractKind { Self::NullInput => "null-input", Self::ParameterDirection => "parameter-direction", Self::FlagSelectedBuffer => "flag-selected-buffer", + Self::BorrowedStorage => "borrowed-storage", + Self::ContextualEffect => "contextual-effect", } } } @@ -96,6 +100,8 @@ pub enum ExactFamilyId { ParameterDirection, ShellCommandString, AudioConditionalOutput, + BorrowedCopy, + AudioContext, } impl ExactFamilyId { @@ -117,6 +123,8 @@ impl ExactFamilyId { Self::ParameterDirection => "com.parameter-direction.v1", Self::ShellCommandString => "shell.flag-selected-string.v1", Self::AudioConditionalOutput => "audio.conditional-output.v1", + Self::BorrowedCopy => "buffers.borrowed-copy.v1", + Self::AudioContext => "audio.context-effect.v1", } } @@ -138,6 +146,8 @@ impl ExactFamilyId { Self::ParameterDirection, Self::ShellCommandString, Self::AudioConditionalOutput, + Self::BorrowedCopy, + Self::AudioContext, ] .into_iter() .find(|family| family.id() == value) @@ -430,6 +440,11 @@ pub(crate) fn validate_exact_entry_catalog( pub(crate) fn statically_declared_exact_entry_ids() -> Result, String> { let mut ids = BTreeSet::new(); + ids.extend( + crate::com_metadata::borrowed::EVIDENCE + .iter() + .map(|entry| entry.entry().entry_id), + ); ids.extend( crate::com_safe_array_registry::all_safe_array_evidence() .iter() @@ -1155,7 +1170,7 @@ mod tests { serde_json::from_str::(SCHEMA_JSON).unwrap(); let registry = load_registry().unwrap(); let ids = statically_declared_exact_entry_ids().unwrap(); - assert_eq!(ids.len(), 506); + assert_eq!(ids.len(), 532); assert_eq!(registry.conditional_outputs.len(), 7); assert_eq!(registry.ownership_outputs.len(), 149); assert_eq!( diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 06277287..063c17b1 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -176,7 +176,7 @@ enum Commands { } const COM_MANIFEST_FILE: &str = ".dynwinrt-com-manifest.json"; -const COM_MANIFEST_VERSION: u32 = 3; +const COM_MANIFEST_VERSION: u32 = 4; #[derive(Debug, Default, Deserialize, Serialize)] struct ComGenerationManifest { @@ -274,7 +274,7 @@ fn run_com_census(winmd: &str, json: bool) -> Result<(), String> { .collect::>(); let complete = eligible .iter() - .filter(|interface| com::generate_com_interface_files(interface, winmd).is_ok()) + .filter(|interface| com::generate_complete_com_interface_files(interface, winmd).is_ok()) .count(); let result = ComCensusResult { metadata: winmd.to_string(), @@ -8998,6 +8998,30 @@ mod tests { fs::remove_dir_all(reverse.parent().unwrap()).unwrap(); } + #[test] + fn com_context_manifest_mismatch_requires_clean_regeneration() { + let output = test_directory("com-context-manifest").join("com"); + fs::create_dir_all(&output).unwrap(); + for version in [1, 2, 3] { + let content = serde_json::to_string(&ComGenerationManifest { + version, + roots: BTreeMap::new(), + }) + .unwrap(); + fs::write(output.join(COM_MANIFEST_FILE), &content).unwrap(); + let error = + prepare_com_generation_manifest(&output, &BTreeMap::new(), &BTreeMap::new()) + .unwrap_err(); + assert!(error.contains("delete and regenerate"), "{error}"); + assert!(has_com_output(&output).is_err()); + assert_eq!( + fs::read_to_string(output.join(COM_MANIFEST_FILE)).unwrap(), + content + ); + } + fs::remove_dir_all(output.parent().unwrap()).unwrap(); + } + #[test] fn unsafe_support_schema_mismatch_requires_clean_regeneration() { let output = test_directory("unsafe-schema-mismatch").join("com"); @@ -9005,14 +9029,14 @@ mod tests { fs::create_dir_all(&unsafe_dir).unwrap(); fs::write( unsafe_dir.join("support.json"), - "{\"schemaVersion\":10,\"interfaces\":[]}\n", + "{\"schemaVersion\":11,\"interfaces\":[]}\n", ) .unwrap(); let error = prepare_generated_unsafe_package(&output, &[]).unwrap_err(); assert!( - error.contains("Unsupported generated unsafe support schema 10") - && error.contains("expected 11"), + error.contains("Unsupported generated unsafe support schema 11") + && error.contains("expected 12"), "{error}" ); From 01393d8799e38b2fbcc52ba18891e2099e903ccc Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 8 Sep 2026 16:42:52 +0800 Subject: [PATCH 2/4] Refactor COM borrowed copies into typed execution recipes Centralize reviewed ABI and lifecycle evidence in a shared contracts crate. Execute typed bindings, bounds, copies and finalizers through one plan-driven runtime while preserving public APIs and supported interfaces. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 4 +- .github/workflows/coverage.yml | 1 + .github/workflows/python-release.yml | 1 + Cargo.lock | 10 + Cargo.toml | 1 + bindings/js/__test__/borrowed-copy-child.cjs | 39 +- bindings/js/__test__/borrowed-plan.spec.ts | 100 ++ bindings/js/src/com_borrowed.rs | 150 +-- crates/dynwinrt-com-contracts/Cargo.toml | 11 + crates/dynwinrt-com-contracts/src/lib.rs | 499 ++++++++++ .../dynwinrt-com-contracts/src/registry.json | 857 ++++++++++++++++ crates/dynwinrt-com-contracts/src/tests.rs | 310 ++++++ crates/dynwinrt-com-contracts/src/validate.rs | 920 ++++++++++++++++++ crates/dynwinrt/Cargo.toml | 1 + crates/dynwinrt/src/com_borrowed.rs | 635 +----------- crates/dynwinrt/src/com_borrowed_plan.rs | 882 +++++++++++++++++ .../dynwinrt/src/com_borrowed_plan_tests.rs | 309 ++++++ .../src/com_borrowed_reordered_support.rs | 417 ++++++++ .../dynwinrt/src/com_borrowed_test_support.rs | 16 +- crates/dynwinrt/src/com_borrowed_tests.rs | 13 +- .../classic-com-contract-evidence-registry.md | 13 +- docs/architecture/classic-com-support.md | 73 +- docs/guides/windows/classic-com-usage.md | 14 +- eng/coverage/coverage.ps1 | 1 + tools/dynwinrt-codegen/Cargo.toml | 1 + .../src/codegen/com/model/borrowed.rs | 204 +--- .../src/codegen/com/project/borrowed.rs | 86 +- .../src/com_borrowed_metadata.rs | 443 ++------- .../dynwinrt-codegen/src/contract_registry.rs | 4 +- tools/dynwinrt-codegen/src/main.rs | 4 +- 30 files changed, 4648 insertions(+), 1371 deletions(-) create mode 100644 bindings/js/__test__/borrowed-plan.spec.ts create mode 100644 crates/dynwinrt-com-contracts/Cargo.toml create mode 100644 crates/dynwinrt-com-contracts/src/lib.rs create mode 100644 crates/dynwinrt-com-contracts/src/registry.json create mode 100644 crates/dynwinrt-com-contracts/src/tests.rs create mode 100644 crates/dynwinrt-com-contracts/src/validate.rs create mode 100644 crates/dynwinrt/src/com_borrowed_plan.rs create mode 100644 crates/dynwinrt/src/com_borrowed_plan_tests.rs create mode 100644 crates/dynwinrt/src/com_borrowed_reordered_support.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 84e1d2e3..13168688 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -72,7 +72,9 @@ jobs: "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV - name: Test core library - run: cargo test -p dynwinrt + run: cargo test -p dynwinrt-com-contracts -p dynwinrt + - name: Test borrowed-copy contracts on i686 + run: cargo test -p dynwinrt-com-contracts --target i686-pc-windows-msvc - name: Test borrowed-copy ABI on live i686 run: cargo test -p dynwinrt --target i686-pc-windows-msvc --lib borrowed_copy - name: Test dynwinrt-codegen diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index f1175164..bbe33c65 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -13,6 +13,7 @@ on: - 'bindings/js/**' - 'bindings/py/**' - 'crates/dynwinrt/**' + - 'crates/dynwinrt-com-contracts/**' - 'eng/coverage/**' - 'tests/e2e/**' - 'tools/dynwinrt-codegen/**' diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml index 91a910fe..a13ef775 100644 --- a/.github/workflows/python-release.yml +++ b/.github/workflows/python-release.yml @@ -10,6 +10,7 @@ on: - '.github/workflows/python-release.yml' - 'bindings/py/**' - 'crates/dynwinrt/**' + - 'crates/dynwinrt-com-contracts/**' - 'eng/release/python/prepare_python_release.py' - 'eng/release/python/test_python_*_wheel.ps1' - 'eng/release/python/verify_python_release.py' diff --git a/Cargo.lock b/Cargo.lock index 4cf05302..a1039732 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -351,6 +351,7 @@ name = "dynwinrt" version = "0.1.0" dependencies = [ "criterion", + "dynwinrt-com-contracts", "futures", "libffi", "libffi-sys", @@ -370,6 +371,7 @@ version = "0.1.0" dependencies = [ "clap", "csv", + "dynwinrt-com-contracts", "fs2", "regex", "roxmltree", @@ -380,6 +382,14 @@ dependencies = [ "windows-metadata", ] +[[package]] +name = "dynwinrt-com-contracts" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "dynwinrt-py" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index aa60b45f..fd122a89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "crates/dynwinrt-com-contracts", "crates/dynwinrt", "bindings/js", "benchmarks/js/static-rust", diff --git a/bindings/js/__test__/borrowed-copy-child.cjs b/bindings/js/__test__/borrowed-copy-child.cjs index 13ba463b..c646e83b 100644 --- a/bindings/js/__test__/borrowed-copy-child.cjs +++ b/bindings/js/__test__/borrowed-copy-child.cjs @@ -246,19 +246,32 @@ if (scenario === 'audio') { assert.equal(descriptor.exposure, 'owned-copy-only') assert.equal(descriptor.access, 'read-write') assert.equal(descriptor.owner, 'receiver') - assert.deepEqual(descriptor.acquire.storage, ['borrowed-bytes', 'out-u32', 'out-u32']) + assert.equal(descriptor.version, 2) + const acquisition = descriptor.calls.find((call) => call.id === descriptor.operations[0].acquire) + assert.deepEqual( + acquisition.bindings.map((binding) => binding.storage), + ['borrowed-bytes', 'out-u32', 'out-u32'], + ) + assert.equal(acquisition.evidence, 'IMFMediaBuffer.Lock') + assert.equal(descriptor.operations[0].after[0].current, 'current') + assert.equal(descriptor.operations[1].after[0].length, 'input.bytes') + assert.equal(descriptor.operations[1].commit[0], 'set-length') + assert.throws( + () => unsafe.DynComBorrowedCopyPlan.prepare(JSON.stringify({ ...descriptor, version: 1 })), + /fully regenerate/i, + ) for (const edit of [ (d) => { d.version++ }, (d) => { - d.acquire.slot++ + d.calls[0].slot = 42 }, (d) => { - d.audio_origin_required = true + d.audio_origin = { role: 'render' } }, (d) => { - d.finalize = null + d.operations[0].cleanup = null }, (d) => { d.metadata_sha256 = 'unknown' @@ -275,6 +288,24 @@ if (scenario === 'audio') { (d) => { d.empty_hresult = 0x08890001 }, + (d) => { + d.calls[0].evidence = 'unknown.Lock' + }, + (d) => { + d.calls[0].bindings[1].unit = 'frames' + }, + (d) => { + d.calls[0].bindings[1].name = d.calls[0].bindings[2].name + }, + (d) => { + d.operations[0].after[0].length = 'uninitialized' + }, + (d) => { + d.operations[1].commit = [] + }, + (d) => { + d.id = 'matching-looking-json' + }, ]) { const changed = structuredClone(descriptor) edit(changed) diff --git a/bindings/js/__test__/borrowed-plan.spec.ts b/bindings/js/__test__/borrowed-plan.spec.ts new file mode 100644 index 00000000..6d58485b --- /dev/null +++ b/bindings/js/__test__/borrowed-plan.spec.ts @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import test from 'ava' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' + +const native = createRequire(import.meta.url)('../dist/index.js') +const registry = JSON.parse( + readFileSync(new URL('../../../crates/dynwinrt-com-contracts/src/registry.json', import.meta.url), 'utf8'), +) +const descriptor = (id: string) => structuredClone(registry.copies.find((copy: { id: string }) => copy.id === id)) +const prepare = (id: string) => native.DynComBorrowedCopyPlan.prepare(JSON.stringify(descriptor(id))) +const events = (fixture: { events(): string[] }, prefix: string) => + fixture.events().filter((event) => event.startsWith(prefix)).length + +test('borrowed plan rejects old, forged and ill-typed descriptors', (t) => { + for (const edit of [ + (d: any) => (d.version = 1), + (d: any) => (d.id = 'unreviewed'), + (d: any) => (d.calls[0].evidence = 'unknown.Lock'), + (d: any) => (d.calls[0].bindings[1].unit = 'frames'), + (d: any) => (d.calls[0].bindings[1].name = 'current'), + (d: any) => (d.operations[0].after[0].length = 'forward-output'), + (d: any) => (d.operations[1].commit = []), + (d: any) => (d.operations[0].cleanup = null), + ]) { + const changed = descriptor('media-buffer') + edit(changed) + t.throws(() => native.DynComBorrowedCopyPlan.prepare(JSON.stringify(changed)), { + message: /fully regenerate/i, + }) + } +}) + +if (typeof native.DynComBorrowedCopyTestFixture !== 'function') { + test.skip('borrowed plan native fixtures require test-hooks', () => {}) +} else { + test.before(() => native.initializeCom(0)) + + test.serial('borrowed plan copies owned bytes and executes length commit/cleanup', (t) => { + const fixture = new native.DynComBorrowedCopyTestFixture() + const object = fixture.object('media') + const plan = prepare('media-buffer') + try { + const before = plan.readCopy(object) + plan.replaceCopy(object, new Uint8Array([9, 8, 7])) + t.deepEqual(before, Buffer.from([0, 1, 2, 3])) + t.deepEqual(plan.readCopy(object), Buffer.from([9, 8, 7])) + t.throws(() => plan.replaceCopy(object, Buffer.alloc(17)), { message: /capacity/i }) + fixture.configure('mediaSetHr', 0x80004005) + t.throws(() => plan.replaceCopy(object, Buffer.alloc(4))) + t.is(events(fixture, 'media.acquire'), events(fixture, 'media.unlock')) + fixture.configure('mediaUnlockHr', 0x80004005) + t.throws(() => plan.readCopy(object)) + const unlocks = events(fixture, 'media.unlock') + t.throws(() => plan.readCopy(object), { message: /poisoned/i }) + t.is(events(fixture, 'media.unlock'), unlocks) + } finally { + object.release() + fixture.releaseOwners() + } + }) + + test.serial('borrowed plan packs bounded rows and releases its acquired owner', (t) => { + const fixture = new native.DynComBorrowedCopyTestFixture() + const object = fixture.object('bitmap') + const plan = prepare('bitmap-bgra8') + try { + const copy = plan.readLockedBgra8Copy(object, [0, 0, 2, 2]) + t.deepEqual(copy.data, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19])) + t.deepEqual([copy.width, copy.height], [2, 2]) + copy.data[0] = 99 + t.is(fixture.bytes()[0], 0) + fixture.configure('wicCount', 19) + t.throws(() => plan.readLockedBgra8Copy(object, [0, 0, 2, 2]), { message: /span/i }) + t.is(events(fixture, 'wic.release'), 2) + t.throws(() => plan.readLockedBgra8Copy(object, [0, 0, 2.5, 2]), { message: /integer/i }) + } finally { + object.release() + fixture.releaseOwners() + } + }) + + test.serial('borrowed plan cannot create provenance for untracked audio', (t) => { + const fixture = new native.DynComBorrowedCopyTestFixture() + const render = fixture.object('render') + const capture = fixture.object('capture') + try { + t.throws(() => prepare('audio-render').writeFramesCopy(render, Buffer.alloc(4)), { message: /observed/i }) + t.throws(() => prepare('audio-capture').readPacketCopy(capture), { message: /observed/i }) + t.is(events(fixture, 'render.acquire'), 0) + t.is(events(fixture, 'capture.acquire'), 0) + } finally { + render.release() + capture.release() + fixture.releaseOwners() + } + }) +} diff --git a/bindings/js/src/com_borrowed.rs b/bindings/js/src/com_borrowed.rs index e6d77bfa..3fc58f0f 100644 --- a/bindings/js/src/com_borrowed.rs +++ b/bindings/js/src/com_borrowed.rs @@ -1,19 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use dynwinrt::com::borrowed::{ - BorrowOwner, BorrowedCopyContract, BorrowedCopyPlan, CallContract, ContextEffect, CopyKind, - Extent, Finalization, MemoryAccess, Storage, -}; +use dynwinrt::com::borrowed::{contracts, BorrowedCopyContract, BorrowedCopyPlan, ContextEffect}; use napi::bindgen_prelude::{BigInt, Buffer, Unknown}; use napi_derive::napi; use serde::Deserialize; -use windows::core::GUID; use super::{com, DynWinRTValue, TABLE}; -const METADATA_HASH: &str = "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; - fn invalid(message: impl Into) -> napi::Error { napi::Error::from_reason(message) } @@ -34,146 +28,28 @@ struct EffectDescriptor { pub(super) fn parse_effect(value: &str) -> napi::Result { let value: EffectDescriptor = serde_json::from_str(value) .map_err(|e| invalid(format!("Invalid audio context descriptor: {e}")))?; - let (effect, fingerprint) = match value.effect.as_str() { - "audio-initialize" => ( - ContextEffect::AudioInitialize, - "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", - ), - "audio-initialize-shared" => ( - ContextEffect::AudioInitializeShared, - "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", - ), - "audio-get-service" => ( - ContextEffect::AudioGetService, - "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", - ), + let effect = match value.effect.as_str() { + "audio-initialize" => ContextEffect::AudioInitialize, + "audio-initialize-shared" => ContextEffect::AudioInitializeShared, + "audio-get-service" => ContextEffect::AudioGetService, _ => return Err(invalid("Unsupported audio context effect")), }; + let evidence = contracts::registry() + .evidence + .iter() + .find(|entry| entry.effect.as_deref() == Some(value.effect.as_str())) + .ok_or_else(|| invalid("Unknown audio context evidence"))?; if value.version != 1 - || value.metadata_sha256 != METADATA_HASH - || value.fingerprint != fingerprint + || value.metadata_sha256 != contracts::METADATA_SHA256 + || value.fingerprint != evidence.fingerprint { return Err(invalid("Audio context evidence drift; regenerate bindings")); } Ok(effect) } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Descriptor { - version: u32, - metadata_sha256: String, - access: String, - exposure: String, - owner: String, - acquired_hresult: i32, - empty_hresult: Option, - kind: String, - receiver: String, - acquire: CallDescriptor, - queries: Vec, - finalize: Option, - extent: String, - finalization: String, - sta_only: bool, - audio_origin_required: bool, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct CallDescriptor { - iid: String, - slot: usize, - storage: Vec, -} - -impl CallDescriptor { - fn contract(self) -> napi::Result { - Ok(CallContract { - iid: GUID::try_from(self.iid.as_str()).map_err(|_| invalid("Invalid borrowed-copy IID"))?, - slot: self.slot, - storage: self - .storage - .iter() - .map(|value| match value.as_str() { - "in-u32" => Ok(Storage::InU32), - "in-rect" => Ok(Storage::InRect), - "out-u32" => Ok(Storage::OutU32), - "out-u64" => Ok(Storage::OutU64), - "out-guid" => Ok(Storage::OutGuid), - "borrowed-bytes" => Ok(Storage::BorrowedBytes), - "owned-interface" => Ok(Storage::OwnedInterface), - _ => Err(invalid("Unsupported borrowed-copy native storage")), - }) - .collect::>()?, - }) - } -} - fn parse_contract(value: &str) -> napi::Result { - let value: Descriptor = serde_json::from_str(value) - .map_err(|e| invalid(format!("Invalid borrowed-copy descriptor: {e}")))?; - if value.version != 1 - || value.metadata_sha256 != METADATA_HASH - || value.exposure != "owned-copy-only" - { - return Err(invalid( - "Borrowed-copy descriptor version/evidence/access drift", - )); - } - let kind = match value.kind.as_str() { - "audio-render" => CopyKind::AudioRender, - "audio-capture" => CopyKind::AudioCapture, - "bitmap-bgra8" => CopyKind::BitmapBgra8, - "media-buffer" => CopyKind::MediaBuffer, - _ => return Err(invalid("Unsupported borrowed-copy kind")), - }; - let extent = match value.extent.as_str() { - "initialized-frames" => Extent::InitializedFrames, - "capture-packet-frames" => Extent::CapturePacketFrames, - "native-bgra8-rows" => Extent::NativeBgra8Rows, - "native-current-and-max" => Extent::NativeCurrentAndMax, - _ => return Err(invalid("Unsupported borrowed-copy native extent")), - }; - let finalization = match value.finalization.as_str() { - "render-full-or-zero" => Finalization::RenderFullOrZero, - "capture-full-or-zero" => Finalization::CaptureFullOrZero, - "release-lock-reference" => Finalization::ReleaseLockReference, - "unlock" => Finalization::Unlock, - _ => return Err(invalid("Unsupported borrowed-copy finalizer")), - }; - let access = match value.access.as_str() { - "read" => MemoryAccess::Read, - "write" => MemoryAccess::Write, - "read-write" => MemoryAccess::ReadWrite, - _ => return Err(invalid("Unsupported borrowed-copy access")), - }; - let owner = match value.owner.as_str() { - "receiver" => BorrowOwner::Receiver, - "audio-service-origin" => BorrowOwner::AudioServiceOrigin, - "acquired-interface" => BorrowOwner::AcquiredInterface, - _ => return Err(invalid("Unsupported borrowed-copy owner")), - }; - Ok(BorrowedCopyContract { - kind, - extent, - finalization, - receiver: GUID::try_from(value.receiver.as_str()) - .map_err(|_| invalid("Invalid borrowed-copy receiver IID"))?, - acquire: value.acquire.contract()?, - queries: value - .queries - .into_iter() - .map(CallDescriptor::contract) - .collect::>()?, - finalize: value.finalize.map(CallDescriptor::contract).transpose()?, - sta_only: value.sta_only, - audio_origin_required: value.audio_origin_required, - access, - owner, - acquired_hresult: value.acquired_hresult, - empty_hresult: value.empty_hresult, - }) + BorrowedCopyContract::parse(value).map_err(invalid) } #[napi] diff --git a/crates/dynwinrt-com-contracts/Cargo.toml b/crates/dynwinrt-com-contracts/Cargo.toml new file mode 100644 index 00000000..068bc745 --- /dev/null +++ b/crates/dynwinrt-com-contracts/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "dynwinrt-com-contracts" +version = "0.1.0" +edition = "2024" +license = "MIT" +description = "Native-independent reviewed contracts for bounded dynwinrt COM copies" +repository = "https://github.com/microsoft/dynwinrt" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/crates/dynwinrt-com-contracts/src/lib.rs b/crates/dynwinrt-com-contracts/src/lib.rs new file mode 100644 index 00000000..d99d7b5f --- /dev/null +++ b/crates/dynwinrt-com-contracts/src/lib.rs @@ -0,0 +1,499 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Closed COM copy recipes and their reviewed evidence. No native dependencies. +//! Deserializing or validating a recipe is not native-call authorization: +//! production admission additionally requires equality with a packaged record. + +use serde::{Deserialize, Serialize}; +use std::sync::LazyLock; + +#[cfg(test)] +mod tests; +mod validate; + +pub const DESCRIPTOR_VERSION: u32 = 2; +pub const METADATA_SHA256: &str = + "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; +pub const REGENERATE: &str = "Unsupported borrowed-copy descriptor/evidence; fully regenerate bindings with the current generator (no incremental migration)"; + +macro_rules! reference { + ($($name:ident),+ $(,)?) => {$( + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub String); + )+}; +} + +reference!( + ByteCountRef, + FrameCountRef, + PixelCountRef, + StrideRef, + FlagsRef, + TimestampRef, + GuidRef, + BytesRef, + OwnerRef, + RectRef, + ExtentRef, + LayoutRef, +); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum CopyKind { + AudioRender, + AudioCapture, + BitmapBgra8, + MediaBuffer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Storage { + InU32, + InRect, + OutU32, + OutU64, + OutGuid, + BorrowedBytes, + OwnedInterface, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Unit { + Scalar, + Bytes, + Frames, + Pixels, + Stride, + Flags, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum AbiCell { + InU32(Unit), + InRect, + OutU32(Unit), + OutU64, + OutGuid, + BorrowedBytes, + OwnedInterface, +} + +impl AbiCell { + pub fn storage(&self) -> Storage { + match self { + Self::InU32(_) => Storage::InU32, + Self::InRect => Storage::InRect, + Self::OutU32(_) => Storage::OutU32, + Self::OutU64 => Storage::OutU64, + Self::OutGuid => Storage::OutGuid, + Self::BorrowedBytes => Storage::BorrowedBytes, + Self::OwnedInterface => Storage::OwnedInterface, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum U32Source { + Constant(u32), + SilentFlag(u32), + Bytes(ByteCountRef), + Frames(FrameCountRef), + Flags(FlagsRef), + Pixels(PixelCountRef), +} + +impl U32Source { + fn unit(&self) -> Option { + match self { + Self::Constant(_) => None, + Self::Bytes(_) => Some(Unit::Bytes), + Self::Frames(_) => Some(Unit::Frames), + Self::SilentFlag(_) | Self::Flags(_) => Some(Unit::Flags), + Self::Pixels(_) => Some(Unit::Pixels), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "storage", rename_all = "kebab-case", deny_unknown_fields)] +pub enum Binding { + InU32 { value: U32Source }, + InRect { value: RectRef }, + OutU32 { name: String, unit: Unit }, + OutU64 { name: String }, + OutGuid { name: String }, + BorrowedBytes { name: String }, + OwnedInterface { name: String, interface: String }, +} + +impl Binding { + pub fn storage(&self) -> Storage { + match self { + Self::InU32 { .. } => Storage::InU32, + Self::InRect { .. } => Storage::InRect, + Self::OutU32 { .. } => Storage::OutU32, + Self::OutU64 { .. } => Storage::OutU64, + Self::OutGuid { .. } => Storage::OutGuid, + Self::BorrowedBytes { .. } => Storage::BorrowedBytes, + Self::OwnedInterface { .. } => Storage::OwnedInterface, + } + } + + pub fn output_name(&self) -> Option<&str> { + match self { + Self::InU32 { .. } | Self::InRect { .. } => None, + Self::OutU32 { name, .. } + | Self::OutU64 { name } + | Self::OutGuid { name } + | Self::BorrowedBytes { name } + | Self::OwnedInterface { name, .. } => Some(name), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum Target { + Receiver, + AudioOrigin, + Acquired(OwnerRef), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CallContract { + pub id: String, + pub evidence: String, + pub target: Target, + pub bindings: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum MemoryAccess { + Read, + Write, + ReadWrite, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum BorrowOwner { + Receiver, + AudioServiceOrigin, + AcquiredInterface, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum AudioRole { + Render, + Capture, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AudioOrigin { + pub role: AudioRole, + pub interface: String, + pub layout: LayoutRef, + pub reject_exclusive_event: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OperationId { + WriteFramesCopy, + WriteSilence, + ReadPacketCopy, + ReadLockedBgra8Copy, + ReadCopy, + ReplaceCopy, +} + +impl OperationId { + pub fn name(self) -> &'static str { + match self { + Self::WriteFramesCopy => "writeFramesCopy", + Self::WriteSilence => "writeSilence", + Self::ReadPacketCopy => "readPacketCopy", + Self::ReadLockedBgra8Copy => "readLockedBgra8Copy", + Self::ReadCopy => "readCopy", + Self::ReplaceCopy => "replaceCopy", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum InputKind { + None, + Bytes, + Frames, + Rectangle, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum FrameInput { + Bytes, + Frames, +} + +/// No general arithmetic, arbitrary branches, pointer inputs or callbacks. +/// Each extent constructor proves one reviewed native memory relationship. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "kebab-case", deny_unknown_fields)] +pub enum Step { + Call { + call: String, + }, + InputFrames { + frames: FrameCountRef, + layout: LayoutRef, + source: FrameInput, + }, + ReturnIfZero { + frames: FrameCountRef, + }, + FrameExtent { + extent: ExtentRef, + frames: FrameCountRef, + capacity: FrameCountRef, + layout: LayoutRef, + nonzero: bool, + }, + NativeExtent { + extent: ExtentRef, + current: ByteCountRef, + capacity: ByteCountRef, + length: ByteCountRef, + }, + RectBounds { + rect: RectRef, + width: PixelCountRef, + height: PixelCountRef, + }, + RowExtent { + extent: ExtentRef, + rect: RectRef, + width: PixelCountRef, + height: PixelCountRef, + stride: StrideRef, + count: ByteCountRef, + format: GuidRef, + format_guid: String, + pixel_bytes: u32, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FlagCondition { + pub flags: FlagsRef, + pub mask: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "direction", rename_all = "kebab-case", deny_unknown_fields)] +pub enum Transfer { + Read { + pointer: BytesRef, + extent: ExtentRef, + silent: Option, + }, + Write { + pointer: BytesRef, + extent: ExtentRef, + }, + NoPayload { + extent: ExtentRef, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum Cleanup { + Call { call: String, abort: Vec }, + ReleaseOwner { owner: OwnerRef }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum ResultMapping { + Void, + Bytes, + Packet { + frames: FrameCountRef, + flags: FlagsRef, + device: TimestampRef, + qpc: TimestampRef, + timestamp_error_mask: u32, + }, + Bitmap { + width: PixelCountRef, + height: PixelCountRef, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Operation { + pub api: OperationId, + pub arguments: InputKind, + pub before: Vec, + pub acquire: String, + pub after: Vec, + pub transfer: Transfer, + pub commit: Vec, + pub cleanup: Cleanup, + pub result: ResultMapping, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BorrowedCopyContract { + pub version: u32, + pub metadata_sha256: String, + pub exposure: String, + pub id: String, + // A compatibility/display label, never an executor or model dispatch key. + pub kind: CopyKind, + pub receiver: String, + pub copy_only: bool, + pub dependencies: Vec, + pub access: MemoryAccess, + pub owner: BorrowOwner, + pub sta_only: bool, + pub audio_origin: Option, + pub acquired_hresult: i32, + pub empty_hresult: Option, + pub calls: Vec, + pub operations: Vec, +} + +impl BorrowedCopyContract { + pub fn expected(kind: CopyKind) -> Self { + registry() + .copies + .iter() + .find(|copy| copy.kind == kind) + .expect("packaged copy") + .clone() + } + + pub fn parse(value: &str) -> Result { + let header: serde_json::Value = + serde_json::from_str(value).map_err(|e| format!("{REGENERATE}: {e}"))?; + if header.get("version").and_then(serde_json::Value::as_u64) + != Some(u64::from(DESCRIPTOR_VERSION)) + { + return Err(REGENERATE.into()); + } + let contract = serde_json::from_str(value).map_err(|e| format!("{REGENERATE}: {e}"))?; + registry().admit(&contract)?; + Ok(contract) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct InterfaceRecord { + pub namespace: String, + pub name: String, + pub iid: String, + pub bases: Vec, + pub base_iids: Vec, + pub own_start: usize, + pub last: usize, + pub context: bool, + pub catalog: bool, + pub required_evidence: Vec, +} + +impl InterfaceRecord { + pub fn identity(&self) -> String { + format!("{}.{}", self.namespace, self.name) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum AcquisitionCleanup { + Call { evidence: String }, + ReleaseOwner, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Evidence { + pub id: String, + pub namespace: String, + pub interface: String, + pub iid: String, + pub method: String, + pub slot: usize, + pub fingerprint: String, + pub effect: Option, + pub citation: String, + pub abi: Option>, + pub acquisition_cleanup: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Registry { + pub interfaces: Vec, + pub evidence: Vec, + pub copies: Vec, +} + +impl Registry { + pub fn interface(&self, identity: &str) -> Result<&InterfaceRecord, String> { + self.interfaces + .iter() + .find(|record| record.identity() == identity) + .ok_or_else(|| format!("Unknown registry interface {identity}")) + } + + pub fn select(&self, namespace: &str, name: &str, iid: &str) -> Option<&BorrowedCopyContract> { + self.copies.iter().find(|copy| { + self.interface(©.receiver).is_ok_and(|record| { + record.namespace == namespace && record.name == name && record.iid == iid + }) + }) + } + + pub fn evidence(&self, id: &str) -> Result<&Evidence, String> { + self.evidence + .iter() + .find(|entry| entry.id == id) + .ok_or_else(|| format!("Unknown registry evidence {id}")) + } + + pub fn admit(&self, contract: &BorrowedCopyContract) -> Result<(), String> { + if !self + .copies + .iter() + .any(|record| record.id == contract.id && record == contract) + { + return Err(REGENERATE.into()); + } + self.validate(contract) + .map_err(|e| format!("{REGENERATE}: {e}")) + } +} + +pub fn registry() -> &'static Registry { + static REGISTRY: LazyLock = LazyLock::new(|| { + serde_json::from_str(include_str!("registry.json")).expect("packaged COM copy registry") + }); + ®ISTRY +} diff --git a/crates/dynwinrt-com-contracts/src/registry.json b/crates/dynwinrt-com-contracts/src/registry.json new file mode 100644 index 00000000..1ef5d99d --- /dev/null +++ b/crates/dynwinrt-com-contracts/src/registry.json @@ -0,0 +1,857 @@ +{ + "interfaces": [ + { + "namespace": "Windows.Win32.Media.Audio", + "name": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 14, + "context": true, + "catalog": true, + "required_evidence": [3, 4, 14] + }, + { + "namespace": "Windows.Win32.Media.Audio", + "name": "IAudioClient2", + "iid": "726778cd-f60a-4eda-82de-e47610cd78aa", + "bases": ["IAudioClient", "IUnknown"], + "base_iids": ["1cb9ad4c-dbfa-4c32-b178-c2f568a703b2"], + "own_start": 15, + "last": 17, + "context": true, + "catalog": true, + "required_evidence": [3, 4, 14] + }, + { + "namespace": "Windows.Win32.Media.Audio", + "name": "IAudioClient3", + "iid": "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42", + "bases": ["IAudioClient2", "IAudioClient", "IUnknown"], + "base_iids": [ + "726778cd-f60a-4eda-82de-e47610cd78aa", + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2" + ], + "own_start": 18, + "last": 20, + "context": true, + "catalog": true, + "required_evidence": [3, 4, 14, 20] + }, + { + "namespace": "Windows.Win32.Media.Audio", + "name": "IAudioRenderClient", + "iid": "f294acfc-3146-4483-a7bf-addca7c260e2", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 4, + "context": false, + "catalog": true, + "required_evidence": [3, 4] + }, + { + "namespace": "Windows.Win32.Media.Audio", + "name": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 5, + "context": false, + "catalog": true, + "required_evidence": [3, 4, 5] + }, + { + "namespace": "Windows.Win32.Graphics.Imaging", + "name": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 7, + "context": false, + "catalog": false, + "required_evidence": [3, 4, 5, 6, 7] + }, + { + "namespace": "Windows.Win32.Graphics.Imaging", + "name": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "bases": ["IWICBitmapSource", "IUnknown"], + "base_iids": ["00000120-a8f2-4877-ba0a-fd2b6645fb94"], + "own_start": 8, + "last": 10, + "context": false, + "catalog": true, + "required_evidence": [3, 4, 5, 6, 7, 8, 9, 10] + }, + { + "namespace": "Windows.Win32.Graphics.Imaging", + "name": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 6, + "context": false, + "catalog": true, + "required_evidence": [3, 4, 5, 6] + }, + { + "namespace": "Windows.Win32.Media.MediaFoundation", + "name": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "bases": ["IUnknown"], + "base_iids": [], + "own_start": 3, + "last": 7, + "context": false, + "catalog": true, + "required_evidence": [3, 4, 5, 6, 7] + } + ], + "evidence": [ + { + "id": "IAudioClient.Initialize", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "Initialize", + "slot": 3, + "fingerprint": "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", + "effect": "audio-initialize", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-initialize", + "abi": null + }, + { + "id": "IAudioClient.GetService", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetService", + "slot": 14, + "fingerprint": "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", + "effect": "audio-get-service", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getservice", + "abi": null + }, + { + "id": "IAudioClient3.InitializeSharedAudioStream", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient3", + "iid": "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42", + "method": "InitializeSharedAudioStream", + "slot": 20, + "fingerprint": "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", + "effect": "audio-initialize-shared", + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream", + "abi": null + }, + { + "id": "IAudioClient.GetBufferSize", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetBufferSize", + "slot": 4, + "fingerprint": "9F0C09DD69B785A9B4A339ECD2A1970E8574BDBA0F173E3ACF630407A9AB14BE", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getbuffersize", + "abi": [{"out-u32": "frames"}] + }, + { + "id": "IAudioRenderClient.GetBuffer", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioRenderClient", + "iid": "f294acfc-3146-4483-a7bf-addca7c260e2", + "method": "GetBuffer", + "slot": 3, + "fingerprint": "E99E87341B5820E896608A563B67ABCF2A0F9BD833202788950D9FAE8F69E2DB", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-getbuffer", + "abi": [{"in-u32": "frames"}, "borrowed-bytes"], + "acquisition_cleanup": {"kind": "call", "evidence": "IAudioRenderClient.ReleaseBuffer"} + }, + { + "id": "IAudioRenderClient.ReleaseBuffer", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioRenderClient", + "iid": "f294acfc-3146-4483-a7bf-addca7c260e2", + "method": "ReleaseBuffer", + "slot": 4, + "fingerprint": "C79B7868B7940E7D879DC90CA1BAC56E386DA7C8E0F7790DFAB7FB8971E0D767", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-releasebuffer", + "abi": [{"in-u32": "frames"}, {"in-u32": "flags"}] + }, + { + "id": "IAudioCaptureClient.GetBuffer", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "GetBuffer", + "slot": 3, + "fingerprint": "DDD954B2807361F2D50D38C8054846A02577E820B6D42E0B82130F785AA3E370", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer", + "abi": ["borrowed-bytes", {"out-u32": "frames"}, {"out-u32": "flags"}, "out-u64", "out-u64"], + "acquisition_cleanup": {"kind": "call", "evidence": "IAudioCaptureClient.ReleaseBuffer"} + }, + { + "id": "IAudioCaptureClient.ReleaseBuffer", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "ReleaseBuffer", + "slot": 4, + "fingerprint": "82D3C575E5031A345E01026F01E600C8887B081DF6F79CA514B49B78F01E5E17", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-releasebuffer", + "abi": [{"in-u32": "frames"}] + }, + { + "id": "IAudioCaptureClient.GetNextPacketSize", + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioCaptureClient", + "iid": "c8adbd64-e71e-48a0-a4de-185c395cd317", + "method": "GetNextPacketSize", + "slot": 5, + "fingerprint": "C540B744DB900C7D5EDAD03422FC17E7034A822832F4A39DC2DD8519B0978209", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getnextpacketsize", + "abi": null + }, + { + "id": "IWICBitmapSource.GetSize", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetSize", + "slot": 3, + "fingerprint": "F0CBF53A188710273FE737C1A06CDA40FA799C4326F3CA9BF68988E5072B5DA2", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getsize", + "abi": [{"out-u32": "pixels"}, {"out-u32": "pixels"}] + }, + { + "id": "IWICBitmapSource.GetPixelFormat", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetPixelFormat", + "slot": 4, + "fingerprint": "D45F675B2B76A3A9BE908AFBAC03BF4CEC2BD5D8162C1BF28F01FA558B2B6F98", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getpixelformat", + "abi": null + }, + { + "id": "IWICBitmapSource.GetResolution", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetResolution", + "slot": 5, + "fingerprint": "3545A1714671B8C7223BF21693848300001272CDD14E1BE6C188680EA5BD75DD", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getresolution", + "abi": null + }, + { + "id": "IWICBitmapSource.CopyPalette", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "CopyPalette", + "slot": 6, + "fingerprint": "CBBEDB597008ED4EA9032EE361F19AC676DA973DA93A1CB8B0B7D67E24CA4A8C", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypalette", + "abi": null + }, + { + "id": "IWICBitmapSource.CopyPixels", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapSource", + "iid": "00000120-a8f2-4877-ba0a-fd2b6645fb94", + "method": "CopyPixels", + "slot": 7, + "fingerprint": "78BA461831509B5574CB3F8485FE071B875E1AA1FF4ABC4EBB4ADE74A1AE0A9A", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypixels", + "abi": null + }, + { + "id": "IWICBitmap.Lock", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "Lock", + "slot": 8, + "fingerprint": "BE432E367AC62157C546DB3F21AE11B89025F930D4AE397ECC5B6A6F2016D154", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-lock", + "abi": ["in-rect", {"in-u32": "flags"}, "owned-interface"], + "acquisition_cleanup": {"kind": "release-owner"} + }, + { + "id": "IWICBitmap.SetPalette", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "SetPalette", + "slot": 9, + "fingerprint": "D714FBE65EE1E239F04D9046C2270572CC8DE81094FCE549D81FF50242BC6F8F", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setpalette", + "abi": null + }, + { + "id": "IWICBitmap.SetResolution", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmap", + "iid": "00000121-a8f2-4877-ba0a-fd2b6645fb94", + "method": "SetResolution", + "slot": 10, + "fingerprint": "394965547E9C14CB338B9AD84677C27CA1D54BF22E4CDBA79A46D26F31C25EB6", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setresolution", + "abi": null + }, + { + "id": "IWICBitmapLock.GetSize", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetSize", + "slot": 3, + "fingerprint": "5FBF3161D277C77796793A167F68999C7B678A182FCBB823CD721DC4BAC83F64", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getsize", + "abi": [{"out-u32": "pixels"}, {"out-u32": "pixels"}] + }, + { + "id": "IWICBitmapLock.GetStride", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetStride", + "slot": 4, + "fingerprint": "0DC2598054C7BCB1D19940355D5BE568D508B332E269D00956BAF22DC854F799", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getstride", + "abi": [{"out-u32": "stride"}] + }, + { + "id": "IWICBitmapLock.GetDataPointer", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetDataPointer", + "slot": 5, + "fingerprint": "FB4F6B8BD302FCA2BB91B231BF957E10D37AC979C39A88992E2526E53349F66C", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getdatapointer", + "abi": [{"out-u32": "bytes"}, "borrowed-bytes"] + }, + { + "id": "IWICBitmapLock.GetPixelFormat", + "namespace": "Windows.Win32.Graphics.Imaging", + "interface": "IWICBitmapLock", + "iid": "00000123-a8f2-4877-ba0a-fd2b6645fb94", + "method": "GetPixelFormat", + "slot": 6, + "fingerprint": "A065B19968592FDA319A1A9DAC7EC1EB51CE63F5D3FFA62C6DD38E92742065E6", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getpixelformat", + "abi": ["out-guid"] + }, + { + "id": "IMFMediaBuffer.Lock", + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "Lock", + "slot": 3, + "fingerprint": "1B9E2C63825F73EE5599F05E9EA180D52FD22F02EDD33BB23028711DDF335172", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-lock", + "abi": ["borrowed-bytes", {"out-u32": "bytes"}, {"out-u32": "bytes"}], + "acquisition_cleanup": {"kind": "call", "evidence": "IMFMediaBuffer.Unlock"} + }, + { + "id": "IMFMediaBuffer.Unlock", + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "Unlock", + "slot": 4, + "fingerprint": "83FB2903C23EBD4BB98C182C6575135225ABD0C3EA78183CDADFB3B027B8107B", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-unlock", + "abi": [] + }, + { + "id": "IMFMediaBuffer.GetCurrentLength", + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "GetCurrentLength", + "slot": 5, + "fingerprint": "AABA562CD26F16571A75D54894E001700500994E98949B4E7A7DA1B6CDE61862", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getcurrentlength", + "abi": null + }, + { + "id": "IMFMediaBuffer.SetCurrentLength", + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "SetCurrentLength", + "slot": 6, + "fingerprint": "75AB892B1685032D840B1E5FECB9CD9A87F8E1865492D24796996674372864CA", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-setcurrentlength", + "abi": [{"in-u32": "bytes"}] + }, + { + "id": "IMFMediaBuffer.GetMaxLength", + "namespace": "Windows.Win32.Media.MediaFoundation", + "interface": "IMFMediaBuffer", + "iid": "045fa593-8799-42b8-bc8d-8968c6453507", + "method": "GetMaxLength", + "slot": 7, + "fingerprint": "738D4850D037E6B9F76F28C7D0403B4D9BDF97F3B04C9B8E5A0EFBA18A3A962C", + "effect": null, + "citation": "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getmaxlength", + "abi": null + } + ], + "copies": [ + { + "version": 2, + "metadata_sha256": "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D", + "exposure": "owned-copy-only", + "id": "audio-render", + "kind": "audio-render", + "receiver": "Windows.Win32.Media.Audio.IAudioRenderClient", + "copy_only": true, + "dependencies": ["Windows.Win32.Media.Audio.IAudioClient"], + "access": "write", + "owner": "audio-service-origin", + "sta_only": false, + "audio_origin": { + "role": "render", + "interface": "Windows.Win32.Media.Audio.IAudioClient", + "layout": "layout", + "reject_exclusive_event": true + }, + "acquired_hresult": 0, + "empty_hresult": null, + "calls": [ + { + "id": "capacity", + "evidence": "IAudioClient.GetBufferSize", + "target": "audio-origin", + "bindings": [ + { "storage": "out-u32", "name": "capacity", "unit": "frames" } + ] + }, + { + "id": "acquire", + "evidence": "IAudioRenderClient.GetBuffer", + "target": "receiver", + "bindings": [ + { "storage": "in-u32", "value": { "frames": "request" } }, + { "storage": "borrowed-bytes", "name": "data" } + ] + }, + { + "id": "release", + "evidence": "IAudioRenderClient.ReleaseBuffer", + "target": "receiver", + "bindings": [ + { "storage": "in-u32", "value": { "frames": "request" } }, + { "storage": "in-u32", "value": { "constant": 0 } } + ] + }, + { + "id": "release-silent", + "evidence": "IAudioRenderClient.ReleaseBuffer", + "target": "receiver", + "bindings": [ + { "storage": "in-u32", "value": { "frames": "request" } }, + { "storage": "in-u32", "value": { "silent-flag": 2 } } + ] + } + ], + "operations": [ + { + "api": "writeFramesCopy", + "arguments": "bytes", + "before": [ + { + "op": "input-frames", + "frames": "request", + "layout": "layout", + "source": "bytes" + }, + { "op": "return-if-zero", "frames": "request" }, + { "op": "call", "call": "capacity" }, + { + "op": "frame-extent", + "extent": "span", + "frames": "request", + "capacity": "capacity", + "layout": "layout", + "nonzero": true + } + ], + "acquire": "acquire", + "after": [], + "transfer": { + "direction": "write", + "pointer": "data", + "extent": "span" + }, + "commit": [], + "cleanup": { + "kind": "call", + "call": "release", + "abort": [{ "constant": 0 }, { "constant": 0 }] + }, + "result": { "kind": "void" } + }, + { + "api": "writeSilence", + "arguments": "frames", + "before": [ + { + "op": "input-frames", + "frames": "request", + "layout": "layout", + "source": "frames" + }, + { "op": "return-if-zero", "frames": "request" }, + { "op": "call", "call": "capacity" }, + { + "op": "frame-extent", + "extent": "span", + "frames": "request", + "capacity": "capacity", + "layout": "layout", + "nonzero": true + } + ], + "acquire": "acquire", + "after": [], + "transfer": { "direction": "no-payload", "extent": "span" }, + "commit": [], + "cleanup": { + "kind": "call", + "call": "release-silent", + "abort": [{ "constant": 0 }, { "constant": 0 }] + }, + "result": { "kind": "void" } + } + ] + }, + { + "version": 2, + "metadata_sha256": "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D", + "exposure": "owned-copy-only", + "id": "audio-capture", + "kind": "audio-capture", + "receiver": "Windows.Win32.Media.Audio.IAudioCaptureClient", + "copy_only": true, + "dependencies": ["Windows.Win32.Media.Audio.IAudioClient"], + "access": "read", + "owner": "audio-service-origin", + "sta_only": false, + "audio_origin": { + "role": "capture", + "interface": "Windows.Win32.Media.Audio.IAudioClient", + "layout": "layout", + "reject_exclusive_event": false + }, + "acquired_hresult": 0, + "empty_hresult": 143196161, + "calls": [ + { + "id": "capacity", + "evidence": "IAudioClient.GetBufferSize", + "target": "audio-origin", + "bindings": [ + { "storage": "out-u32", "name": "capacity", "unit": "frames" } + ] + }, + { + "id": "acquire", + "evidence": "IAudioCaptureClient.GetBuffer", + "target": "receiver", + "bindings": [ + { "storage": "borrowed-bytes", "name": "data" }, + { "storage": "out-u32", "name": "frames", "unit": "frames" }, + { "storage": "out-u32", "name": "flags", "unit": "flags" }, + { "storage": "out-u64", "name": "device" }, + { "storage": "out-u64", "name": "qpc" } + ] + }, + { + "id": "release", + "evidence": "IAudioCaptureClient.ReleaseBuffer", + "target": "receiver", + "bindings": [{ "storage": "in-u32", "value": { "frames": "frames" } }] + } + ], + "operations": [ + { + "api": "readPacketCopy", + "arguments": "none", + "before": [{ "op": "call", "call": "capacity" }], + "acquire": "acquire", + "after": [ + { + "op": "frame-extent", + "extent": "span", + "frames": "frames", + "capacity": "capacity", + "layout": "layout", + "nonzero": true + } + ], + "transfer": { + "direction": "read", + "pointer": "data", + "extent": "span", + "silent": { "flags": "flags", "mask": 2 } + }, + "commit": [], + "cleanup": { + "kind": "call", + "call": "release", + "abort": [{ "constant": 0 }] + }, + "result": { + "kind": "packet", + "frames": "frames", + "flags": "flags", + "device": "device", + "qpc": "qpc", + "timestamp_error_mask": 4 + } + } + ] + }, + { + "version": 2, + "metadata_sha256": "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D", + "exposure": "owned-copy-only", + "id": "bitmap-bgra8", + "kind": "bitmap-bgra8", + "receiver": "Windows.Win32.Graphics.Imaging.IWICBitmap", + "copy_only": false, + "dependencies": ["Windows.Win32.Graphics.Imaging.IWICBitmapLock"], + "access": "read", + "owner": "acquired-interface", + "sta_only": true, + "audio_origin": null, + "acquired_hresult": 0, + "empty_hresult": null, + "calls": [ + { + "id": "bitmap-size", + "evidence": "IWICBitmapSource.GetSize", + "target": "receiver", + "bindings": [ + { "storage": "out-u32", "name": "bitmap-width", "unit": "pixels" }, + { "storage": "out-u32", "name": "bitmap-height", "unit": "pixels" } + ] + }, + { + "id": "acquire", + "evidence": "IWICBitmap.Lock", + "target": "receiver", + "bindings": [ + { "storage": "in-rect", "value": "input.rect" }, + { "storage": "in-u32", "value": { "constant": 1 } }, + { + "storage": "owned-interface", + "name": "lock", + "interface": "Windows.Win32.Graphics.Imaging.IWICBitmapLock" + } + ] + }, + { + "id": "lock-size", + "evidence": "IWICBitmapLock.GetSize", + "target": { "acquired": "lock" }, + "bindings": [ + { "storage": "out-u32", "name": "width", "unit": "pixels" }, + { "storage": "out-u32", "name": "height", "unit": "pixels" } + ] + }, + { + "id": "stride", + "evidence": "IWICBitmapLock.GetStride", + "target": { "acquired": "lock" }, + "bindings": [ + { "storage": "out-u32", "name": "stride", "unit": "stride" } + ] + }, + { + "id": "format", + "evidence": "IWICBitmapLock.GetPixelFormat", + "target": { "acquired": "lock" }, + "bindings": [{ "storage": "out-guid", "name": "format" }] + }, + { + "id": "data", + "evidence": "IWICBitmapLock.GetDataPointer", + "target": { "acquired": "lock" }, + "bindings": [ + { "storage": "out-u32", "name": "count", "unit": "bytes" }, + { "storage": "borrowed-bytes", "name": "data" } + ] + } + ], + "operations": [ + { + "api": "readLockedBgra8Copy", + "arguments": "rectangle", + "before": [ + { "op": "call", "call": "bitmap-size" }, + { + "op": "rect-bounds", + "rect": "input.rect", + "width": "bitmap-width", + "height": "bitmap-height" + } + ], + "acquire": "acquire", + "after": [ + { "op": "call", "call": "lock-size" }, + { "op": "call", "call": "stride" }, + { "op": "call", "call": "format" }, + { "op": "call", "call": "data" }, + { + "op": "row-extent", + "extent": "span", + "rect": "input.rect", + "width": "width", + "height": "height", + "stride": "stride", + "count": "count", + "format": "format", + "format_guid": "6fddc324-4e03-4bfe-b185-3d77768dc90f", + "pixel_bytes": 4 + } + ], + "transfer": { + "direction": "read", + "pointer": "data", + "extent": "span", + "silent": null + }, + "commit": [], + "cleanup": { "kind": "release-owner", "owner": "lock" }, + "result": { "kind": "bitmap", "width": "width", "height": "height" } + } + ] + }, + { + "version": 2, + "metadata_sha256": "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D", + "exposure": "owned-copy-only", + "id": "media-buffer", + "kind": "media-buffer", + "receiver": "Windows.Win32.Media.MediaFoundation.IMFMediaBuffer", + "copy_only": true, + "dependencies": [], + "access": "read-write", + "owner": "receiver", + "sta_only": false, + "audio_origin": null, + "acquired_hresult": 0, + "empty_hresult": null, + "calls": [ + { + "id": "acquire", + "evidence": "IMFMediaBuffer.Lock", + "target": "receiver", + "bindings": [ + { "storage": "borrowed-bytes", "name": "data" }, + { "storage": "out-u32", "name": "maximum", "unit": "bytes" }, + { "storage": "out-u32", "name": "current", "unit": "bytes" } + ] + }, + { + "id": "set-length", + "evidence": "IMFMediaBuffer.SetCurrentLength", + "target": "receiver", + "bindings": [ + { "storage": "in-u32", "value": { "bytes": "input.bytes" } } + ] + }, + { + "id": "unlock", + "evidence": "IMFMediaBuffer.Unlock", + "target": "receiver", + "bindings": [] + } + ], + "operations": [ + { + "api": "readCopy", + "arguments": "none", + "before": [], + "acquire": "acquire", + "after": [ + { + "op": "native-extent", + "extent": "span", + "current": "current", + "capacity": "maximum", + "length": "current" + } + ], + "transfer": { + "direction": "read", + "pointer": "data", + "extent": "span", + "silent": null + }, + "commit": [], + "cleanup": { "kind": "call", "call": "unlock", "abort": [] }, + "result": { "kind": "bytes" } + }, + { + "api": "replaceCopy", + "arguments": "bytes", + "before": [], + "acquire": "acquire", + "after": [ + { + "op": "native-extent", + "extent": "span", + "current": "current", + "capacity": "maximum", + "length": "input.bytes" + } + ], + "transfer": { + "direction": "write", + "pointer": "data", + "extent": "span" + }, + "commit": ["set-length"], + "cleanup": { "kind": "call", "call": "unlock", "abort": [] }, + "result": { "kind": "void" } + } + ] + } + ] +} diff --git a/crates/dynwinrt-com-contracts/src/tests.rs b/crates/dynwinrt-com-contracts/src/tests.rs new file mode 100644 index 00000000..f26b0eaf --- /dev/null +++ b/crates/dynwinrt-com-contracts/src/tests.rs @@ -0,0 +1,310 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; + +fn reject(kind: CopyKind, edit: impl FnOnce(&mut BorrowedCopyContract), reason: &str) { + let mut contract = BorrowedCopyContract::expected(kind); + edit(&mut contract); + let error = registry().validate(&contract).unwrap_err(); + assert!(error.contains(reason), "{error}, expected {reason}"); + assert!(registry().admit(&contract).is_err()); +} + +#[test] +fn packaged_borrowed_copy_recipes_are_typed_and_admitted() { + assert_eq!(registry().copies.len(), 4); + assert_eq!(registry().evidence.len(), 26); + for contract in ®istry().copies { + registry().admit(contract).unwrap(); + assert_eq!( + BorrowedCopyContract::parse(&serde_json::to_string(contract).unwrap()).unwrap(), + *contract, + ); + } +} + +#[test] +fn borrowed_copy_rejects_wrong_native_cells_and_reference_units() { + reject( + CopyKind::MediaBuffer, + |c| { + c.calls[0].bindings[1] = Binding::OutU64 { + name: "maximum".into(), + }; + }, + "ABI cells", + ); + reject( + CopyKind::MediaBuffer, + |c| { + let Binding::OutU32 { unit, .. } = &mut c.calls[0].bindings[1] else { + panic!() + }; + *unit = Unit::Frames; + }, + "Wrong output/reference type", + ); + reject( + CopyKind::MediaBuffer, + |c| { + let Binding::OutU32 { name, .. } = &mut c.calls[0].bindings[1] else { + panic!() + }; + *name = "data".into(); + }, + "Duplicate value/output", + ); +} + +#[test] +fn borrowed_copy_rejects_dangling_forward_and_uninitialized_sources() { + reject( + CopyKind::AudioRender, + |c| { + c.calls[1].bindings[0] = Binding::InU32 { + value: U32Source::Frames(FrameCountRef("not-produced".into())), + }; + }, + "Dangling, forward or uninitialized", + ); + reject( + CopyKind::MediaBuffer, + |c| { + // A source from another operation is not initialized here. + let Step::NativeExtent { length, .. } = &mut c.operations[0].after[0] else { + panic!() + }; + length.0 = "input.bytes".into(); + }, + "Dangling, forward or uninitialized", + ); + reject( + CopyKind::BitmapBgra8, + |c| { + c.operations[0].before.insert( + 0, + Step::Call { + call: "lock-size".into(), + }, + ); + }, + "Unavailable acquired owner", + ); + reject( + CopyKind::AudioRender, + |c| { + c.operations[0].before.swap(2, 3); + }, + "Dangling, forward or uninitialized", + ); +} + +#[test] +fn borrowed_copy_rejects_invalid_bounds_results_and_cleanup_dependencies() { + reject( + CopyKind::MediaBuffer, + |c| { + let Step::NativeExtent { length, .. } = &mut c.operations[1].after[0] else { + panic!() + }; + length.0 = "maximum".into(); + }, + "Copy length", + ); + reject( + CopyKind::AudioCapture, + |c| { + let Cleanup::Call { abort, .. } = &mut c.operations[0].cleanup else { + panic!() + }; + abort[0] = U32Source::Frames(FrameCountRef("frames".into())); + }, + "Dangling, forward or uninitialized", + ); + reject( + CopyKind::AudioCapture, + |c| { + c.calls[2].bindings[0] = Binding::InU32 { + value: U32Source::Constant(0), + }; + }, + "Missing full/zero", + ); + reject( + CopyKind::MediaBuffer, + |c| c.operations[1].commit.clear(), + "requires its native length commit", + ); + reject( + CopyKind::BitmapBgra8, + |c| { + c.operations[0].cleanup = Cleanup::ReleaseOwner { + owner: OwnerRef("other-lock".into()), + }; + }, + "unique acquired cleanup owner", + ); + reject( + CopyKind::BitmapBgra8, + |c| { + let ResultMapping::Bitmap { width, .. } = &mut c.operations[0].result else { + panic!() + }; + width.0 = "bitmap-width".into(); + }, + "Bitmap result", + ); + reject( + CopyKind::MediaBuffer, + |c| c.access = MemoryAccess::Read, + "access policy", + ); +} + +#[test] +fn borrowed_copy_unknown_evidence_and_old_descriptors_fail_closed() { + reject( + CopyKind::MediaBuffer, + |c| c.calls[0].evidence = "unreviewed.Lock".into(), + "Unknown registry evidence", + ); + let mut c = BorrowedCopyContract::expected(CopyKind::MediaBuffer); + c.version = 1; + let error = BorrowedCopyContract::parse(&serde_json::to_string(&c).unwrap()).unwrap_err(); + assert!(error.contains("fully regenerate")); + c.version = 2; + c.id = "matching-looking-json".into(); + assert!( + registry() + .admit(&c) + .unwrap_err() + .contains("fully regenerate") + ); +} + +#[test] +fn borrowed_copy_duplicate_json_fields_and_call_bindings_are_rejected() { + let c = BorrowedCopyContract::expected(CopyKind::MediaBuffer); + let json = serde_json::to_string(&c).unwrap(); + let duplicate = json.replacen("\"version\":2", "\"version\":2,\"version\":2", 1); + assert!(BorrowedCopyContract::parse(&duplicate).is_err()); + reject( + CopyKind::MediaBuffer, + |c| c.calls.push(c.calls[0].clone()), + "Duplicate call binding", + ); +} + +#[test] +fn borrowed_copy_silence_requires_a_typed_normal_commit_flag() { + reject( + CopyKind::AudioRender, + |c| { + let release = c + .calls + .iter_mut() + .find(|call| call.id == "release-silent") + .unwrap(); + release.bindings[1] = Binding::InU32 { + value: U32Source::Constant(0), + }; + }, + "typed silent-flag", + ); + reject( + CopyKind::AudioRender, + |c| { + let Cleanup::Call { abort, .. } = &mut c.operations[1].cleanup else { + panic!() + }; + abort[1] = U32Source::SilentFlag(2); + }, + "Abort cannot commit", + ); +} + +#[test] +fn borrowed_copy_cannot_alias_an_acquisition_as_an_after_query() { + reject( + CopyKind::AudioRender, + |c| { + let mut alias = c + .calls + .iter() + .find(|call| call.id == "acquire") + .unwrap() + .clone(); + alias.id = "another-acquisition".into(); + c.calls.push(alias); + c.operations[0].after.push(Step::Call { + call: "another-acquisition".into(), + }); + }, + "Acquisition evidence", + ); +} + +#[test] +fn borrowed_copy_cleanup_must_close_its_reviewed_acquisition() { + reject( + CopyKind::MediaBuffer, + |c| { + let Cleanup::Call { call: id, .. } = &c.operations[0].cleanup else { + panic!() + }; + let unlock = c.calls.iter_mut().find(|call| call.id == *id).unwrap(); + unlock.evidence = "IMFMediaBuffer.SetCurrentLength".into(); + unlock.bindings = vec![Binding::InU32 { + value: U32Source::Constant(0), + }]; + for operation in &mut c.operations { + let Cleanup::Call { abort, .. } = &mut operation.cleanup else { + panic!() + }; + *abort = vec![U32Source::Constant(0)]; + } + }, + "Cleanup does not close the reviewed acquisition", + ); +} + +#[test] +fn borrowed_copy_native_units_are_positional_on_all_call_paths() { + for id in ["release", "release-silent"] { + reject( + CopyKind::AudioRender, + |c| { + c.calls + .iter_mut() + .find(|call| call.id == id) + .unwrap() + .bindings + .swap(0, 1); + }, + "Wrong output/reference type for native ABI cell", + ); + } + reject( + CopyKind::AudioCapture, + |c| { + c.calls + .iter_mut() + .find(|call| call.id == "acquire") + .unwrap() + .bindings + .swap(1, 2); + }, + "Wrong output/reference type for native ABI cell", + ); + reject( + CopyKind::AudioRender, + |c| { + let Cleanup::Call { abort, .. } = &mut c.operations[0].cleanup else { + panic!() + }; + abort[1] = U32Source::Frames(FrameCountRef("capacity".into())); + }, + "Wrong output/reference type for native abort ABI cell", + ); +} diff --git a/crates/dynwinrt-com-contracts/src/validate.rs b/crates/dynwinrt-com-contracts/src/validate.rs new file mode 100644 index 00000000..bf981f58 --- /dev/null +++ b/crates/dynwinrt-com-contracts/src/validate.rs @@ -0,0 +1,920 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +use std::collections::{HashMap, HashSet}; + +type Check = Result; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Kind { + U32(Unit), + Timestamp, + Guid, + Bytes, + Owner(String), + Rect, + Layout, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Before, + Acquire, + After, + Commit, + Cleanup, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Producer { + call: String, + target: Target, + phase: Phase, +} + +#[derive(Clone)] +struct Value { + kind: Kind, + producer: Option, +} + +#[derive(Clone)] +enum ExtentProof { + Frames { + frames: FrameCountRef, + from_input: bool, + }, + Linear { + current: ByteCountRef, + length: ByteCountRef, + producer: Producer, + }, + Rows { + width: PixelCountRef, + height: PixelCountRef, + producer: Producer, + }, +} + +struct Validator<'a> { + registry: &'a Registry, + contract: &'a BorrowedCopyContract, + operation: &'a Operation, + values: HashMap, + extents: HashMap, + called: HashSet, + bounded_rects: HashSet, +} + +fn require(condition: bool, reason: &str) -> Check { + if condition { + Ok(()) + } else { + Err(reason.into()) + } +} + +fn guid(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(i, ch)| { + if [8, 13, 18, 23].contains(&i) { + ch == b'-' + } else { + ch.is_ascii_hexdigit() + } + }) +} + +impl Registry { + /// Checks the closed typed graph, not permission to execute an untrusted graph. + pub fn validate(&self, contract: &BorrowedCopyContract) -> Check { + require( + contract.version == DESCRIPTOR_VERSION + && contract.metadata_sha256 == METADATA_SHA256 + && contract.exposure == "owned-copy-only", + REGENERATE, + )?; + let unique = |names: Vec| { + let count = names.len(); + names.into_iter().collect::>().len() == count + }; + require( + unique( + self.interfaces + .iter() + .map(InterfaceRecord::identity) + .collect(), + ), + "Duplicate registry interface identity", + )?; + require( + unique(self.evidence.iter().map(|e| e.id.clone()).collect()), + "Duplicate registry evidence", + )?; + require( + unique(contract.calls.iter().map(|c| c.id.clone()).collect()), + "Duplicate call binding", + )?; + require( + !contract.calls.is_empty() + && contract.calls.len() <= 32 + && !contract.operations.is_empty() + && contract.operations.len() <= 6, + "Unsupported recipe size", + )?; + let receiver = self.interface(&contract.receiver)?; + require(guid(&receiver.iid), "Invalid receiver IID")?; + for dependency in &contract.dependencies { + self.interface(dependency)?; + } + require( + (contract.owner == BorrowOwner::AudioServiceOrigin) == contract.audio_origin.is_some(), + "Audio owner/layout capability mismatch", + )?; + if let Some(origin) = &contract.audio_origin { + require( + self.interface(&origin.interface)?.context + && contract.dependencies.contains(&origin.interface), + "Audio origin is not a reviewed context dependency", + )?; + require( + origin.role != AudioRole::Render || origin.reject_exclusive_event, + "Full/zero render cleanup requires exclusive-event rejection", + )?; + } + require( + contract.acquired_hresult == 0 && contract.empty_hresult.is_none_or(|hr| hr > 0), + "Unsupported acquisition HRESULT conditions", + )?; + let mut operations = HashSet::new(); + let mut used = HashSet::new(); + for operation in &contract.operations { + require( + operations.insert(operation.api.name()), + "Duplicate public operation", + )?; + let mut validator = Validator { + registry: self, + contract, + operation, + values: HashMap::new(), + extents: HashMap::new(), + called: HashSet::new(), + bounded_rects: HashSet::new(), + }; + validator.validate()?; + used.extend(validator.called); + } + require( + used.len() == contract.calls.len(), + "Unreachable native call in recipe", + ) + } +} + +impl Validator<'_> { + fn define(&mut self, name: &str, kind: Kind, producer: Option) -> Check { + require( + !name.is_empty() && name.len() <= 96, + "Invalid value binding name", + )?; + require( + !self.values.contains_key(name) && !self.extents.contains_key(name), + "Duplicate value/output binding", + )?; + self.values.insert(name.into(), Value { kind, producer }); + Ok(()) + } + + fn value(&self, name: &str, kind: &Kind) -> Check<&Value> { + let value = self + .values + .get(name) + .ok_or_else(|| format!("Dangling, forward or uninitialized reference {name}"))?; + require( + &value.kind == kind, + &format!("Wrong output/reference type for {name}"), + )?; + Ok(value) + } + + fn native(&self, name: &str, kind: &Kind) -> Check<&Producer> { + self.value(name, kind)? + .producer + .as_ref() + .ok_or_else(|| format!("Native extent evidence required for {name}")) + } + + fn source(&self, source: &U32Source) -> Check { + let (name, unit) = match source { + U32Source::Constant(_) | U32Source::SilentFlag(_) => return Ok(()), + U32Source::Bytes(r) => (&r.0, Unit::Bytes), + U32Source::Frames(r) => (&r.0, Unit::Frames), + U32Source::Flags(r) => (&r.0, Unit::Flags), + U32Source::Pixels(r) => (&r.0, Unit::Pixels), + }; + self.value(name, &Kind::U32(unit)).map(|_| ()) + } + + fn call(&self, id: &str) -> Check<&CallContract> { + self.contract + .calls + .iter() + .find(|call| call.id == id) + .ok_or_else(|| format!("Unknown native call {id}")) + } + + fn target(&self, target: &Target) -> Check<&InterfaceRecord> { + let identity = match target { + Target::Receiver => &self.contract.receiver, + Target::AudioOrigin => { + &self + .contract + .audio_origin + .as_ref() + .ok_or("Missing audio-origin capability")? + .interface + } + Target::Acquired(owner) => { + let value = self + .values + .get(&owner.0) + .ok_or("Unavailable acquired owner")?; + let Kind::Owner(identity) = &value.kind else { + return Err("Acquired target is not an owned-interface output".into()); + }; + require( + value + .producer + .as_ref() + .is_some_and(|p| p.phase == Phase::Acquire), + "Owner did not originate at acquisition", + )?; + identity + } + }; + self.registry.interface(identity) + } + + fn abi(&self, call: &CallContract) -> Check<&[AbiCell]> { + let abi = self + .registry + .evidence(&call.evidence)? + .abi + .as_deref() + .ok_or("Evidence has no completed copy ABI")?; + require( + abi.len() == call.bindings.len() + && abi + .iter() + .zip(&call.bindings) + .all(|(cell, binding)| cell.storage() == binding.storage()), + "Native argument/output storage does not match registry ABI cells", + )?; + for (cell, binding) in abi.iter().zip(&call.bindings) { + let matches = match cell { + AbiCell::InU32(unit) => { + matches!(binding, Binding::InU32 { value } if value.unit().is_none_or(|source| source == *unit)) + } + AbiCell::OutU32(unit) => { + matches!(binding, Binding::OutU32 { unit: output, .. } if unit == output) + } + AbiCell::InRect + | AbiCell::OutU64 + | AbiCell::OutGuid + | AbiCell::BorrowedBytes + | AbiCell::OwnedInterface => true, + }; + require(matches, "Wrong output/reference type for native ABI cell")?; + } + Ok(abi) + } + + fn native_call(&mut self, id: &str, phase: Phase) -> Check { + require( + self.called.insert(id.into()), + "Native call repeated across lifecycle phases", + )?; + let call = self.call(id)?.clone(); + let evidence = self.registry.evidence(&call.evidence)?; + require( + (phase == Phase::Acquire) == evidence.acquisition_cleanup.is_some(), + "Acquisition evidence must be used in its acquisition phase", + )?; + if matches!(phase, Phase::Before | Phase::After) { + let mut lifecycle = vec![self.operation.acquire.as_str()]; + lifecycle.extend(self.operation.commit.iter().map(String::as_str)); + if let Cleanup::Call { call, .. } = &self.operation.cleanup { + lifecycle.push(call); + } + for id in lifecycle { + let reserved = self.registry.evidence(&self.call(id)?.evidence)?; + require( + evidence.iid != reserved.iid || evidence.slot != reserved.slot, + "A lifecycle method cannot be reused as a query under another binding", + )?; + } + } + require( + guid(&evidence.iid) + && evidence.slot >= 3 + && evidence.slot < 256 + && evidence.fingerprint.len() == 64 + && evidence.fingerprint.bytes().all(|c| c.is_ascii_hexdigit()) + && !evidence.citation.is_empty(), + "Incomplete native registry evidence", + )?; + let target = self.target(&call.target)?; + require( + target.iid == evidence.iid || target.base_iids.contains(&evidence.iid), + "Native call IID is incompatible with its owner/receiver", + )?; + self.abi(&call)?; + // Resolve every input against the old environment. An earlier output + // argument in this same native call is not an initialized input source. + for binding in &call.bindings { + match binding { + Binding::InU32 { value } => { + self.source(value)?; + if let U32Source::SilentFlag(flag) = value { + require( + phase == Phase::Cleanup + && *flag != 0 + && matches!(self.operation.transfer, Transfer::NoPayload { .. }), + "Silent flags are eligible only for no-payload normal finalization", + )?; + } + } + Binding::InRect { value } => { + self.value(&value.0, &Kind::Rect)?; + require( + phase == Phase::Acquire && self.bounded_rects.contains(&value.0), + "Rectangle acquisition lacks prior native bounds", + )?; + } + _ => {} + } + } + let outputs = call + .bindings + .iter() + .filter(|b| b.output_name().is_some()) + .count(); + require( + match phase { + Phase::Before | Phase::After => outputs != 0, + Phase::Acquire => outputs != 0 && call.target == Target::Receiver, + Phase::Commit | Phase::Cleanup => { + outputs == 0 + && call + .bindings + .iter() + .all(|b| matches!(b, Binding::InU32 { .. })) + } + }, + "Native call is incompatible with its lifecycle phase", + )?; + for binding in &call.bindings { + let kind = match binding { + Binding::InU32 { .. } | Binding::InRect { .. } => continue, + Binding::OutU32 { unit, .. } => Kind::U32(*unit), + Binding::OutU64 { .. } => Kind::Timestamp, + Binding::OutGuid { .. } => Kind::Guid, + Binding::BorrowedBytes { .. } => { + require( + phase == Phase::Acquire || phase == Phase::After, + "Borrowed bytes have no active acquisition", + )?; + match &self.operation.cleanup { + Cleanup::Call { .. } => require( + call.target == Target::Receiver, + "Borrowed bytes are not covered by paired receiver cleanup", + )?, + Cleanup::ReleaseOwner { owner } => require( + call.target == Target::Acquired(owner.clone()) && phase == Phase::After, + "Borrowed bytes outlive or do not belong to the acquired owner", + )?, + } + Kind::Bytes + } + Binding::OwnedInterface { interface, name } => { + require( + phase == Phase::Acquire + && self.operation.cleanup + == (Cleanup::ReleaseOwner { + owner: OwnerRef(name.clone()), + }) + && self.contract.dependencies.contains(interface), + "Owned output is not the unique acquired cleanup owner", + )?; + self.registry.interface(interface)?; + Kind::Owner(interface.clone()) + } + }; + self.define( + binding.output_name().unwrap(), + kind, + Some(Producer { + call: id.into(), + target: call.target.clone(), + phase, + }), + )?; + } + Ok(()) + } + + fn extent(&mut self, name: &ExtentRef, proof: ExtentProof) -> Check { + require( + !self.values.contains_key(&name.0) && !self.extents.contains_key(&name.0), + "Duplicate extent binding", + )?; + self.extents.insert(name.0.clone(), proof); + Ok(()) + } + + fn steps(&mut self, steps: &[Step], phase: Phase) -> Check { + for step in steps { + match step { + Step::Call { call } => self.native_call(call, phase)?, + Step::InputFrames { + frames, + layout, + source, + } => { + require( + phase == Phase::Before, + "Input layout must be proven before acquisition", + )?; + self.value(&layout.0, &Kind::Layout)?; + require( + matches!( + (source, self.operation.arguments), + (FrameInput::Bytes, InputKind::Bytes) + | (FrameInput::Frames, InputKind::Frames) + ), + "Frame input source does not match operation input", + )?; + self.define(&frames.0, Kind::U32(Unit::Frames), None)?; + } + Step::ReturnIfZero { frames } => { + require( + phase == Phase::Before && self.operation.result == ResultMapping::Void, + "Early return cannot skip acquired cleanup or result producers", + )?; + require( + self.value(&frames.0, &Kind::U32(Unit::Frames))? + .producer + .is_none(), + "Zero-request shortcut requires input frames", + )?; + } + Step::FrameExtent { + extent, + frames, + capacity, + layout, + nonzero, + } => { + self.value(&layout.0, &Kind::Layout)?; + let from_input = self + .value(&frames.0, &Kind::U32(Unit::Frames))? + .producer + .is_none(); + let capacity_source = self.native(&capacity.0, &Kind::U32(Unit::Frames))?; + require( + capacity_source.target == Target::AudioOrigin + && capacity_source.phase == Phase::Before + && *nonzero, + "Frame bound requires native owner capacity and a nonzero full packet", + )?; + if !from_input { + require( + self.native(&frames.0, &Kind::U32(Unit::Frames))?.phase + == Phase::Acquire, + "Packet frames must originate in acquisition", + )?; + } + self.extent( + extent, + ExtentProof::Frames { + frames: frames.clone(), + from_input, + }, + )?; + } + Step::NativeExtent { + extent, + current, + capacity, + length, + } => { + require( + phase == Phase::After, + "Native byte bounds require acquisition", + )?; + let current_source = self.native(¤t.0, &Kind::U32(Unit::Bytes))?.clone(); + require( + current_source == *self.native(&capacity.0, &Kind::U32(Unit::Bytes))? + && current_source.phase == Phase::Acquire, + "Current/capacity must be initialized outputs of the same acquisition", + )?; + self.value(&length.0, &Kind::U32(Unit::Bytes))?; + self.extent( + extent, + ExtentProof::Linear { + current: current.clone(), + length: length.clone(), + producer: current_source, + }, + )?; + } + Step::RectBounds { + rect, + width, + height, + } => { + require( + phase == Phase::Before, + "Rectangle bounds must precede acquisition", + )?; + self.value(&rect.0, &Kind::Rect)?; + let w = self.native(&width.0, &Kind::U32(Unit::Pixels))?; + require( + w.target == Target::Receiver + && w.phase == Phase::Before + && w == self.native(&height.0, &Kind::U32(Unit::Pixels))?, + "Rectangle bound must use native receiver dimensions", + )?; + self.bounded_rects.insert(rect.0.clone()); + } + Step::RowExtent { + extent, + rect, + width, + height, + stride, + count, + format, + format_guid, + pixel_bytes, + } => { + require( + phase == Phase::After + && self.bounded_rects.contains(&rect.0) + && *pixel_bytes > 0 + && *pixel_bytes <= 16 + && guid(format_guid), + "Unsupported row-layout or rectangle proof", + )?; + let source = self.native(&count.0, &Kind::U32(Unit::Bytes))?.clone(); + require( + matches!(source.target, Target::Acquired(_)) + && source.phase == Phase::After, + "Row count requires a live acquired owner", + )?; + for (name, kind) in [ + (&width.0, Kind::U32(Unit::Pixels)), + (&height.0, Kind::U32(Unit::Pixels)), + (&stride.0, Kind::U32(Unit::Stride)), + (&format.0, Kind::Guid), + ] { + let p = self.native(name, &kind)?; + require( + p.target == source.target && p.phase == Phase::After, + "Row layout sources have different owner lifetimes", + )?; + } + self.extent( + extent, + ExtentProof::Rows { + width: width.clone(), + height: height.clone(), + producer: source, + }, + )?; + } + } + } + Ok(()) + } + + fn validate(&mut self) -> Check { + let op = self.operation; + require( + op.before.len() + op.after.len() <= 24, + "Unsupported recipe length", + )?; + match op.arguments { + InputKind::Bytes => self.define("input.bytes", Kind::U32(Unit::Bytes), None)?, + InputKind::Frames => self.define("input.frames", Kind::U32(Unit::Frames), None)?, + InputKind::Rectangle => self.define("input.rect", Kind::Rect, None)?, + InputKind::None => {} + } + if let Some(origin) = &self.contract.audio_origin { + self.define(&origin.layout.0, Kind::Layout, None)?; + } + self.steps(&op.before, Phase::Before)?; + let acquisition = self.registry.evidence(&self.call(&op.acquire)?.evidence)?; + // Abort must be constructible before native acquisition, even if + // acquisition's pointer/count outputs turn out invalid or are unreadable. + match &op.cleanup { + Cleanup::Call { call, abort } => { + let finalize = self.call(call)?; + require( + matches!( + &acquisition.acquisition_cleanup, + Some(AcquisitionCleanup::Call { evidence }) if evidence == &finalize.evidence + ), + "Cleanup does not close the reviewed acquisition", + )?; + self.target(&finalize.target)?; + require( + finalize.target == Target::Receiver + && finalize.bindings.len() == abort.len() + && finalize + .bindings + .iter() + .all(|b| matches!(b, Binding::InU32 { .. })) + && self.contract.owner != BorrowOwner::AcquiredInterface, + "Invalid paired finalization target/storage/owner", + )?; + for (arg, cell) in abort.iter().zip(self.abi(finalize)?) { + require( + !matches!(arg, U32Source::SilentFlag(_)), + "Abort cannot commit a silent payload", + )?; + self.source(arg)?; + require( + matches!(cell, AbiCell::InU32(unit) if arg.unit().is_none_or(|source| source == *unit)), + "Wrong output/reference type for native abort ABI cell", + )?; + } + } + Cleanup::ReleaseOwner { .. } => require( + acquisition.acquisition_cleanup == Some(AcquisitionCleanup::ReleaseOwner) + && self.contract.owner == BorrowOwner::AcquiredInterface + && self.contract.empty_hresult.is_none(), + "Owned acquisition cannot use a paired or empty-packet lifecycle", + )?, + } + self.native_call(&op.acquire, Phase::Acquire)?; + if let Cleanup::ReleaseOwner { owner } = &op.cleanup { + self.target(&Target::Acquired(owner.clone()))?; + } + self.steps(&op.after, Phase::After)?; + require( + self.extents.len() == 1, + "Exactly one proven copy extent is required", + )?; + let (extent, pointer, silent, write) = match &op.transfer { + Transfer::Read { + extent, + pointer, + silent, + } => (extent, Some(pointer), silent.as_ref(), false), + Transfer::Write { extent, pointer } => (extent, Some(pointer), None, true), + Transfer::NoPayload { extent } => (extent, None, None, true), + }; + require( + if write { + self.contract.access != MemoryAccess::Read + } else { + self.contract.access != MemoryAccess::Write + }, + "Copy violates native access policy", + )?; + let proof = self + .extents + .get(&extent.0) + .ok_or("Uninitialized copy extent reference")? + .clone(); + let pointer_source = pointer + .map(|p| self.native(&p.0, &Kind::Bytes).cloned()) + .transpose()?; + match &proof { + ExtentProof::Linear { + current, + length, + producer, + } => { + require( + pointer_source.as_ref() == Some(producer), + "Pointer and byte bound have different producers", + )?; + require( + if write { + length.0 == "input.bytes" && op.arguments == InputKind::Bytes + } else { + length == current + }, + "Copy length is not native current length or staged input bytes", + )?; + require( + silent.is_none(), + "Linear byte copies cannot skip pointer validation", + )?; + } + ExtentProof::Frames { frames, from_input } => { + require( + *from_input == write, + "Frame transfer direction/source mismatch", + )?; + require( + self.contract.audio_origin.as_ref().is_some_and(|origin| { + origin.role + == if write { + AudioRole::Render + } else { + AudioRole::Capture + } + }), + "Frame access requires the corresponding observed audio service role", + )?; + if write { + if let Some(pointer) = &pointer_source { + require( + pointer.phase == Phase::Acquire && pointer.call == op.acquire, + "Frame writes require the pointer returned for the acquired request", + )?; + } + require( + self.call(&op.acquire)? + .bindings + .iter() + .filter(|b| { + matches!(b, + Binding::InU32 { value: U32Source::Frames(r) } if r == frames) + }) + .count() + == 1, + "Acquisition must request the exact proven input frames", + )?; + } else { + require( + pointer_source.as_ref() + == Some(self.native(&frames.0, &Kind::U32(Unit::Frames))?), + "Packet pointer and frames have different acquisition producers", + )?; + } + let Cleanup::Call { call, abort } = &op.cleanup else { + return Err("Frame copies require full/zero paired cleanup".into()); + }; + let finalize = self.call(call)?; + let mut full = 0; + let mut silent = 0; + for ((binding, abort), cell) in + finalize.bindings.iter().zip(abort).zip(self.abi(finalize)?) + { + if matches!(cell, AbiCell::InU32(Unit::Frames)) { + let Binding::InU32 { + value: U32Source::Frames(r), + } = binding + else { + return Err("Missing full/zero frame finalization dependency".into()); + }; + require( + r == frames && abort == &U32Source::Constant(0), + "Frame finalization must use full proven frames or zero on abort", + )?; + full += 1; + } + if let Binding::InU32 { + value: U32Source::SilentFlag(flag), + } = binding + { + require( + *flag != 0 && abort == &U32Source::Constant(0), + "Silence commit needs its reviewed flag and zero flags on abort", + )?; + silent += 1; + } + } + require(full == 1, "Missing full/zero frame finalization dependency")?; + require( + silent == usize::from(matches!(op.transfer, Transfer::NoPayload { .. })), + "No-payload transfer requires exactly one typed silent-flag finalization binding", + )?; + } + ExtentProof::Rows { producer, .. } => { + require( + !write + && silent.is_none() + && pointer_source.as_ref() == Some(producer) + && self.contract.sta_only, + "Row copy access, owner, count or apartment mismatch", + )?; + } + } + if let Some(silent) = silent { + require(silent.mask != 0, "Empty silent-packet mask")?; + self.native(&silent.flags.0, &Kind::U32(Unit::Flags))?; + } + if write && matches!(proof, ExtentProof::Linear { .. }) { + require( + op.commit.len() == 1, + "Byte replacement requires its native length commit", + )?; + let commit = self.call(&op.commit[0])?; + require( + commit.target == Target::Receiver + && commit.bindings.iter().any(|b| { + matches!(b, + Binding::InU32 { value: U32Source::Bytes(r) } if r.0 == "input.bytes") + }), + "Native length commit must consume the bounded staged input length", + )?; + } else { + require( + op.commit.is_empty(), + "Unsupported commit after this transfer", + )?; + } + for call in &op.commit { + self.native_call(call, Phase::Commit)?; + } + if let Cleanup::Call { call, abort } = &op.cleanup { + if !matches!(proof, ExtentProof::Frames { .. }) { + require( + self.call(call)?.bindings.iter().zip(abort).all( + |(arg, abort)| matches!(arg, Binding::InU32 { value } if value == abort), + ), + "Non-frame cleanup must have identical normal/abort arguments", + )?; + } + self.native_call(call, Phase::Cleanup)?; + } + match &op.result { + ResultMapping::Void => require(write, "Read result cannot discard required bytes")?, + ResultMapping::Bytes => { + require(!write && silent.is_none(), "Invalid owned-byte result")? + } + ResultMapping::Packet { + frames, + flags, + device, + qpc, + timestamp_error_mask, + } => { + require( + !write + && matches!(&proof, ExtentProof::Frames { frames: f, .. } if f == frames) + && silent.is_some_and(|s| s.flags == *flags) + && *timestamp_error_mask != 0, + "Packet result does not match its frame/flag transfer", + )?; + for (name, kind) in [ + (&flags.0, Kind::U32(Unit::Flags)), + (&device.0, Kind::Timestamp), + (&qpc.0, Kind::Timestamp), + ] { + require( + Some(self.native(name, &kind)?) == pointer_source.as_ref(), + "Packet result sources do not share the acquisition", + )?; + } + } + ResultMapping::Bitmap { width, height } => require( + matches!(&proof, ExtentProof::Rows { width: w, height: h, .. } if width == w && height == h), + "Bitmap result does not match bounded native rows", + )?, + } + require( + self.contract.empty_hresult.is_none() + || matches!(op.result, ResultMapping::Packet { .. }), + "Empty acquisition needs a nullable packet result", + )?; + let shape = match op.api { + OperationId::WriteFramesCopy => { + op.arguments == InputKind::Bytes + && matches!(proof, ExtentProof::Frames { .. }) + && matches!(op.transfer, Transfer::Write { .. }) + } + OperationId::WriteSilence => { + op.arguments == InputKind::Frames + && matches!(proof, ExtentProof::Frames { .. }) + && matches!(op.transfer, Transfer::NoPayload { .. }) + } + OperationId::ReadPacketCopy => { + op.arguments == InputKind::None && matches!(op.result, ResultMapping::Packet { .. }) + } + OperationId::ReadLockedBgra8Copy => { + op.arguments == InputKind::Rectangle + && matches!(op.result, ResultMapping::Bitmap { .. }) + } + OperationId::ReadCopy => { + op.arguments == InputKind::None && op.result == ResultMapping::Bytes + } + OperationId::ReplaceCopy => { + op.arguments == InputKind::Bytes + && matches!(proof, ExtentProof::Linear { .. }) + && matches!(op.transfer, Transfer::Write { .. }) + } + }; + require( + shape, + "Operation input/result shape does not match its public API", + ) + } +} diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index 5b92adc4..ad531a8c 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -11,6 +11,7 @@ authors = ["Microsoft"] test-hooks = [] [dependencies] +dynwinrt-com-contracts = { path = "../dynwinrt-com-contracts", version = "0.1.0" } libffi = "5.1.0" libffi-sys = "4.1.0" paste = "1" diff --git a/crates/dynwinrt/src/com_borrowed.rs b/crates/dynwinrt/src/com_borrowed.rs index 5ba05f77..359a067e 100644 --- a/crates/dynwinrt/src/com_borrowed.rs +++ b/crates/dynwinrt/src/com_borrowed.rs @@ -21,6 +21,16 @@ use windows_core::{GUID, HRESULT, IUnknown, Interface as _}; use super::{AudioFormatValue, InterfaceBase, MethodHandle, MethodSignature, Type, Value}; use crate::{MetadataTable, WinRTValue, result}; +use contracts::AudioRole; +pub use dynwinrt_com_contracts::{ + self as contracts, BorrowOwner, BorrowedCopyContract, CallContract, CopyKind, MemoryAccess, + Storage, +}; + +#[path = "com_borrowed_plan.rs"] +mod plan; +pub use plan::BorrowedCopyPlan; + #[cfg(any(test, feature = "test-hooks"))] #[path = "com_borrowed_test_support.rs"] pub mod testing; @@ -36,9 +46,13 @@ pub const AUDIO_CAPTURE: GUID = GUID::from_u128(0xc8adbd64_e71e_48a0_a4de_185c39 pub const WIC_BITMAP: GUID = GUID::from_u128(0x00000121_a8f2_4877_ba0a_fd2b6645fb94); pub const WIC_LOCK: GUID = GUID::from_u128(0x00000123_a8f2_4877_ba0a_fd2b6645fb94); pub const MF_BUFFER: GUID = GUID::from_u128(0x045fa593_8799_42b8_bc8d_8968c6453507); +#[cfg(any(test, feature = "test-hooks"))] const BGRA8: GUID = GUID::from_u128(0x6fddc324_4e03_4bfe_b185_3d77768dc90f); +#[cfg(test)] const BUFFER_EMPTY: i32 = 0x08890001; +#[cfg(test)] const SILENT: u32 = 2; +#[cfg(test)] const TIMESTAMP_ERROR: u32 = 4; const EVENT_CALLBACK: u32 = 0x00040000; const MAX_COPY_BYTES: usize = 64 * 1024 * 1024; @@ -233,9 +247,12 @@ impl Identity { Rc::ptr_eq(&self.inner, &other.inner) } - fn audio_owner(&self, service_iid: GUID) -> result::Result { + fn audio_owner(&self, service: AudioRole) -> result::Result { self.ensure_thread()?; - let role = if service_iid == AUDIO_RENDER { 1 } else { 2 }; + let role = match service { + AudioRole::Render => 1, + AudioRole::Capture => 2, + }; if self.inner.services.get() & role == 0 { return Err(error( "Audio copy requires an observed successful GetService for this interface", @@ -440,620 +457,6 @@ impl Drop for OwnedInterfaceCell { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CopyKind { - AudioRender, - AudioCapture, - BitmapBgra8, - MediaBuffer, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Storage { - InU32, - InRect, - OutU32, - OutU64, - OutGuid, - BorrowedBytes, - OwnedInterface, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CallContract { - pub iid: GUID, - pub slot: usize, - pub storage: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Extent { - InitializedFrames, - CapturePacketFrames, - NativeBgra8Rows, - NativeCurrentAndMax, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Finalization { - RenderFullOrZero, - CaptureFullOrZero, - ReleaseLockReference, - Unlock, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MemoryAccess { - Read, - Write, - ReadWrite, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BorrowOwner { - Receiver, - AudioServiceOrigin, - AcquiredInterface, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BorrowedCopyContract { - pub kind: CopyKind, - pub receiver: GUID, - pub acquire: CallContract, - pub queries: Vec, - pub finalize: Option, - pub extent: Extent, - pub finalization: Finalization, - pub sta_only: bool, - pub audio_origin_required: bool, - pub access: MemoryAccess, - pub owner: BorrowOwner, - pub acquired_hresult: i32, - pub empty_hresult: Option, -} - -impl BorrowedCopyContract { - pub fn expected(kind: CopyKind) -> Self { - use Storage::*; - let call = |iid, slot, storage: &[Storage]| CallContract { - iid, - slot, - storage: storage.to_vec(), - }; - match kind { - CopyKind::AudioRender => Self { - kind, - receiver: AUDIO_RENDER, - acquire: call(AUDIO_RENDER, 3, &[InU32, BorrowedBytes]), - queries: vec![call(AUDIO_CLIENT, 4, &[OutU32])], - finalize: Some(call(AUDIO_RENDER, 4, &[InU32, InU32])), - extent: Extent::InitializedFrames, - finalization: Finalization::RenderFullOrZero, - sta_only: false, - audio_origin_required: true, - access: MemoryAccess::Write, - owner: BorrowOwner::AudioServiceOrigin, - acquired_hresult: 0, - empty_hresult: None, - }, - CopyKind::AudioCapture => Self { - kind, - receiver: AUDIO_CAPTURE, - acquire: call( - AUDIO_CAPTURE, - 3, - &[BorrowedBytes, OutU32, OutU32, OutU64, OutU64], - ), - queries: vec![call(AUDIO_CLIENT, 4, &[OutU32])], - finalize: Some(call(AUDIO_CAPTURE, 4, &[InU32])), - extent: Extent::CapturePacketFrames, - finalization: Finalization::CaptureFullOrZero, - sta_only: false, - audio_origin_required: true, - access: MemoryAccess::Read, - owner: BorrowOwner::AudioServiceOrigin, - acquired_hresult: 0, - empty_hresult: Some(BUFFER_EMPTY), - }, - CopyKind::BitmapBgra8 => Self { - kind, - receiver: WIC_BITMAP, - acquire: call(WIC_BITMAP, 8, &[InRect, InU32, OwnedInterface]), - queries: vec![ - call(WIC_BITMAP, 3, &[OutU32, OutU32]), - call(WIC_LOCK, 3, &[OutU32, OutU32]), - call(WIC_LOCK, 4, &[OutU32]), - call(WIC_LOCK, 6, &[OutGuid]), - call(WIC_LOCK, 5, &[OutU32, BorrowedBytes]), - ], - finalize: None, - extent: Extent::NativeBgra8Rows, - finalization: Finalization::ReleaseLockReference, - sta_only: true, - audio_origin_required: false, - access: MemoryAccess::Read, - owner: BorrowOwner::AcquiredInterface, - acquired_hresult: 0, - empty_hresult: None, - }, - CopyKind::MediaBuffer => Self { - kind, - receiver: MF_BUFFER, - acquire: call(MF_BUFFER, 3, &[BorrowedBytes, OutU32, OutU32]), - queries: vec![call(MF_BUFFER, 6, &[InU32])], - finalize: Some(call(MF_BUFFER, 4, &[])), - extent: Extent::NativeCurrentAndMax, - finalization: Finalization::Unlock, - sta_only: false, - audio_origin_required: false, - access: MemoryAccess::ReadWrite, - owner: BorrowOwner::Receiver, - acquired_hresult: 0, - empty_hresult: None, - }, - } - } -} - -/// Prepared immutable calls and cleanup recipes. Does not own a native borrow. -pub struct BorrowedCopyPlan { - contract: BorrowedCopyContract, - acquire: MethodHandle, - queries: Vec, - finalize: Option, -} - -fn prepare( - table: &std::sync::Arc, - contract: &CallContract, -) -> result::Result { - // Output cells are deliberately lowered to addresses of private stable storage. - // The executor must not read them until the exact acquisition HRESULT is known. - let mut signature = MethodSignature::new(table).preserve_hresult(); - for storage in &contract.storage { - signature = signature.add_in(match storage { - Storage::InU32 => Type::winrt(table.u32_type()), - Storage::InRect - | Storage::OutU32 - | Storage::OutU64 - | Storage::OutGuid - | Storage::BorrowedBytes - | Storage::OwnedInterface => Type::pointer(), - }); - } - let interface = super::register_interface( - table, - "BorrowedCopyPlan", - contract.iid, - InterfaceBase::IUnknown, - ) - .add_method_at(contract.slot, "completed-copy-call", signature)?; - Ok(interface.method(contract.slot).expect("prepared method")) -} - -impl BorrowedCopyPlan { - pub fn prepare( - table: &std::sync::Arc, - contract: BorrowedCopyContract, - ) -> result::Result { - if contract != BorrowedCopyContract::expected(contract.kind) { - return Err(error( - "Unsupported borrowed-copy descriptor; regenerate bindings", - )); - } - let acquire = prepare(table, &contract.acquire)?; - let queries = contract - .queries - .iter() - .map(|call| prepare(table, call)) - .collect::>()?; - let finalize = contract - .finalize - .as_ref() - .map(|call| prepare(table, call)) - .transpose()?; - Ok(Self { - contract, - acquire, - queries, - finalize, - }) - } - - fn begin( - &self, - context: &Identity, - object: &IUnknown, - ) -> result::Result<(Transaction, IUnknown, Option)> { - context.ensure_idle()?; - if self.contract.sta_only { - let mut apartment = Default::default(); - let mut qualifier = Default::default(); - unsafe { CoGetApartmentType(&mut apartment, &mut qualifier)? }; - if apartment != APTTYPE_STA && apartment != APTTYPE_MAINSTA { - return Err(error( - "WIC borrowed-copy GetDataPointer requires an STA apartment", - )); - } - } - let origin = if self.contract.audio_origin_required { - Some(context.audio_owner(self.contract.receiver)?) - } else { - None - }; - let transaction = - Transaction::enter(context, origin.as_ref().map(|(identity, _)| identity), true)?; - if !context.matches(&Identity::for_object(object)?) { - return Err(error( - "Borrowed-copy context does not belong to this COM identity", - )); - } - let view = query(object, &self.contract.receiver)?; - Ok((transaction, view, origin)) - } - - fn audio_layout(&self, origin: &AudioOwner) -> result::Result { - let layout = { - let stored = origin.0.inner.initialized.borrow(); - stored.as_ref().map(|initialized| { - ( - initialized.block_align, - initialized.share_mode, - initialized.flags, - initialized.format.block_align() as usize, - ) - }) - }; - let (block, share_mode, flags, native_block) = layout - .ok_or_else(|| error("Audio client has no observed successful initialization"))?; - let block = block.ok_or_else(|| { - error("Initialized audio format is not a validated uncompressed frame layout") - })?; - if !(0..=1).contains(&share_mode) { - return Err(error("Unsupported initialized audio share mode")); - } - if self.contract.kind == CopyKind::AudioRender - && share_mode == 1 - && flags & EVENT_CALLBACK != 0 - { - return Err(error( - "Exclusive event-driven render copy is unsupported: zero-frame abort is invalid", - )); - } - // Keep immutable initialized format, not GetMixFormat or a caller blockAlign. - debug_assert_eq!(block, native_block); - Ok(block) - } - - fn audio_capacity(&self, origin: &AudioOwner) -> result::Result { - let mut capacity = 0u32; - exact_success(&self.queries[0], &origin.1, &[cell(&mut capacity)])?; - Ok(capacity) - } - - fn acquired_hresult(&self, transaction: &Transaction, hr: HRESULT) -> result::Result { - if hr.0 == self.contract.acquired_hresult { - Ok(true) - } else if self.contract.empty_hresult == Some(hr.0) { - Ok(false) - } else { - // Unknown success does not prove acquisition or authorize output reads. - transaction.poison(); - Err(error(format!( - "Unexpected acquisition HRESULT 0x{:08X}; context poisoned", - hr.0 as u32 - ))) - } - } - - pub fn write_frames_copy( - &self, - context: &Identity, - object: &IUnknown, - data: &[u8], - ) -> result::Result<()> { - self.write_audio(context, object, Some(data), 0) - } - - pub fn write_silence( - &self, - context: &Identity, - object: &IUnknown, - frames: u32, - ) -> result::Result<()> { - self.write_audio(context, object, None, frames) - } - - fn write_audio( - &self, - context: &Identity, - object: &IUnknown, - data: Option<&[u8]>, - silence_frames: u32, - ) -> result::Result<()> { - if self.contract.kind != CopyKind::AudioRender { - return Err(error( - "writeFramesCopy/writeSilence require a render copy plan", - )); - } - let (mut transaction, view, origin) = self.begin(context, object)?; - let origin = origin.as_ref().expect("audio origin"); - let block = self.audio_layout(origin)?; - let frames = if let Some(data) = data { - checked_extent(data.len())?; - if data.len() % block != 0 { - return Err(error( - "Audio data length must contain whole initialized-format frames", - )); - } - u32::try_from(data.len() / block).map_err(|_| error("Audio frame count overflow"))? - } else { - silence_frames - }; - let bytes = frame_bytes(frames, block)?; - if frames == 0 { - return transaction.complete(Ok(()), &[]); - } - if frames > self.audio_capacity(origin)? { - return Err(error("Audio frame count exceeds native buffer capacity")); - } - let finalizer = Finalizer::Call { - method: self.finalize.as_ref().expect("render finalizer").clone(), - view: view.clone(), - abort: vec![WinRTValue::U32(0), WinRTValue::U32(0)], - }; - let mut pointer = ptr::null_mut::(); - let hr = call( - &self.acquire, - &view, - &[WinRTValue::U32(frames), cell(&mut pointer)], - )?; - self.acquired_hresult(&transaction, hr)?; - transaction.acquired(finalizer); - let copied = if let Some(data) = data { - validate_pointer(pointer, bytes).map(|()| unsafe { - ptr::copy_nonoverlapping(data.as_ptr(), pointer, bytes); - }) - } else { - Ok(()) - }; - transaction.complete( - copied, - &[ - WinRTValue::U32(frames), - WinRTValue::U32(if data.is_none() { SILENT } else { 0 }), - ], - ) - } - - pub fn read_packet_copy( - &self, - context: &Identity, - object: &IUnknown, - ) -> result::Result> { - if self.contract.kind != CopyKind::AudioCapture { - return Err(error("readPacketCopy requires a capture copy plan")); - } - let (mut transaction, view, origin) = self.begin(context, object)?; - let origin = origin.as_ref().expect("audio origin"); - let block = self.audio_layout(origin)?; - let capacity = self.audio_capacity(origin)?; - let finalizer = Finalizer::Call { - method: self.finalize.as_ref().expect("capture finalizer").clone(), - view: view.clone(), - abort: vec![WinRTValue::U32(0)], - }; - let mut pointer = ptr::null_mut::(); - let (mut frames, mut flags, mut device, mut qpc) = (0u32, 0u32, 0u64, 0u64); - let hr = call( - &self.acquire, - &view, - &[ - cell(&mut pointer), - cell(&mut frames), - cell(&mut flags), - cell(&mut device), - cell(&mut qpc), - ], - )?; - if !self.acquired_hresult(&transaction, hr)? { - // No reads of any output cell, and no ReleaseBuffer, on BUFFER_EMPTY. - return transaction.complete(Ok(None), &[]); - } - transaction.acquired(finalizer); - let result = (|| { - if frames == 0 || frames > capacity { - return Err(error( - "Capture packet frames are outside native buffer capacity", - )); - } - let bytes = frame_bytes(frames, block)?; - let data = if flags & SILENT != 0 { - None - } else { - Some(copy_bytes(pointer, bytes)?) - }; - Ok(Some(CapturePacket { - data, - frames, - flags, - device_position: (flags & TIMESTAMP_ERROR == 0).then_some(device), - qpc_position: (flags & TIMESTAMP_ERROR == 0).then_some(qpc), - })) - })(); - transaction.complete(result, &[WinRTValue::U32(frames)]) - } - - pub fn read_copy(&self, context: &Identity, object: &IUnknown) -> result::Result> { - self.media_copy(context, object, None) - } - - pub fn replace_copy( - &self, - context: &Identity, - object: &IUnknown, - data: &[u8], - ) -> result::Result<()> { - checked_extent(data.len())?; - self.media_copy(context, object, Some(data)).map(|_| ()) - } - - fn media_copy( - &self, - context: &Identity, - object: &IUnknown, - data: Option<&[u8]>, - ) -> result::Result> { - if self.contract.kind != CopyKind::MediaBuffer { - return Err(error( - "readCopy/replaceCopy require a linear media-buffer plan", - )); - } - let (mut transaction, view, _) = self.begin(context, object)?; - let finalizer = Finalizer::Call { - method: self.finalize.as_ref().expect("media finalizer").clone(), - view: view.clone(), - abort: vec![], - }; - let mut pointer = ptr::null_mut::(); - let (mut maximum, mut current) = (0u32, 0u32); - let hr = call( - &self.acquire, - &view, - &[cell(&mut pointer), cell(&mut maximum), cell(&mut current)], - )?; - self.acquired_hresult(&transaction, hr)?; - transaction.acquired(finalizer); - let result = (|| { - if current > maximum { - return Err(error("Media buffer current length exceeds native maximum")); - } - if let Some(data) = data { - if data.len() > maximum as usize { - return Err(error("Replacement exceeds native media-buffer capacity")); - } - validate_pointer(pointer, data.len())?; - if !data.is_empty() { - unsafe { ptr::copy_nonoverlapping(data.as_ptr(), pointer, data.len()) }; - } - exact_success( - &self.queries[0], - &view, - &[WinRTValue::U32(data.len() as u32)], - )?; - Ok(vec![]) - } else { - copy_bytes(pointer, current as usize) - } - })(); - transaction.complete(result, &[]) - } - - pub fn read_locked_bgra8_copy( - &self, - context: &Identity, - object: &IUnknown, - rect: [i32; 4], - ) -> result::Result { - if self.contract.kind != CopyKind::BitmapBgra8 { - return Err(error("readLockedBgra8Copy requires a bitmap copy plan")); - } - let [x, y, width, height] = rect; - if x < 0 || y < 0 || width <= 0 || height <= 0 { - return Err(error( - "Bitmap rectangle must have nonnegative origin and positive dimensions", - )); - } - let right = x - .checked_add(width) - .ok_or_else(|| error("Bitmap rectangle overflow"))?; - let bottom = y - .checked_add(height) - .ok_or_else(|| error("Bitmap rectangle overflow"))?; - let (mut transaction, view, _) = self.begin(context, object)?; - let (mut bitmap_width, mut bitmap_height) = (0u32, 0u32); - exact_success( - &self.queries[0], - &view, - &[cell(&mut bitmap_width), cell(&mut bitmap_height)], - )?; - if right as u32 > bitmap_width || bottom as u32 > bitmap_height { - return Err(error("Bitmap rectangle exceeds native dimensions")); - } - let mut lock = OwnedInterfaceCell::default(); - let mut rect = rect; - let hr = call( - &self.acquire, - &view, - &[cell(&mut rect), WinRTValue::U32(1), cell(&mut lock.0)], - )?; - self.acquired_hresult(&transaction, hr)?; - let raw_lock = lock.0; - transaction.acquired(Finalizer::Release(lock)); - let result = (|| { - let lock = unsafe { IUnknown::from_raw_borrowed(&raw_lock) } - .ok_or_else(|| error("Bitmap Lock returned a required null lock"))?; - let (mut actual_width, mut actual_height, mut stride, mut count) = - (0u32, 0u32, 0u32, 0u32); - let mut format = GUID::zeroed(); - let mut pointer = ptr::null_mut::(); - exact_success( - &self.queries[1], - lock, - &[cell(&mut actual_width), cell(&mut actual_height)], - )?; - exact_success(&self.queries[2], lock, &[cell(&mut stride)])?; - exact_success(&self.queries[3], lock, &[cell(&mut format)])?; - if format != BGRA8 { - return Err(error("Bitmap copy supports only native 32bpp BGRA")); - } - if actual_width != width as u32 || actual_height != height as u32 { - return Err(error( - "Bitmap lock dimensions differ from the requested rectangle", - )); - } - exact_success( - &self.queries[4], - lock, - &[cell(&mut count), cell(&mut pointer)], - )?; - let row = (actual_width as usize) - .checked_mul(4) - .ok_or_else(|| error("Bitmap row overflow"))?; - let span = (actual_height as usize - 1) - .checked_mul(stride as usize) - .and_then(|n| n.checked_add(row)) - .ok_or_else(|| error("Bitmap span overflow"))?; - if row > stride as usize || span > count as usize { - return Err(error( - "Bitmap final-row span exceeds native byte count/stride", - )); - } - validate_pointer(pointer, span)?; - let length = row - .checked_mul(actual_height as usize) - .ok_or_else(|| error("Bitmap copy size overflow"))?; - let mut data = allocate(length)?; - for (index, target) in data.chunks_exact_mut(row).enumerate() { - unsafe { - ptr::copy_nonoverlapping( - pointer.add(index * stride as usize), - target.as_mut_ptr(), - row, - ) - }; - } - Ok(BitmapCopy { - data, - width: actual_width, - height: actual_height, - }) - })(); - transaction.complete(result, &[]) - } -} - pub struct CapturePacket { pub data: Option>, pub frames: u32, diff --git a/crates/dynwinrt/src/com_borrowed_plan.rs b/crates/dynwinrt/src/com_borrowed_plan.rs new file mode 100644 index 00000000..d8fb6358 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_plan.rs @@ -0,0 +1,882 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Executes only the typed, admitted copy recipes. No interface-family dispatch. + +use super::*; +use contracts::{ + AudioOrigin, Binding, Cleanup, FrameInput, InputKind, Operation, OperationId, Registry, + ResultMapping, Step, Target, Transfer, U32Source, +}; + +/// Completed immutable MethodHandles and a validated, closed execution recipe. +/// No native borrow or caller-provided extent is retained in this plan. +pub struct BorrowedCopyPlan { + contract: BorrowedCopyContract, + receiver: GUID, + calls: HashMap, +} + +struct PreparedCall { + contract: CallContract, + iid: GUID, + method: MethodHandle, +} + +enum Datum { + U32(u32), + U64(u64), + Guid(GUID), + Bytes(*mut u8), + Owner(*mut c_void), + Rect([i32; 4]), + Layout(usize), +} + +#[derive(Default)] +struct Values { + data: HashMap, + extents: HashMap, +} + +impl Values { + fn get(&self, name: &str) -> result::Result<&Datum> { + self.data + .get(name) + .ok_or_else(|| error("Uninitialized copy-plan value")) + } + fn u32(&self, name: &str) -> result::Result { + match self.get(name)? { + Datum::U32(v) => Ok(*v), + _ => Err(error("Copy-plan u32 type mismatch")), + } + } + fn u64(&self, name: &str) -> result::Result { + match self.get(name)? { + Datum::U64(v) => Ok(*v), + _ => Err(error("Copy-plan timestamp type mismatch")), + } + } + fn layout(&self, name: &str) -> result::Result { + match self.get(name)? { + Datum::Layout(v) => Ok(*v), + _ => Err(error("Missing observed initialized layout")), + } + } + fn rect(&self, name: &str) -> result::Result<[i32; 4]> { + match self.get(name)? { + Datum::Rect(v) => Ok(*v), + _ => Err(error("Copy-plan rectangle type mismatch")), + } + } + fn pointer(&self, name: &str) -> result::Result<*mut u8> { + match self.get(name)? { + Datum::Bytes(v) => Ok(*v), + _ => Err(error("Copy-plan byte pointer type mismatch")), + } + } + fn source(&self, source: &U32Source) -> result::Result { + match source { + U32Source::Constant(v) | U32Source::SilentFlag(v) => Ok(*v), + U32Source::Bytes(r) => self.u32(&r.0), + U32Source::Frames(r) => self.u32(&r.0), + U32Source::Flags(r) => self.u32(&r.0), + U32Source::Pixels(r) => self.u32(&r.0), + } + } +} + +// Native output cells are never values until the exact success condition has +// been classified. Owned outputs alone carry RAII, including native failure. +enum NativeCell { + U32(u32), + U64(u64), + Guid(GUID), + Bytes(*mut u8), + Owner(OwnedInterfaceCell), +} + +impl NativeCell { + fn address(&mut self) -> WinRTValue { + match self { + Self::U32(v) => cell(v), + Self::U64(v) => cell(v), + Self::Guid(v) => cell(v), + Self::Bytes(v) => cell(v), + Self::Owner(v) => cell(&mut v.0), + } + } +} + +struct Outputs(Vec<(String, Option)>); + +impl Outputs { + fn for_call(call: &CallContract) -> Self { + Self( + call.bindings + .iter() + .filter_map(|binding| { + let value = match binding { + Binding::InU32 { .. } | Binding::InRect { .. } => return None, + Binding::OutU32 { .. } => NativeCell::U32(0), + Binding::OutU64 { .. } => NativeCell::U64(0), + Binding::OutGuid { .. } => NativeCell::Guid(GUID::zeroed()), + Binding::BorrowedBytes { .. } => NativeCell::Bytes(ptr::null_mut()), + Binding::OwnedInterface { .. } => { + NativeCell::Owner(OwnedInterfaceCell::default()) + } + }; + Some((binding.output_name().unwrap().into(), Some(value))) + }) + .collect(), + ) + } + + fn address(&mut self, name: &str) -> result::Result { + self.0 + .iter_mut() + .find(|(id, _)| id == name) + .and_then(|(_, value)| value.as_mut()) + .map(NativeCell::address) + .ok_or_else(|| error("Missing native output binding")) + } + + fn take_owner(&mut self, name: &str) -> result::Result { + let value = self + .0 + .iter_mut() + .find(|(id, _)| id == name) + .and_then(|(_, value)| value.take()) + .ok_or_else(|| error("Missing acquired owner binding"))?; + match value { + NativeCell::Owner(owner) => Ok(owner), + _ => Err(error("Acquired cleanup source is not an owned interface")), + } + } + + fn publish(self, values: &mut Values) -> result::Result<()> { + for (name, value) in self.0 { + let value = match value { + None => continue, // The transaction already took its unique owner. + Some(NativeCell::U32(v)) => Datum::U32(v), + Some(NativeCell::U64(v)) => Datum::U64(v), + Some(NativeCell::Guid(v)) => Datum::Guid(v), + Some(NativeCell::Bytes(v)) => Datum::Bytes(v), + Some(NativeCell::Owner(_)) => return Err(error("Unarmed acquired owner")), + }; + values.data.insert(name, value); + } + Ok(()) + } +} + +#[derive(Clone, Copy)] +enum Input<'a> { + None, + Bytes(&'a [u8]), + Frames(u32), + Rect([i32; 4]), +} + +impl Input<'_> { + fn kind(self) -> InputKind { + match self { + Self::None => InputKind::None, + Self::Bytes(_) => InputKind::Bytes, + Self::Frames(_) => InputKind::Frames, + Self::Rect(_) => InputKind::Rectangle, + } + } +} + +struct Run<'a> { + input: Input<'a>, + receiver: IUnknown, + origin: Option, + values: Values, +} + +struct CopyExtent { + length: usize, + span: usize, + row: usize, + stride: usize, + rows: usize, +} + +impl CopyExtent { + fn linear(bytes: usize) -> result::Result { + checked_extent(bytes)?; + Ok(Self { + length: bytes, + span: bytes, + row: bytes, + stride: bytes, + rows: 1, + }) + } + + fn read(&self, pointer: *const u8) -> result::Result> { + if self.rows == 1 { + return copy_bytes(pointer, self.length); + } + validate_pointer(pointer, self.span)?; + let mut data = allocate(self.length)?; + for (index, target) in data.chunks_exact_mut(self.row).enumerate() { + unsafe { + ptr::copy_nonoverlapping( + pointer.add(index * self.stride), + target.as_mut_ptr(), + self.row, + ) + }; + } + Ok(data) + } + + fn write(&self, pointer: *mut u8, data: &[u8]) -> result::Result<()> { + if self.rows != 1 || data.len() != self.length { + return Err(error("Copy input does not match its proven native extent")); + } + validate_pointer(pointer, self.span)?; + if !data.is_empty() { + unsafe { ptr::copy_nonoverlapping(data.as_ptr(), pointer, data.len()) }; + } + Ok(()) + } +} + +enum CopyOutput { + Void, + Bytes(Vec), + Packet(Option), + Bitmap(BitmapCopy), +} + +impl BorrowedCopyPlan { + pub fn prepare( + table: &Arc, + contract: BorrowedCopyContract, + ) -> result::Result { + let registry = contracts::registry(); + registry.admit(&contract).map_err(error)?; + Self::compile(table, contract, registry) + } + + // No test-registry injection is compiled into production or test-hooks builds. + #[cfg(test)] + pub(super) fn prepare_test( + table: &Arc, + contract: BorrowedCopyContract, + registry: &Registry, + ) -> result::Result { + registry.admit(&contract).map_err(error)?; + Self::compile(table, contract, registry) + } + + fn compile( + table: &Arc, + contract: BorrowedCopyContract, + registry: &Registry, + ) -> result::Result { + let receiver = parse_iid(®istry.interface(&contract.receiver).map_err(error)?.iid)?; + let mut calls = HashMap::new(); + for definition in &contract.calls { + let evidence = registry.evidence(&definition.evidence).map_err(error)?; + let iid = parse_iid(&evidence.iid)?; + let mut signature = MethodSignature::new(table).preserve_hresult(); + for binding in &definition.bindings { + signature = signature.add_in(match binding { + Binding::InU32 { .. } => Type::winrt(table.u32_type()), + Binding::InRect { .. } + | Binding::OutU32 { .. } + | Binding::OutU64 { .. } + | Binding::OutGuid { .. } + | Binding::BorrowedBytes { .. } + | Binding::OwnedInterface { .. } => Type::pointer(), + }); + } + let interface = super::super::register_interface( + table, + "BorrowedCopyPlan", + iid, + InterfaceBase::IUnknown, + ) + .add_method_at(evidence.slot, &evidence.method, signature)?; + calls.insert( + definition.id.clone(), + PreparedCall { + contract: definition.clone(), + iid, + method: interface + .method(evidence.slot) + .expect("completed copy method"), + }, + ); + } + Ok(Self { + contract, + receiver, + calls, + }) + } + + fn begin<'a>( + &self, + context: &Identity, + object: &IUnknown, + input: Input<'a>, + ) -> result::Result<(Transaction, Run<'a>)> { + context.ensure_idle()?; + let mut values = Values::default(); + match input { + Input::Bytes(bytes) => { + checked_extent(bytes.len())?; + values + .data + .insert("input.bytes".into(), Datum::U32(bytes.len() as u32)); + } + Input::Frames(frames) => { + values + .data + .insert("input.frames".into(), Datum::U32(frames)); + } + Input::Rect(rect) => { + rectangle_end(rect)?; + values.data.insert("input.rect".into(), Datum::Rect(rect)); + } + Input::None => {} + } + if self.contract.sta_only { + let mut apartment = Default::default(); + let mut qualifier = Default::default(); + unsafe { CoGetApartmentType(&mut apartment, &mut qualifier)? }; + if apartment != APTTYPE_STA && apartment != APTTYPE_MAINSTA { + return Err(error( + "WIC borrowed-copy GetDataPointer requires an STA apartment", + )); + } + } + let origin = self + .contract + .audio_origin + .as_ref() + .map(|policy| context.audio_owner(policy.role)) + .transpose()?; + let transaction = + Transaction::enter(context, origin.as_ref().map(|(identity, _)| identity), true)?; + if !context.matches(&Identity::for_object(object)?) { + return Err(error( + "Borrowed-copy context does not belong to this COM identity", + )); + } + let receiver = query(object, &self.receiver)?; + if let (Some(policy), Some(origin)) = (&self.contract.audio_origin, &origin) { + values.data.insert( + policy.layout.0.clone(), + Datum::Layout(audio_layout(origin, policy)?), + ); + } + Ok(( + transaction, + Run { + input, + receiver, + origin, + values, + }, + )) + } + + fn prepared(&self, id: &str) -> result::Result<&PreparedCall> { + self.calls + .get(id) + .ok_or_else(|| error("Unknown completed copy call")) + } + + fn target(&self, prepared: &PreparedCall, run: &Run<'_>) -> result::Result { + let object = match &prepared.contract.target { + Target::Receiver => &run.receiver, + Target::AudioOrigin => { + &run.origin + .as_ref() + .ok_or_else(|| error("Missing audio origin"))? + .1 + } + Target::Acquired(owner) => { + let Datum::Owner(raw) = run.values.get(&owner.0)? else { + return Err(error("Acquired target is not a live owner")); + }; + unsafe { IUnknown::from_raw_borrowed(raw) } + .ok_or_else(|| error("Acquisition returned a required null owner"))? + } + }; + query(object, &prepared.iid) + } + + fn invoke(&self, id: &str, run: &mut Run<'_>) -> result::Result<(HRESULT, Outputs)> { + let prepared = self.prepared(id)?; + let view = self.target(prepared, run)?; + // Build the complete vector before taking addresses; its allocation is + // stable through the synchronous libffi call, independent of binding order. + let mut outputs = Outputs::for_call(&prepared.contract); + let mut args = Vec::with_capacity(prepared.contract.bindings.len()); + for binding in &prepared.contract.bindings { + args.push(match binding { + Binding::InU32 { value } => WinRTValue::U32(run.values.source(value)?), + Binding::InRect { value } => { + let Some(Datum::Rect(rect)) = run.values.data.get_mut(&value.0) else { + return Err(error("Uninitialized rectangle source")); + }; + cell(rect) + } + _ => outputs.address(binding.output_name().unwrap())?, + }); + } + let hr = call(&prepared.method, &view, &args)?; + Ok((hr, outputs)) + } + + fn exact_call(&self, id: &str, run: &mut Run<'_>) -> result::Result<()> { + let (hr, outputs) = self.invoke(id, run)?; + if hr.0 != 0 { + return Err(error(format!( + "Borrowed-copy call returned unexpected HRESULT 0x{:08X}", + hr.0 as u32 + ))); + } + outputs.publish(&mut run.values) + } + + fn steps(&self, steps: &[Step], run: &mut Run<'_>) -> result::Result { + for step in steps { + match step { + Step::Call { call } => self.exact_call(call, run)?, + Step::InputFrames { + frames, + layout, + source, + } => { + let block = run.values.layout(&layout.0)?; + let count = match (source, run.input) { + (FrameInput::Bytes, Input::Bytes(data)) => { + if data.len() % block != 0 { + return Err(error( + "Audio data length must contain whole initialized-format frames", + )); + } + u32::try_from(data.len() / block) + .map_err(|_| error("Audio frame count overflow"))? + } + (FrameInput::Frames, Input::Frames(frames)) => frames, + _ => return Err(error("Invalid frame input source")), + }; + frame_bytes(count, block)?; + run.values.data.insert(frames.0.clone(), Datum::U32(count)); + } + Step::ReturnIfZero { frames } => { + if run.values.u32(&frames.0)? == 0 { + return Ok(false); + } + } + Step::FrameExtent { + extent, + frames, + capacity, + layout, + nonzero, + } => { + let frames = run.values.u32(&frames.0)?; + if (*nonzero && frames == 0) || frames > run.values.u32(&capacity.0)? { + return Err(error("Audio frame count is outside native buffer capacity")); + } + let bytes = frame_bytes(frames, run.values.layout(&layout.0)?)?; + run.values + .extents + .insert(extent.0.clone(), CopyExtent::linear(bytes)?); + } + Step::NativeExtent { + extent, + current, + capacity, + length, + } => { + let current = run.values.u32(¤t.0)?; + let maximum = run.values.u32(&capacity.0)?; + if current > maximum { + return Err(error("Media buffer current length exceeds native maximum")); + } + let length = run.values.u32(&length.0)?; + if length > maximum { + return Err(error("Replacement exceeds native media-buffer capacity")); + } + run.values + .extents + .insert(extent.0.clone(), CopyExtent::linear(length as usize)?); + } + Step::RectBounds { + rect, + width, + height, + } => { + let (right, bottom) = rectangle_end(run.values.rect(&rect.0)?)?; + if right > run.values.u32(&width.0)? || bottom > run.values.u32(&height.0)? { + return Err(error("Bitmap rectangle exceeds native dimensions")); + } + } + Step::RowExtent { + extent, + rect, + width, + height, + stride, + count, + format, + format_guid, + pixel_bytes, + } => { + let expected = parse_iid(format_guid)?; + if !matches!(run.values.get(&format.0)?, Datum::Guid(value) if *value == expected) + { + return Err(error("Bitmap copy supports only native 32bpp BGRA")); + } + let rect = run.values.rect(&rect.0)?; + let width = run.values.u32(&width.0)?; + let height = run.values.u32(&height.0)?; + if width != rect[2] as u32 || height != rect[3] as u32 { + return Err(error( + "Bitmap lock dimensions differ from the requested rectangle", + )); + } + let stride = run.values.u32(&stride.0)? as usize; + let row = (width as usize) + .checked_mul(*pixel_bytes as usize) + .ok_or_else(|| error("Bitmap row overflow"))?; + let rows = height as usize; + let span = rows + .checked_sub(1) + .and_then(|n| n.checked_mul(stride)) + .and_then(|n| n.checked_add(row)) + .ok_or_else(|| error("Bitmap span overflow"))?; + if row == 0 || row > stride || span > run.values.u32(&count.0)? as usize { + return Err(error( + "Bitmap final-row span exceeds native byte count/stride", + )); + } + checked_extent(span)?; + let length = row + .checked_mul(rows) + .ok_or_else(|| error("Bitmap copy size overflow"))?; + checked_extent(length)?; + run.values.extents.insert( + extent.0.clone(), + CopyExtent { + length, + span, + row, + stride, + rows, + }, + ); + } + } + } + Ok(true) + } + + fn transfer(&self, transfer: &Transfer, run: &Run<'_>) -> result::Result>> { + let extent = match transfer { + Transfer::Read { extent, .. } + | Transfer::Write { extent, .. } + | Transfer::NoPayload { extent } => extent, + }; + let extent = run + .values + .extents + .get(&extent.0) + .ok_or_else(|| error("Uninitialized native extent"))?; + match transfer { + Transfer::Read { + pointer, silent, .. + } => { + if let Some(condition) = silent + && run.values.u32(&condition.flags.0)? & condition.mask != 0 + { + return Ok(None); + } + extent.read(run.values.pointer(&pointer.0)?).map(Some) + } + Transfer::Write { pointer, .. } => { + let Input::Bytes(data) = run.input else { + return Err(error("Missing staged input bytes")); + }; + extent.write(run.values.pointer(&pointer.0)?, data)?; + Ok(None) + } + Transfer::NoPayload { .. } => Ok(None), + } + } + + fn output( + &self, + mapping: &ResultMapping, + values: &Values, + data: Option>, + ) -> result::Result { + let required_data = + |data: Option>| data.ok_or_else(|| error("Missing owned-copy result")); + Ok(match mapping { + ResultMapping::Void => CopyOutput::Void, + ResultMapping::Bytes => CopyOutput::Bytes(required_data(data)?), + ResultMapping::Packet { + frames, + flags, + device, + qpc, + timestamp_error_mask, + } => { + let flags = values.u32(&flags.0)?; + let timestamps = flags & timestamp_error_mask == 0; + CopyOutput::Packet(Some(CapturePacket { + data, + frames: values.u32(&frames.0)?, + flags, + device_position: if timestamps { + Some(values.u64(&device.0)?) + } else { + None + }, + qpc_position: if timestamps { + Some(values.u64(&qpc.0)?) + } else { + None + }, + })) + } + ResultMapping::Bitmap { width, height } => CopyOutput::Bitmap(BitmapCopy { + data: required_data(data)?, + width: values.u32(&width.0)?, + height: values.u32(&height.0)?, + }), + }) + } + + fn normal_args( + &self, + operation: &Operation, + values: &Values, + ) -> result::Result> { + let Cleanup::Call { call, .. } = &operation.cleanup else { + return Ok(vec![]); + }; + self.prepared(call)? + .contract + .bindings + .iter() + .map(|binding| match binding { + Binding::InU32 { value } => values.source(value).map(WinRTValue::U32), + _ => Err(error("Invalid finalization input binding")), + }) + .collect() + } + + fn execute( + &self, + api: OperationId, + context: &Identity, + object: &IUnknown, + input: Input<'_>, + ) -> result::Result { + let operation = self + .contract + .operations + .iter() + .find(|op| op.api == api && op.arguments == input.kind()) + .ok_or_else(|| error("Operation is not supported by this borrowed-copy plan"))?; + let (mut transaction, mut run) = self.begin(context, object, input)?; + if !self.steps(&operation.before, &mut run)? { + return transaction.complete(Ok(CopyOutput::Void), &[]); + } + let paired = if let Cleanup::Call { call, abort } = &operation.cleanup { + let prepared = self.prepared(call)?; + Some(Finalizer::Call { + method: prepared.method.clone(), + view: self.target(prepared, &run)?, + abort: abort + .iter() + .map(|v| run.values.source(v).map(WinRTValue::U32)) + .collect::>()?, + }) + } else { + None + }; + let (hr, mut outputs) = self.invoke(&operation.acquire, &mut run)?; + if hr.0 != self.contract.acquired_hresult { + if self.contract.empty_hresult == Some(hr.0) { + // Neither publish/read native outputs nor release a packet. + return transaction.complete(Ok(CopyOutput::Packet(None)), &[]); + } + transaction.poison(); + return Err(error(format!( + "Unexpected acquisition HRESULT 0x{:08X}; context poisoned", + hr.0 as u32 + ))); + } + match &operation.cleanup { + Cleanup::Call { .. } => transaction.acquired(paired.expect("prepared paired cleanup")), + Cleanup::ReleaseOwner { owner } => { + let acquired = outputs.take_owner(&owner.0)?; + let raw = acquired.0; + transaction.acquired(Finalizer::Release(acquired)); + run.values.data.insert(owner.0.clone(), Datum::Owner(raw)); + } + } + // Cleanup is now armed. All output validation, copies, allocations and + // native length commits are inside this single transaction. + let result = (|| { + outputs.publish(&mut run.values)?; + self.steps(&operation.after, &mut run)?; + let data = self.transfer(&operation.transfer, &run)?; + for call in &operation.commit { + self.exact_call(call, &mut run)?; + } + let output = self.output(&operation.result, &run.values, data)?; + Ok((output, self.normal_args(operation, &run.values)?)) + })(); + match result { + Ok((output, commit)) => transaction.complete(Ok(output), &commit), + Err(failure) => transaction.complete(Err(failure), &[]), + } + } + + pub fn write_frames_copy( + &self, + context: &Identity, + object: &IUnknown, + data: &[u8], + ) -> result::Result<()> { + self.execute( + OperationId::WriteFramesCopy, + context, + object, + Input::Bytes(data), + ) + .and_then(void) + } + pub fn write_silence( + &self, + context: &Identity, + object: &IUnknown, + frames: u32, + ) -> result::Result<()> { + self.execute( + OperationId::WriteSilence, + context, + object, + Input::Frames(frames), + ) + .and_then(void) + } + pub fn replace_copy( + &self, + context: &Identity, + object: &IUnknown, + data: &[u8], + ) -> result::Result<()> { + self.execute( + OperationId::ReplaceCopy, + context, + object, + Input::Bytes(data), + ) + .and_then(void) + } + pub fn read_copy(&self, context: &Identity, object: &IUnknown) -> result::Result> { + match self.execute(OperationId::ReadCopy, context, object, Input::None)? { + CopyOutput::Bytes(data) => Ok(data), + _ => Err(error("Owned-byte result shape mismatch")), + } + } + pub fn read_packet_copy( + &self, + context: &Identity, + object: &IUnknown, + ) -> result::Result> { + match self.execute(OperationId::ReadPacketCopy, context, object, Input::None)? { + CopyOutput::Packet(packet) => Ok(packet), + _ => Err(error("Packet result shape mismatch")), + } + } + pub fn read_locked_bgra8_copy( + &self, + context: &Identity, + object: &IUnknown, + rect: [i32; 4], + ) -> result::Result { + match self.execute( + OperationId::ReadLockedBgra8Copy, + context, + object, + Input::Rect(rect), + )? { + CopyOutput::Bitmap(bitmap) => Ok(bitmap), + _ => Err(error("Bitmap result shape mismatch")), + } + } +} + +fn void(output: CopyOutput) -> result::Result<()> { + match output { + CopyOutput::Void => Ok(()), + _ => Err(error("Void result shape mismatch")), + } +} + +fn parse_iid(iid: &str) -> result::Result { + GUID::try_from(iid).map_err(|_| error("Invalid reviewed copy IID/GUID")) +} + +fn rectangle_end(rect: [i32; 4]) -> result::Result<(u32, u32)> { + let [x, y, width, height] = rect; + if x < 0 || y < 0 || width <= 0 || height <= 0 { + return Err(error( + "Bitmap rectangle must have nonnegative origin and positive dimensions", + )); + } + let right = x + .checked_add(width) + .ok_or_else(|| error("Bitmap rectangle overflow"))?; + let bottom = y + .checked_add(height) + .ok_or_else(|| error("Bitmap rectangle overflow"))?; + Ok((right as u32, bottom as u32)) +} + +fn audio_layout(origin: &AudioOwner, policy: &AudioOrigin) -> result::Result { + let layout = { + let stored = origin.0.inner.initialized.borrow(); + stored.as_ref().map(|initialized| { + ( + initialized.block_align, + initialized.share_mode, + initialized.flags, + initialized.format.block_align() as usize, + ) + }) + }; + let (block, share_mode, flags, native_block) = + layout.ok_or_else(|| error("Audio client has no observed successful initialization"))?; + let block = block.ok_or_else(|| { + error("Initialized audio format is not a validated uncompressed frame layout") + })?; + if !(0..=1).contains(&share_mode) { + return Err(error("Unsupported initialized audio share mode")); + } + if policy.reject_exclusive_event && share_mode == 1 && flags & EVENT_CALLBACK != 0 { + return Err(error( + "Exclusive event-driven render copy is unsupported: zero-frame abort is invalid", + )); + } + debug_assert_eq!(block, native_block); + Ok(block) +} diff --git a/crates/dynwinrt/src/com_borrowed_plan_tests.rs b/crates/dynwinrt/src/com_borrowed_plan_tests.rs new file mode 100644 index 00000000..7a9727b9 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_plan_tests.rs @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +use contracts::{Binding, Cleanup, OperationId, Registry, Step, U32Source, Unit}; +use testing::reordered; + +fn record(registry: &Registry, name: &str) -> BorrowedCopyContract { + let identity = registry + .interface(&format!("Tests.Borrowed.{name}")) + .unwrap(); + registry + .select(&identity.namespace, &identity.name, &identity.iid) + .unwrap() + .clone() +} + +fn prepare(registry: &Registry, name: &str) -> BorrowedCopyPlan { + let copy = record(registry, name); + assert_eq!( + copy.kind, + CopyKind::MediaBuffer, + "display label must not route execution" + ); + assert!( + BorrowedCopyPlan::prepare(&MetadataTable::new(), copy.clone()).is_err(), + "Production admission must never authorize a test record" + ); + BorrowedCopyPlan::prepare_test(&MetadataTable::new(), copy, registry).unwrap() +} + +#[test] +fn borrowed_copy_new_records_execute_linear_frame_and_row_contracts() { + super::super::super::initialize_apartment(super::super::super::ApartmentType::SingleThreaded) + .unwrap(); + let registry = reordered::registry(); + let fixture = reordered::fixture(); + let media = fixture.object("media").unwrap(); + let context = Identity::for_object(&media).unwrap(); + let linear = prepare(®istry, "Linear"); + assert_eq!(linear.read_copy(&context, &media).unwrap(), [0, 1, 2, 3]); + linear.replace_copy(&context, &media, &[9, 8, 7]).unwrap(); + assert_eq!(linear.read_copy(&context, &media).unwrap(), [9, 8, 7]); + assert_eq!(count(&fixture, "media.unlock"), 3); + assert_eq!(count(&fixture, "media.length.3"), 1); + + let client = initialized(&fixture, 0, 0); + let (render, context) = service(&fixture, &client, AUDIO_RENDER).unwrap(); + let writer = prepare(®istry, "FrameWriter"); + let data = [9, 8, 7, 6, 5, 4, 3, 2]; + writer.write_frames_copy(&context, &render, &data).unwrap(); + assert_eq!(&fixture.bytes()[..8], &data); + fixture.configure("renderNull", 1).unwrap(); + writer.write_silence(&context, &render, 2).unwrap(); + assert!(fixture.events().contains(&"render.release.2.0".into())); + assert!(fixture.events().contains(&"render.release.2.2".into())); + assert!(writer.write_frames_copy(&context, &render, &data).is_err()); + assert!(fixture.events().contains(&"render.release.0.0".into())); + + let (capture, context) = service(&fixture, &client, AUDIO_CAPTURE).unwrap(); + let reader = prepare(®istry, "FrameReader"); + let packet = reader + .read_packet_copy(&context, &capture) + .unwrap() + .unwrap(); + assert_eq!(packet.data.unwrap(), data); + assert_eq!( + ( + packet.frames, + packet.flags, + packet.device_position, + packet.qpc_position + ), + (2, 0, Some(123), Some(456)) + ); + fixture.configure("captureHr", BUFFER_EMPTY as u32).unwrap(); + assert!( + reader + .read_packet_copy(&context, &capture) + .unwrap() + .is_none() + ); + assert_eq!(count(&fixture, "capture.release"), 1); + fixture.configure("captureHr", 0).unwrap(); + fixture + .configure("captureFlags", SILENT | TIMESTAMP_ERROR) + .unwrap(); + fixture.configure("captureNull", 1).unwrap(); + let packet = reader + .read_packet_copy(&context, &capture) + .unwrap() + .unwrap(); + assert!( + packet.data.is_none() && packet.device_position.is_none() && packet.qpc_position.is_none() + ); + assert_eq!(count(&fixture, "capture.release.2"), 2); + + let bitmap = fixture.object("bitmap").unwrap(); + let context = Identity::for_object(&bitmap).unwrap(); + let image = prepare(®istry, "Image"); + let copy = image + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 3]) + .unwrap(); + assert_eq!((copy.width, copy.height), (2, 3)); + assert_eq!( + copy.data, + fixture.bytes()[..8] + .iter() + .copied() + .chain(12..20) + .chain(24..32) + .collect::>() + ); + assert_eq!(count(&fixture, "wic.release"), 1); + fixture.configure("wicCount", 31).unwrap(); + assert!( + image + .read_locked_bgra8_copy(&context, &bitmap, [0, 0, 2, 3]) + .is_err() + ); + assert_eq!(count(&fixture, "wic.release"), 2); +} + +#[test] +fn borrowed_copy_reordered_cleanup_errors_poison_once() { + let registry = reordered::registry(); + let fixture = reordered::fixture(); + let media = fixture.object("media").unwrap(); + let context = Identity::for_object(&media).unwrap(); + let linear = prepare(®istry, "Linear"); + fixture.configure("mediaSetHr", 0x80004005).unwrap(); + assert!(linear.replace_copy(&context, &media, &[4; 4]).is_err()); + assert_eq!(count(&fixture, "media.unlock"), 1); + context.ensure_idle().unwrap(); + fixture.configure("mediaUnlockHr", 0x80004005).unwrap(); + assert!(linear.read_copy(&context, &media).is_err()); + assert!(linear.read_copy(&context, &media).is_err()); + assert_eq!(count(&fixture, "media.unlock"), 2); + assert!(context.ensure_idle().is_err()); +} + +fn reject(name: &str, edit: impl FnOnce(&mut BorrowedCopyContract), reason: &str) { + let fixture = reordered::fixture(); + let mut registry = reordered::registry(); + let mut copy = record(®istry, name); + edit(&mut copy); + *registry + .copies + .iter_mut() + .find(|c| c.id == copy.id) + .unwrap() = copy.clone(); + let Err(failure) = BorrowedCopyPlan::prepare_test(&MetadataTable::new(), copy, ®istry) + else { + panic!("Invalid plan was prepared"); + }; + assert!(failure.message().contains(reason), "{}", failure.message()); + assert!( + fixture.events().is_empty(), + "No native entry is allowed during rejected admission" + ); +} + +#[test] +fn borrowed_copy_test_registry_validation_rejects_invalid_compositions_before_native_entry() { + reject( + "Linear", + |copy| { + let acquire = copy + .calls + .iter_mut() + .find(|c| c.id == "recipe-acquire") + .unwrap(); + acquire.bindings[0] = Binding::OutU64 { + name: "current".into(), + }; + }, + "ABI cells", + ); + reject( + "Linear", + |copy| { + let acquire = copy + .calls + .iter_mut() + .find(|c| c.id == "recipe-acquire") + .unwrap(); + acquire.bindings[0] = Binding::OutU32 { + name: "current".into(), + unit: Unit::Frames, + }; + }, + "Wrong output/reference type", + ); + reject( + "Linear", + |copy| { + let acquire = copy + .calls + .iter_mut() + .find(|c| c.id == "recipe-acquire") + .unwrap(); + acquire.bindings[2] = Binding::OutU32 { + name: "current".into(), + unit: Unit::Bytes, + }; + }, + "Duplicate value/output", + ); + reject( + "FrameWriter", + |copy| copy.operations[0].before.swap(2, 3), + "Dangling, forward or uninitialized", + ); + reject( + "FrameReader", + |copy| { + let Cleanup::Call { abort, .. } = &mut copy.operations[0].cleanup else { + panic!() + }; + abort[1] = U32Source::Frames(contracts::FrameCountRef("frames".into())); + }, + "Dangling, forward or uninitialized", + ); + reject( + "Linear", + |copy| { + let Step::NativeExtent { length, .. } = &mut copy.operations[0].after[0] else { + panic!() + }; + length.0 = "input.bytes".into(); + }, + "Dangling, forward or uninitialized", + ); + reject( + "Image", + |copy| { + copy.operations[0].before.insert( + 0, + Step::Call { + call: "recipe-data".into(), + }, + ); + }, + "Unavailable acquired owner", + ); + reject( + "Linear", + |copy| { + let replace = copy + .operations + .iter_mut() + .find(|op| op.api == OperationId::ReplaceCopy) + .unwrap(); + replace.commit.clear(); + }, + "requires its native length commit", + ); + reject( + "FrameReader", + |copy| { + let release = copy + .calls + .iter_mut() + .find(|c| c.id == "recipe-release") + .unwrap(); + release.bindings[1] = Binding::InU32 { + value: U32Source::Constant(0), + }; + }, + "Missing full/zero", + ); + reject( + "Image", + |copy| copy.calls[0].evidence = "unknown-review-evidence".into(), + "Unknown registry evidence", + ); + reject( + "FrameWriter", + |copy| { + copy.calls + .iter_mut() + .find(|call| call.id == "recipe-release") + .unwrap() + .bindings + .swap(0, 1); + }, + "Wrong output/reference type for native ABI cell", + ); + reject( + "Linear", + |copy| { + let Cleanup::Call { call: id, .. } = ©.operations[0].cleanup else { + panic!() + }; + let release = copy.calls.iter_mut().find(|call| call.id == *id).unwrap(); + release.evidence = "test-IMFMediaBuffer.SetCurrentLength".into(); + release.bindings.push(Binding::InU32 { + value: U32Source::Constant(0), + }); + for op in &mut copy.operations { + let Cleanup::Call { abort, .. } = &mut op.cleanup else { + panic!() + }; + abort.push(U32Source::Constant(0)); + } + }, + "Cleanup does not close the reviewed acquisition", + ); +} diff --git a/crates/dynwinrt/src/com_borrowed_reordered_support.rs b/crates/dynwinrt/src/com_borrowed_reordered_support.rs new file mode 100644 index 00000000..1798ddd7 --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_reordered_support.rs @@ -0,0 +1,417 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Test-only reviewed records and ABI-correct alternative interfaces. Original +//! views remain truthful for observed Initialize/GetService provenance; all copy +//! calls use new IIDs, new slots, and reordered native bindings. + +use super::super::contracts::{ + self, AbiCell, AcquisitionCleanup, Binding, Cleanup, CopyKind, Registry, Step, Target, + U32Source, Unit, +}; +use super::*; +use std::sync::LazyLock; + +const CLIENT: GUID = GUID::from_u128(0xde860701_67f0_4c94_9665_514d8b6a9811); +const RENDER: GUID = GUID::from_u128(0xde860702_67f0_4c94_9665_514d8b6a9811); +const CAPTURE: GUID = GUID::from_u128(0xde860703_67f0_4c94_9665_514d8b6a9811); +const BITMAP: GUID = GUID::from_u128(0xde860704_67f0_4c94_9665_514d8b6a9811); +const LOCK: GUID = GUID::from_u128(0xde860705_67f0_4c94_9665_514d8b6a9811); +const MEDIA: GUID = GUID::from_u128(0xde860706_67f0_4c94_9665_514d8b6a9811); +const MARKER: u32 = 0xD07; + +unsafe extern "system" fn reordered_qi( + this: *mut c_void, + iid: *const GUID, + output: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || output.is_null() { + return POINTER; + } + let owner = unsafe { owner(this) }; + let extra = match owner.kind { + Kind::Client => CLIENT, + Kind::Render => RENDER, + Kind::Capture => CAPTURE, + Kind::Bitmap => BITMAP, + Kind::Lock => LOCK, + Kind::Media => MEDIA, + }; + if unsafe { *iid } != extra { + return unsafe { qi(this, iid, output) }; + } + unsafe { + *output = (&owner.views[1] as *const View).cast_mut().cast(); + add_ref(this); + } + OK +} + +fn unknown() -> IUnknown_Vtbl { + IUnknown_Vtbl { + QueryInterface: reordered_qi, + AddRef: add_ref, + Release: release, + } +} + +#[repr(C)] +struct Client { + base: ClientVtable, + capacity: unsafe extern "system" fn(*mut c_void, u32, *mut u32) -> HRESULT, +} +unsafe extern "system" fn capacity(this: *mut c_void, marker: u32, output: *mut u32) -> HRESULT { + if marker != MARKER { + return INVALID; + } + unsafe { size(this, output) } +} +static CLIENT_TABLE: LazyLock = LazyLock::new(|| Client { + base: ClientVtable { + base: unknown(), + ..CLIENT_VTABLE + }, + capacity, +}); + +#[repr(C)] +struct Render { + base: RenderVtable, + acquire: unsafe extern "system" fn(*mut c_void, *mut *mut u8, u32) -> HRESULT, + finish: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT, +} +unsafe extern "system" fn render_acquire( + this: *mut c_void, + data: *mut *mut u8, + frames: u32, +) -> HRESULT { + unsafe { render_get(this, frames, data) } +} +unsafe extern "system" fn render_finish(this: *mut c_void, flags: u32, frames: u32) -> HRESULT { + unsafe { render_release(this, frames, flags) } +} +static RENDER_TABLE: LazyLock = LazyLock::new(|| Render { + base: RenderVtable { + base: unknown(), + ..RENDER_VTABLE + }, + acquire: render_acquire, + finish: render_finish, +}); + +#[repr(C)] +struct Capture { + base: CaptureVtable, + acquire: unsafe extern "system" fn( + *mut c_void, + *mut u64, + *mut u32, + *mut *mut u8, + *mut u64, + *mut u32, + ) -> HRESULT, + finish: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT, +} +unsafe extern "system" fn packet_acquire( + this: *mut c_void, + qpc: *mut u64, + flags: *mut u32, + data: *mut *mut u8, + device: *mut u64, + frames: *mut u32, +) -> HRESULT { + unsafe { capture_get(this, data, frames, flags, device, qpc) } +} +unsafe extern "system" fn packet_finish(this: *mut c_void, marker: u32, frames: u32) -> HRESULT { + if marker != MARKER { + return INVALID; + } + unsafe { capture_release(this, frames) } +} +static CAPTURE_TABLE: LazyLock = LazyLock::new(|| Capture { + base: CaptureVtable { + base: unknown(), + ..CAPTURE_VTABLE + }, + acquire: packet_acquire, + finish: packet_finish, +}); + +#[repr(C)] +struct Bitmap { + base: BitmapVtable, + acquire: unsafe extern "system" fn(*mut c_void, *mut *mut c_void, u32, *const i32) -> HRESULT, + dimensions: unsafe extern "system" fn(*mut c_void, *mut u32, *mut u32) -> HRESULT, +} +unsafe extern "system" fn image_acquire( + this: *mut c_void, + output: *mut *mut c_void, + flags: u32, + rect: *const i32, +) -> HRESULT { + if rect.is_null() || unsafe { std::slice::from_raw_parts(rect, 4) } != [0, 0, 2, 3] { + return INVALID; + } + let fixture_rect = [0, 0, 2, 2]; + let hr = unsafe { bitmap_lock(this, fixture_rect.as_ptr(), flags, output) }; + if !output.is_null() && !unsafe { *output }.is_null() { + unsafe { install(*output, (&*LOCK_TABLE as *const Lock).cast()) }; + } + hr +} +unsafe extern "system" fn dimensions( + this: *mut c_void, + height: *mut u32, + width: *mut u32, +) -> HRESULT { + let hr = unsafe { bitmap_size(this, width, height) }; + if hr.0 == 0 { + unsafe { *height = 3 }; + } + hr +} +static BITMAP_TABLE: LazyLock = LazyLock::new(|| Bitmap { + base: BitmapVtable { + base: unknown(), + ..BITMAP_VTABLE + }, + acquire: image_acquire, + dimensions, +}); + +#[repr(C)] +struct Lock { + base: LockVtable, + dimensions: unsafe extern "system" fn(*mut c_void, *mut u32, *mut u32) -> HRESULT, + stride: unsafe extern "system" fn(*mut c_void, u32, *mut u32) -> HRESULT, + data: unsafe extern "system" fn(*mut c_void, *mut *mut u8, *mut u32) -> HRESULT, + format: unsafe extern "system" fn(*mut c_void, *mut GUID) -> HRESULT, +} +unsafe extern "system" fn stride(this: *mut c_void, marker: u32, output: *mut u32) -> HRESULT { + if marker != MARKER { + return INVALID; + } + unsafe { lock_stride(this, output) } +} +unsafe extern "system" fn image_data( + this: *mut c_void, + data: *mut *mut u8, + count: *mut u32, +) -> HRESULT { + unsafe { lock_data(this, count, data) } +} +static LOCK_TABLE: LazyLock = LazyLock::new(|| Lock { + base: LockVtable { + base: unknown(), + ..LOCK_VTABLE + }, + dimensions, + stride, + data: image_data, + format: bitmap_format, +}); + +#[repr(C)] +struct Linear { + base: MediaVtable, + acquire: unsafe extern "system" fn(*mut c_void, *mut u32, *mut *mut u8, *mut u32) -> HRESULT, + set_length: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT, + finish: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, +} +unsafe extern "system" fn linear_acquire( + this: *mut c_void, + current: *mut u32, + data: *mut *mut u8, + max: *mut u32, +) -> HRESULT { + unsafe { media_lock(this, data, max, current) } +} +unsafe extern "system" fn set_length(this: *mut c_void, marker: u32, length: u32) -> HRESULT { + if marker != MARKER { + return INVALID; + } + unsafe { media_set(this, length) } +} +unsafe extern "system" fn linear_finish(this: *mut c_void, marker: u32) -> HRESULT { + if marker != MARKER { + return INVALID; + } + unsafe { media_unlock(this) } +} +static LINEAR_TABLE: LazyLock = LazyLock::new(|| Linear { + base: MediaVtable { + base: unknown(), + ..MEDIA_VTABLE + }, + acquire: linear_acquire, + set_length, + finish: linear_finish, +}); + +unsafe fn install(this: *mut c_void, vtable: *const c_void) { + let owner = unsafe { &mut *(*(this.cast::())).owner }; + for view in &mut owner.views { + view.vtable = vtable; + } +} + +pub fn fixture() -> CopyFixture { + let fixture = CopyFixture::default(); + fixture.configure("wicCount", 32).unwrap(); + for (name, table) in [ + ("client", (&*CLIENT_TABLE as *const Client).cast()), + ("render", (&*RENDER_TABLE as *const Render).cast()), + ("capture", (&*CAPTURE_TABLE as *const Capture).cast()), + ("bitmap", (&*BITMAP_TABLE as *const Bitmap).cast()), + ("media", (&*LINEAR_TABLE as *const Linear).cast()), + ] { + unsafe { install(fixture.object(name).unwrap().as_raw(), table) }; + } + fixture +} + +pub fn registry() -> Registry { + let mut registry = contracts::registry().clone(); + let mut identities = std::collections::HashMap::new(); + for (original, name, iid, last) in [ + ("IAudioClient", "ObservedClient", CLIENT, 21), + ("IAudioRenderClient", "FrameWriter", RENDER, 6), + ("IAudioCaptureClient", "FrameReader", CAPTURE, 7), + ("IWICBitmap", "Image", BITMAP, 12), + ("IWICBitmapLock", "ImageOwner", LOCK, 10), + ("IMFMediaBuffer", "Linear", MEDIA, 10), + ] { + let mut record = registry + .interfaces + .iter() + .find(|r| r.name == original) + .unwrap() + .clone(); + let old = record.identity(); + record.namespace = "Tests.Borrowed".into(); + record.name = name.into(); + record.iid = format!("{iid:?}").to_lowercase(); + record.bases = vec!["IUnknown".into()]; + record.base_iids.clear(); + record.own_start = 3; + record.last = last; + identities.insert(old, (record.identity(), record.iid.clone())); + registry.interfaces.push(record); + } + for mut copy in contracts::registry().copies.clone() { + copy.id = format!("test-{}", copy.id); + copy.receiver = identities[©.receiver].0.clone(); + for dependency in &mut copy.dependencies { + *dependency = identities[dependency].0.clone(); + } + if let Some(origin) = &mut copy.audio_origin { + origin.interface = identities[&origin.interface].0.clone(); + } + // Deliberately misleading display labels cannot select an algorithm. + copy.kind = CopyKind::MediaBuffer; + let mut finalizer_orders = std::collections::HashMap::new(); + for call in &mut copy.calls { + let old = registry.evidence(&call.evidence).unwrap(); + let (slot, order, marker): (usize, &[usize], bool) = match call.evidence.as_str() { + "IAudioClient.GetBufferSize" => (21, &[0], true), + "IAudioRenderClient.GetBuffer" => (5, &[1, 0], false), + "IAudioRenderClient.ReleaseBuffer" => (6, &[1, 0], false), + "IAudioCaptureClient.GetBuffer" => (6, &[4, 2, 0, 3, 1], false), + "IAudioCaptureClient.ReleaseBuffer" => (7, &[0], true), + "IWICBitmapSource.GetSize" => (12, &[1, 0], false), + "IWICBitmap.Lock" => (11, &[2, 1, 0], false), + "IWICBitmapLock.GetSize" => (7, &[1, 0], false), + "IWICBitmapLock.GetStride" => (8, &[0], true), + "IWICBitmapLock.GetDataPointer" => (9, &[1, 0], false), + "IWICBitmapLock.GetPixelFormat" => (10, &[0], false), + "IMFMediaBuffer.Lock" => (8, &[2, 0, 1], false), + "IMFMediaBuffer.SetCurrentLength" => (9, &[0], true), + "IMFMediaBuffer.Unlock" => (10, &[], true), + _ => panic!("No test ABI"), + }; + let mut evidence = old.clone(); + let target = match &call.target { + Target::Receiver => ©.receiver, + Target::AudioOrigin => ©.audio_origin.as_ref().unwrap().interface, + Target::Acquired(_) => ©.dependencies[0], + }; + let target = registry.interface(target).unwrap(); + evidence.id = format!("test-{}", evidence.id); + evidence.namespace = target.namespace.clone(); + evidence.interface = target.name.clone(); + evidence.iid = target.iid.clone(); + evidence.slot = slot; + evidence.fingerprint = "A".repeat(64); + evidence.citation = "test-only ABI-correct reordered native vtable".into(); + if let Some(AcquisitionCleanup::Call { evidence }) = &mut evidence.acquisition_cleanup { + *evidence = format!("test-{evidence}"); + } + call.evidence = evidence.id.clone(); + let old_abi = old.abi.as_ref().unwrap(); + let mut abi: Vec<_> = order.iter().map(|i| old_abi[*i].clone()).collect(); + call.bindings = order.iter().map(|i| call.bindings[*i].clone()).collect(); + if marker { + abi.insert(0, AbiCell::InU32(Unit::Scalar)); + call.bindings.insert( + 0, + Binding::InU32 { + value: U32Source::Constant(MARKER), + }, + ); + } + for binding in &mut call.bindings { + if let Binding::OwnedInterface { interface, .. } = binding { + *interface = identities[interface].0.clone(); + } + } + evidence.abi = Some(abi); + if !registry.evidence.iter().any(|e| e.id == evidence.id) { + registry.evidence.push(evidence); + } + finalizer_orders.insert(call.id.clone(), (order.to_vec(), marker)); + call.id = format!("recipe-{}", call.id); + } + for op in &mut copy.operations { + op.acquire = format!("recipe-{}", op.acquire); + for step in op.before.iter_mut().chain(&mut op.after) { + if let Step::Call { call } = step { + *call = format!("recipe-{call}"); + } + } + for call in &mut op.commit { + *call = format!("recipe-{call}"); + } + if let Cleanup::Call { call, abort } = &mut op.cleanup { + let (order, marker) = &finalizer_orders[call]; + *abort = order.iter().map(|i| abort[*i].clone()).collect(); + if *marker { + abort.insert(0, U32Source::Constant(MARKER)); + } + *call = format!("recipe-{call}"); + } + } + copy.calls.reverse(); + registry.copies.push(copy); + } + registry +} + +#[test] +fn borrowed_copy_reordered_fake_slots_are_abi_correct_on_both_widths() { + use std::mem::{offset_of, size_of}; + let p = size_of::(); + assert_eq!(offset_of!(Client, capacity), 21 * p); + assert_eq!(offset_of!(Render, acquire), 5 * p); + assert_eq!(offset_of!(Render, finish), 6 * p); + assert_eq!(offset_of!(Capture, acquire), 6 * p); + assert_eq!(offset_of!(Capture, finish), 7 * p); + assert_eq!(offset_of!(Bitmap, acquire), 11 * p); + assert_eq!(offset_of!(Bitmap, dimensions), 12 * p); + assert_eq!(offset_of!(Lock, dimensions), 7 * p); + assert_eq!(offset_of!(Lock, stride), 8 * p); + assert_eq!(offset_of!(Lock, data), 9 * p); + assert_eq!(offset_of!(Lock, format), 10 * p); + assert_eq!(offset_of!(Linear, acquire), 8 * p); + assert_eq!(offset_of!(Linear, set_length), 9 * p); + assert_eq!(offset_of!(Linear, finish), 10 * p); +} diff --git a/crates/dynwinrt/src/com_borrowed_test_support.rs b/crates/dynwinrt/src/com_borrowed_test_support.rs index fc752768..2c9301ea 100644 --- a/crates/dynwinrt/src/com_borrowed_test_support.rs +++ b/crates/dynwinrt/src/com_borrowed_test_support.rs @@ -16,6 +16,10 @@ use std::{ }; use windows_core::{GUID, HRESULT, IUnknown, IUnknown_Vtbl, Interface as _}; +#[cfg(test)] +#[path = "com_borrowed_reordered_support.rs"] +pub(super) mod reordered; + const FAIL: HRESULT = HRESULT(0x80004005u32 as i32); const INVALID: HRESULT = HRESULT(0x80070057u32 as i32); const POINTER: HRESULT = HRESULT(0x80004003u32 as i32); @@ -507,7 +511,7 @@ unsafe extern "system" fn current_period( mix_format(this, format) } } -static CLIENT_VTABLE: ClientVtable = ClientVtable { +const CLIENT_VTABLE: ClientVtable = ClientVtable { base: UNKNOWN, initialize, size, @@ -587,7 +591,7 @@ unsafe extern "system" fn render_release(this: *mut c_void, frames: u32, flags: control.render_active.set(false); OK } -static RENDER_VTABLE: RenderVtable = RenderVtable { +const RENDER_VTABLE: RenderVtable = RenderVtable { base: UNKNOWN, get: render_get, release: render_release, @@ -681,7 +685,7 @@ unsafe extern "system" fn capture_next(this: *mut c_void, output: *mut u32) -> H } OK } -static CAPTURE_VTABLE: CaptureVtable = CaptureVtable { +const CAPTURE_VTABLE: CaptureVtable = CaptureVtable { base: UNKNOWN, get: capture_get, release: capture_release, @@ -780,7 +784,7 @@ unsafe extern "system" fn bitmap_lock( } HRESULT(control.wic_lock_hr.get()) } -static BITMAP_VTABLE: BitmapVtable = BitmapVtable { +const BITMAP_VTABLE: BitmapVtable = BitmapVtable { base: UNKNOWN, size: bitmap_size, format: bitmap_format, @@ -831,7 +835,7 @@ unsafe extern "system" fn lock_data( } OK } -static LOCK_VTABLE: LockVtable = LockVtable { +const LOCK_VTABLE: LockVtable = LockVtable { base: UNKNOWN, size: bitmap_size, stride: lock_stride, @@ -921,7 +925,7 @@ unsafe extern "system" fn media_max(this: *mut c_void, output: *mut u32) -> HRES } OK } -static MEDIA_VTABLE: MediaVtable = MediaVtable { +const MEDIA_VTABLE: MediaVtable = MediaVtable { base: UNKNOWN, lock: media_lock, unlock: media_unlock, diff --git a/crates/dynwinrt/src/com_borrowed_tests.rs b/crates/dynwinrt/src/com_borrowed_tests.rs index b4249aa9..825e1b6a 100644 --- a/crates/dynwinrt/src/com_borrowed_tests.rs +++ b/crates/dynwinrt/src/com_borrowed_tests.rs @@ -4,6 +4,9 @@ use super::testing::CopyFixture; use super::*; +#[path = "com_borrowed_plan_tests.rs"] +mod planner; + fn plan(kind: CopyKind) -> BorrowedCopyPlan { BorrowedCopyPlan::prepare(&MetadataTable::new(), BorrowedCopyContract::expected(kind)).unwrap() } @@ -147,13 +150,17 @@ fn borrowed_copy_descriptor_drift_and_effect_signature_reject_before_dispatch() CopyKind::MediaBuffer, ] { let mut descriptor = BorrowedCopyContract::expected(kind); - descriptor.acquire.slot += 1; + descriptor.calls[0].evidence.push_str(".slot-drift"); assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); let mut descriptor = BorrowedCopyContract::expected(kind); - descriptor.acquire.storage.clear(); + descriptor.calls[0].bindings.clear(); assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); let mut descriptor = BorrowedCopyContract::expected(kind); - descriptor.audio_origin_required = !descriptor.audio_origin_required; + descriptor.audio_origin = if descriptor.audio_origin.is_some() { + None + } else { + BorrowedCopyContract::expected(CopyKind::AudioRender).audio_origin + }; assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); } let table = MetadataTable::new(); diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 1cce042e..74a1afd3 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -556,14 +556,19 @@ controlled contract-family ablation, remains later registry migration work. The strict contract data schema and its registry `manifest.json` remain version 2. The capability summary is version 3, and generated unsafe support manifests are version 12. -Seven WMI conditional-output entries and 149 output-ownership entries are -JSON-backed; the other 376 registered entries remain code-defined. All code and -data entries use the same selector-derived `entryId`, typed `familyId`, +Seven WMI conditional-output entries and 149 output-ownership entries use the +grouped contract-data registry. Of the other 376 registered entries, 26 +borrowed-copy/context entries now live in the native-independent packaged +`dynwinrt-com-contracts` JSON registry; their existing exact-entry catalog and +dependency classification are preserved. The other 350 remain code-defined. +All entries use the same selector-derived `entryId`, typed `familyId`, selector/fingerprint/citation catalog, and pinned-metadata validation path. Separately, PR1 raised the generated COM file-ownership manifest `com/.dynwinrt-com-manifest.json` from version 2 to version 3; borrowed-copy -context effects now require version 4. Generated safe +context effects introduced version 4, and version-2 typed copy recipes now +require manifest version 5. This changes neither evidence IDs nor support +counts. Generated safe classes must register descriptors for the public runtime `/com` `projectAs` entrypoint and typed `IMMDevice.activate` through private `/com/unsafe` helpers. Delete existing generated bindings and completely regenerate every diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 7a17f502..72bec6e0 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -267,11 +267,44 @@ count the three copy-only facades as newly complete interfaces. ### Private context and lifecycle -The plan describes receiver IID, acquire method, private output-cell storage, -native extent source, access, owner, normal/abort finalizers, and apartment -prerequisites. All signatures and cleanup recipes are prepared before native -acquisition. Output cells are private stable storage, not language values: the -executor cannot read them before the transaction classifies the HRESULT. +The native-independent +[`dynwinrt-com-contracts` registry](../../crates/dynwinrt-com-contracts/src/registry.json) +is the single reviewed source for complete interface identities, native +IID/slot/ABI-cell evidence, operation/result mappings, and lifecycle recipes. +Codegen selects records by exact identity; the runtime admits only an exact +packaged record. A matching-looking JSON object or a new record ID does not +authorize native memory access. + +The version-2 recipe actually drives execution: + +* named `calls` reference reviewed `evidence` and bind each native argument to + a typed input source or named output cell; +* `before`, `acquire`, and `after` order queries and acquisition; typed byte, + frame, layout, rectangle, row, flag, timestamp, and owner references must have + available producers, compatible ABI cells and matching native owners; +* the closed `frame-extent`, `native-extent`, and `row-extent` constructors prove + the copy bounds, while `transfer` chooses read, write, silent-packet skipping, + or no-payload silence; +* `commit` consumes the proven replacement length, and `cleanup` supplies the + actual normal/abort arguments or names the unique acquired owner to Release; +* `result` names the bounded dimensions, frames, flags and timestamps to project. + +The pure validator checks the entire recipe, including abort availability +before acquisition, full/zero frame release, access, result shape and owner +lifetime, before preparing any native call. Reviewed evidence designates each +acquisition's finalizer and the units of each native scalar cell; a same-width +flags/count swap or unrelated cleanup call cannot satisfy the graph proof. +Runtime native lengths still +require checked arithmetic and pointer/extent validation after successful +acquisition. All calls use completed MethodHandles/libffi, with no family +execution switch or per-interface SDK adapter. The public methods are thin +operation selectors. This is not an arbitrary-execution DSL: no pointer input, +caller byte extent, user callback, loop, allocator selection or new production +interface is introduced. + +Output cells are private stable storage, not language values: the executor +cannot publish/read them before classifying the exact HRESULT. Cleanup is +armed before inspecting acquired outputs or allocating/copying result bytes. ```text Idle -> Acquiring -> Active -> Finalizing -> Idle @@ -374,25 +407,40 @@ Caller-provided height or stride is never treated as native memory bounds. ### Evidence and regeneration +The shared packaged registry contains the same 26 exact selectors, full source +fingerprints and Microsoft citations. [`com_borrowed_metadata.rs`](../../tools/dynwinrt-codegen/src/com_borrowed_metadata.rs) -contains all 26 exact selectors, full source fingerprints and Microsoft -citations. The configured metadata must include Win32Metadata +checks them against the configured metadata, which must include Win32Metadata **71.0.14-preview**, SHA256 `B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`. The complete inherited interfaces and required owner/lock dependencies are validated, not just acquisition methods. Runtime descriptors are versioned and closed; absent/drifted signatures, storage roles, prerequisites or finalizers fail before acquisition. Renderers only serialize the projected IR. - -COM file-ownership manifest **4** and unsafe support schema **12** require deletion and full regeneration -of older output. Do not mix pre-effect audio wrappers with new copy facades. +Borrowed descriptors are now **version 2**, and the generated COM ownership +manifest is **version 5**. Old descriptors/manifests require complete +regeneration; there is no silent or incremental migration. Evidence IDs, +fingerprints, support sets and public declarations are unchanged; embedded +descriptor JavaScript and the ownership-manifest version necessarily differ. + +Hardware-free tests add test-only records for new linear, frame-writer, +frame-reader and row-copy interfaces (plus their owner/context views). +Every native copy call uses a different IID and slot, reordered argument/output +bindings, and renamed/reordered calls. Real copies and full/zero or owner +cleanup execute without changing production model/executor dispatch. The +fixtures also exercise ABI-sized storage on x64/i686, short last rows, +silent/empty packets, commit failure and exactly-once poisoning. Test registry +injection is absent from production and JS test-hooks builds. + +COM file-ownership manifest **5** and unsafe support schema **12** require deletion +and full regeneration of older output. Do not mix pre-effect audio wrappers with new copy facades. Coverage includes native fake tear-offs with complete SDK-correct vtables, truthful QI, alias/context lifetime, failed initialization and differing mix formats, no-JS reentrancy, exact-once poisoned cleanup, all packet states, WIC final-row/stride cases, MF failure paths, and live stock-Windows WIC/MF. Both x64 and live i686 execute the same runtime tests. -Retained PR3 validation: +Retained PR3 validation before the version-2 execution-plan refactor: | Check | Result | | --- | --- | @@ -808,7 +856,8 @@ without adding COM exports to the WinRT root. PR1 raised the generated COM file-ownership manifest `com/.dynwinrt-com-manifest.json` from version 2 to version 3. Borrowed-copy -context effects now require **version 4**. Every +context effects introduced **version 4**; typed borrowed-copy recipes now +require **version 5**. Every generated safe class now registers a descriptor through private `@microsoft/dynwinrt/com/unsafe` helpers. Public `projectAs` remains on the runtime `@microsoft/dynwinrt/com` entrypoint, and generated diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 6140d324..0b5a7d09 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -136,14 +136,15 @@ Generated output is placed in `generated/com/`. Internally, the `.js` files impo value types from `@microsoft/dynwinrt/com`. The generator records files per top-level COM root in -`generated/com/.dynwinrt-com-manifest.json`, currently version 4. Within the +`generated/com/.dynwinrt-com-manifest.json`, currently version 5. Within the same manifest version, regenerating a root removes files it no longer owns, while files shared with or generated by other roots remain intact. **Upgrade requirement:** PR1 introduced version 3 for registered `projectAs` -and typed endpoint activation. Borrowed-copy support requires version 4 so -every selected audio initialization/GetService wrapper carries its context -effects. Delete the existing generated bindings directory and +and typed endpoint activation. Borrowed-copy support introduced version 4 for +audio initialization/GetService context effects. The plan-driven copy recipes +now require manifest version 5 and borrowed-descriptor version 2; public APIs +and supported interfaces are unchanged. Delete the existing generated bindings directory and completely regenerate all selected roots with the matching updated runtime and codegen. There is no in-place migration: do not edit the manifest version, regenerate only one old root, or mix old and new generated classes. @@ -744,8 +745,9 @@ endpoint settings. ### 5.7 Borrowed native storage: use owned copies Generate the Audio client and copy receivers together. After upgrading to -COM manifest **4** / unsafe support schema **12**, delete the old generated output and regenerate it in -full; do not combine old audio initialization wrappers with new copy facades. +COM manifest **5**, borrowed-descriptor version **2**, and unsafe support schema +**12**, delete the old generated output and regenerate it in full; do not combine +old audio initialization wrappers with new copy facades. ```powershell npx dynwinrt-codegen generate --winmd $winmd ` diff --git a/eng/coverage/coverage.ps1 b/eng/coverage/coverage.ps1 index e196176a..9f332f04 100644 --- a/eng/coverage/coverage.ps1 +++ b/eng/coverage/coverage.ps1 @@ -604,6 +604,7 @@ try { } Invoke-Step "Rust workspace tests" { & cargo test ` + -p dynwinrt-com-contracts ` -p dynwinrt ` -p dynwinrt-codegen ` -p dynwinrt-py ` diff --git a/tools/dynwinrt-codegen/Cargo.toml b/tools/dynwinrt-codegen/Cargo.toml index b2286375..e8b7e426 100644 --- a/tools/dynwinrt-codegen/Cargo.toml +++ b/tools/dynwinrt-codegen/Cargo.toml @@ -8,6 +8,7 @@ repository = "https://github.com/microsoft/dynwinrt" authors = ["Microsoft"] [dependencies] +dynwinrt-com-contracts = { path = "../../crates/dynwinrt-com-contracts", version = "0.1.0" } windows-metadata = "0.59.0" clap = { version = "4", features = ["derive"] } csv = "1" diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs b/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs index 7ead9f77..50f44379 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs @@ -2,44 +2,10 @@ // Licensed under the MIT License. use crate::com_metadata::{ComInterfaceMeta, borrowed as evidence}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(in crate::codegen::com) enum CopyFamily { - AudioRender, - AudioCapture, - BitmapBgra8, - MediaBuffer, -} - -#[derive(serde::Serialize)] -pub(in crate::codegen::com) struct NativeCall { - iid: &'static str, - slot: usize, - storage: Vec<&'static str>, -} - -#[derive(serde::Serialize)] -pub(in crate::codegen::com) struct BorrowedCopyPlan { - version: u32, - metadata_sha256: &'static str, - access: &'static str, - exposure: &'static str, - owner: &'static str, - acquired_hresult: i32, - empty_hresult: Option, - kind: &'static str, - receiver: &'static str, - acquire: NativeCall, - queries: Vec, - finalize: Option, - extent: &'static str, - finalization: &'static str, - sta_only: bool, - audio_origin_required: bool, -} +use dynwinrt_com_contracts::{BorrowedCopyContract, registry}; pub(in crate::codegen::com) struct ValidatedStorage { - pub copy: Option<(CopyFamily, BorrowedCopyPlan)>, + pub copy: Option, pub effects: Vec<(usize, &'static evidence::Evidence)>, pub dependencies: crate::contract_registry::EvidenceDependencies, } @@ -54,144 +20,40 @@ pub(in crate::codegen::com) fn validate( evidence::require_metadata_hash(paths)?; evidence::validate_interface(meta)?; let mut dependencies = crate::com_metadata::collect_evidence_dependencies(meta); - if evidence::is_audio_context(meta) { - let effects = meta - .raw_methods - .as_ref() - .expect("validated raw evidence") - .iter() - .filter_map(|raw| evidence::evidence_for(raw).transpose()) - .collect::, _>>()? - .into_iter() - .filter(|entry| entry.effect.is_some()) - .map(|entry| (entry.slot, entry)) - .collect(); - return Ok(Some(ValidatedStorage { - copy: None, - effects, - dependencies, - })); - } - let family = match ( - meta.interface.namespace.as_str(), - meta.interface.name.as_str(), - ) { - (evidence::AUDIO, "IAudioRenderClient") => CopyFamily::AudioRender, - (evidence::AUDIO, "IAudioCaptureClient") => CopyFamily::AudioCapture, - (evidence::WIC, "IWICBitmap") => CopyFamily::BitmapBgra8, - (evidence::MF, "IMFMediaBuffer") => CopyFamily::MediaBuffer, - _ => return Err("Unknown borrowed-storage family".into()), - }; - let dependency = if family == CopyFamily::BitmapBgra8 { - Some((evidence::WIC, "IWICBitmapLock")) - } else if matches!(family, CopyFamily::AudioRender | CopyFamily::AudioCapture) { - Some((evidence::AUDIO, "IAudioClient")) - } else { - None - }; - if let Some((namespace, name)) = dependency { - let dependency = crate::com_metadata::parse_com_interface(paths, namespace, name) - .ok_or_else(|| format!("Borrowed-copy dependency {namespace}.{name} is absent"))?; - evidence::validate_interface(&dependency)?; - for entry in evidence::catalog_entries(&dependency) { - dependencies.add_exact(entry.entry_id, entry.family_id, entry.contract_kind); + let effects = meta + .raw_methods + .as_ref() + .expect("validated raw evidence") + .iter() + .filter_map(|raw| evidence::evidence_for(raw).transpose()) + .collect::, _>>()? + .into_iter() + .filter(|entry| entry.effect.is_some()) + .map(|entry| (entry.slot, entry)) + .collect(); + let copy = registry() + .select( + &meta.interface.namespace, + &meta.interface.name, + &meta.interface.iid, + ) + .cloned(); + if let Some(copy) = © { + registry().admit(copy)?; + for identity in ©.dependencies { + let record = registry().interface(identity)?; + let dependency = + crate::com_metadata::parse_com_interface(paths, &record.namespace, &record.name) + .ok_or_else(|| format!("Borrowed-copy dependency {identity} is absent"))?; + evidence::validate_interface(&dependency)?; + for entry in evidence::catalog_entries(&dependency) { + dependencies.add_exact(entry.entry_id, entry.family_id, entry.contract_kind); + } } } - let call = |iid, slot, storage: &[&'static str]| NativeCall { - iid, - slot, - storage: storage.to_vec(), - }; - let (kind, receiver, acquire, queries, finalize, extent, finalization) = match family { - CopyFamily::AudioRender => ( - "audio-render", - evidence::RENDER_IID, - call(evidence::RENDER_IID, 3, &["in-u32", "borrowed-bytes"]), - vec![call(evidence::CLIENT_IID, 4, &["out-u32"])], - Some(call(evidence::RENDER_IID, 4, &["in-u32", "in-u32"])), - "initialized-frames", - "render-full-or-zero", - ), - CopyFamily::AudioCapture => ( - "audio-capture", - evidence::CAPTURE_IID, - call( - evidence::CAPTURE_IID, - 3, - &["borrowed-bytes", "out-u32", "out-u32", "out-u64", "out-u64"], - ), - vec![call(evidence::CLIENT_IID, 4, &["out-u32"])], - Some(call(evidence::CAPTURE_IID, 4, &["in-u32"])), - "capture-packet-frames", - "capture-full-or-zero", - ), - CopyFamily::BitmapBgra8 => ( - "bitmap-bgra8", - evidence::BITMAP_IID, - call( - evidence::BITMAP_IID, - 8, - &["in-rect", "in-u32", "owned-interface"], - ), - vec![ - call(evidence::BITMAP_IID, 3, &["out-u32", "out-u32"]), - call(evidence::LOCK_IID, 3, &["out-u32", "out-u32"]), - call(evidence::LOCK_IID, 4, &["out-u32"]), - call(evidence::LOCK_IID, 6, &["out-guid"]), - call(evidence::LOCK_IID, 5, &["out-u32", "borrowed-bytes"]), - ], - None, - "native-bgra8-rows", - "release-lock-reference", - ), - CopyFamily::MediaBuffer => ( - "media-buffer", - evidence::MF_IID, - call( - evidence::MF_IID, - 3, - &["borrowed-bytes", "out-u32", "out-u32"], - ), - vec![call(evidence::MF_IID, 6, &["in-u32"])], - Some(call(evidence::MF_IID, 4, &[])), - "native-current-and-max", - "unlock", - ), - }; Ok(Some(ValidatedStorage { - effects: vec![], + copy, + effects, dependencies, - copy: Some(( - family, - BorrowedCopyPlan { - version: 1, - metadata_sha256: evidence::METADATA_SHA256, - exposure: "owned-copy-only", - access: match family { - CopyFamily::AudioRender => "write", - CopyFamily::AudioCapture | CopyFamily::BitmapBgra8 => "read", - CopyFamily::MediaBuffer => "read-write", - }, - owner: match family { - CopyFamily::AudioRender | CopyFamily::AudioCapture => "audio-service-origin", - CopyFamily::BitmapBgra8 => "acquired-interface", - CopyFamily::MediaBuffer => "receiver", - }, - acquired_hresult: 0, - empty_hresult: (family == CopyFamily::AudioCapture).then_some(0x08890001), - kind, - receiver, - acquire, - queries, - finalize, - extent, - finalization, - sta_only: family == CopyFamily::BitmapBgra8, - audio_origin_required: matches!( - family, - CopyFamily::AudioRender | CopyFamily::AudioCapture - ), - }, - )), })) } diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs b/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs index 198955ad..c80c037a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs @@ -6,14 +6,12 @@ use super::super::{ CopyArguments, CopyResult, ProjectedBorrowedCopy, ProjectedBorrowedOperation, ProjectedBorrowedStorage, }, - model::borrowed::{CopyFamily, ValidatedStorage}, + model::borrowed::ValidatedStorage, }; +use dynwinrt_com_contracts::{InputKind, ResultMapping}; pub(super) fn project(storage: ValidatedStorage) -> Result { - let copy_only = storage - .copy - .as_ref() - .is_some_and(|(family, _)| *family != CopyFamily::BitmapBgra8); + let copy_only = storage.copy.as_ref().is_some_and(|copy| copy.copy_only); let context_effects = storage .effects .into_iter() @@ -22,7 +20,7 @@ pub(super) fn project(storage: ValidatedStorage) -> Result Result>()?; let copy = storage .copy - .map(|(family, plan)| { - let op = |name, arguments, result| ProjectedBorrowedOperation { - name, - runtime_method: name, - arguments, - result, - }; - let operations = match family { - CopyFamily::AudioRender => vec![ - op("writeFramesCopy", CopyArguments::Bytes, CopyResult::Void), - op("writeSilence", CopyArguments::Frames, CopyResult::Void), - ], - CopyFamily::AudioCapture => vec![op( - "readPacketCopy", - CopyArguments::None, - CopyResult::Packet, - )], - CopyFamily::BitmapBgra8 => vec![op( - "readLockedBgra8Copy", - CopyArguments::Rectangle, - CopyResult::Bitmap, - )], - CopyFamily::MediaBuffer => vec![ - op("readCopy", CopyArguments::None, CopyResult::Bytes), - op("replaceCopy", CopyArguments::Bytes, CopyResult::Void), - ], - }; + .map(|plan| { + let operations = plan + .operations + .iter() + .map(|op| ProjectedBorrowedOperation { + name: op.api.name(), + runtime_method: op.api.name(), + arguments: match op.arguments { + InputKind::None => CopyArguments::None, + InputKind::Bytes => CopyArguments::Bytes, + InputKind::Frames => CopyArguments::Frames, + InputKind::Rectangle => CopyArguments::Rectangle, + }, + result: match op.result { + ResultMapping::Void => CopyResult::Void, + ResultMapping::Bytes => CopyResult::Bytes, + ResultMapping::Packet { .. } => CopyResult::Packet, + ResultMapping::Bitmap { .. } => CopyResult::Bitmap, + }, + }) + .collect(); Ok::<_, String>(ProjectedBorrowedCopy { descriptor: serde_json::to_string(&plan).map_err(|error| error.to_string())?, operations, @@ -80,6 +72,32 @@ mod tests { }; use crate::com_metadata::{borrowed as evidence, parse_com_interface}; + fn compare_public_baseline(name: &str, declarations: &str) { + let Ok(root) = std::env::var("DYNWINRT_BORROWED_DECLARATION_BASELINE") else { + return; + }; + fn find(root: &std::path::Path, name: &str) -> Option { + for file in std::fs::read_dir(root).unwrap() { + let file = file.unwrap(); + let path = file.path(); + if file.file_type().unwrap().is_dir() { + if let Some(found) = find(&path, name) { + return Some(found); + } + } else if file.file_name() == format!("{name}.d.ts").as_str() { + return Some(path); + } + } + None + } + let path = find(std::path::Path::new(&root), name).expect("baseline declaration"); + assert_eq!( + std::fs::read_to_string(path).unwrap(), + declarations, + "{name} public declarations must remain byte-for-byte unchanged" + ); + } + #[test] fn borrowed_copy_projection_is_bounded_and_renderer_is_ir_driven() { let Ok(paths) = std::env::var("DYNWINRT_WIN32_WINMD") else { @@ -105,6 +123,7 @@ mod tests { ] { let metadata = parse_com_interface(&paths, namespace, name).unwrap(); let output = generate_com_interface_files(&metadata, &paths).unwrap(); + compare_public_baseline(name, &output.dts); for method in public_methods { assert!(output.js.contains(&format!(" {method}("))); assert!(output.dts.contains(&format!(" {method}("))); @@ -152,6 +171,7 @@ mod tests { if name == "IAudioClient3" { 3 } else { 2 } ); let output = generate_complete_com_interface_files(&metadata, &paths).unwrap(); + compare_public_baseline(name, &output.dts); assert!(output.js.contains(".withContextEffect(")); assert!( output.js.contains("audio-initialize") && output.js.contains("audio-get-service") diff --git a/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs b/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs index 9859fc60..f477a118 100644 --- a/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs @@ -1,328 +1,57 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -//! Exact storage/context evidence. These selectors are not general pointer rules. +//! Verifies configured WinMD against the shared reviewed COM registry. +//! Registry records, not interface-name branches, select copy capabilities. use super::{ComInterfaceMeta, RawComMethod, raw_method_fingerprint}; use crate::contract_registry::{ ContractKind, ExactEntrySelector, ExactFamilyId, ExactRegistryEntry, }; +pub use dynwinrt_com_contracts::{Evidence, METADATA_SHA256}; +use dynwinrt_com_contracts::{InterfaceRecord, registry}; use sha2::{Digest, Sha256}; -pub const METADATA_SHA256: &str = - "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D"; +#[cfg(test)] pub const AUDIO: &str = "Windows.Win32.Media.Audio"; +#[cfg(test)] pub const WIC: &str = "Windows.Win32.Graphics.Imaging"; +#[cfg(test)] pub const MF: &str = "Windows.Win32.Media.MediaFoundation"; -pub const CLIENT_IID: &str = "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2"; -pub const CLIENT2_IID: &str = "726778cd-f60a-4eda-82de-e47610cd78aa"; -pub const CLIENT3_IID: &str = "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42"; -pub const RENDER_IID: &str = "f294acfc-3146-4483-a7bf-addca7c260e2"; -pub const CAPTURE_IID: &str = "c8adbd64-e71e-48a0-a4de-185c395cd317"; -pub const BITMAP_IID: &str = "00000121-a8f2-4877-ba0a-fd2b6645fb94"; -pub const LOCK_IID: &str = "00000123-a8f2-4877-ba0a-fd2b6645fb94"; -pub const MF_IID: &str = "045fa593-8799-42b8-bc8d-8968c6453507"; -#[derive(Debug)] -pub struct Evidence { - pub namespace: &'static str, - pub interface: &'static str, - pub iid: &'static str, - pub method: &'static str, - pub slot: usize, - pub fingerprint: &'static str, - pub effect: Option<&'static str>, - pub citation: &'static str, +pub fn all_evidence() -> &'static [Evidence] { + ®istry().evidence } -macro_rules! storage { - ($ns:expr, $interface:literal, $iid:expr, $method:literal, $slot:literal, $hash:literal, $citation:literal) => { - Evidence { - namespace: $ns, - interface: $interface, - iid: $iid, - method: $method, - slot: $slot, - fingerprint: $hash, - effect: None, - citation: $citation, - } +pub(crate) fn catalog_entry(entry: &Evidence) -> ExactRegistryEntry { + let family = if entry.effect.is_some() { + ExactFamilyId::AudioContext + } else { + ExactFamilyId::BorrowedCopy }; -} - -// Fingerprints include native layouts, directions, optional/Const flags, -// NativeArrayInfo, return convention and all existing exact-contract evidence. -pub const EVIDENCE: &[Evidence] = &[ - Evidence { - namespace: AUDIO, - interface: "IAudioClient", - iid: CLIENT_IID, - method: "Initialize", - slot: 3, - fingerprint: "7F14AD1E6E6E178A91283B68002988D362898FCAC97823B866D61FAFF5766039", - effect: Some("audio-initialize"), - citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-initialize", - }, - Evidence { - namespace: AUDIO, - interface: "IAudioClient", - iid: CLIENT_IID, - method: "GetService", - slot: 14, - fingerprint: "6362D65B61F18446F4E990C84DA998C4A7DE08517C7405981DF823854227CA7E", - effect: Some("audio-get-service"), - citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getservice", - }, - Evidence { - namespace: AUDIO, - interface: "IAudioClient3", - iid: CLIENT3_IID, - method: "InitializeSharedAudioStream", - slot: 20, - fingerprint: "08879857019485B6813E45F4BEB2941E4D83ACF80CA55AA4538F50B08C1B9531", - effect: Some("audio-initialize-shared"), - citation: "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream", - }, - storage!( - AUDIO, - "IAudioClient", - CLIENT_IID, - "GetBufferSize", - 4, - "9F0C09DD69B785A9B4A339ECD2A1970E8574BDBA0F173E3ACF630407A9AB14BE", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getbuffersize" - ), - storage!( - AUDIO, - "IAudioRenderClient", - RENDER_IID, - "GetBuffer", - 3, - "E99E87341B5820E896608A563B67ABCF2A0F9BD833202788950D9FAE8F69E2DB", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-getbuffer" - ), - storage!( - AUDIO, - "IAudioRenderClient", - RENDER_IID, - "ReleaseBuffer", - 4, - "C79B7868B7940E7D879DC90CA1BAC56E386DA7C8E0F7790DFAB7FB8971E0D767", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiorenderclient-releasebuffer" - ), - storage!( - AUDIO, - "IAudioCaptureClient", - CAPTURE_IID, - "GetBuffer", - 3, - "DDD954B2807361F2D50D38C8054846A02577E820B6D42E0B82130F785AA3E370", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer" - ), - storage!( - AUDIO, - "IAudioCaptureClient", - CAPTURE_IID, - "ReleaseBuffer", - 4, - "82D3C575E5031A345E01026F01E600C8887B081DF6F79CA514B49B78F01E5E17", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-releasebuffer" - ), - storage!( - AUDIO, - "IAudioCaptureClient", - CAPTURE_IID, - "GetNextPacketSize", - 5, - "C540B744DB900C7D5EDAD03422FC17E7034A822832F4A39DC2DD8519B0978209", - "https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getnextpacketsize" - ), - storage!( - WIC, - "IWICBitmapSource", - "00000120-a8f2-4877-ba0a-fd2b6645fb94", - "GetSize", - 3, - "F0CBF53A188710273FE737C1A06CDA40FA799C4326F3CA9BF68988E5072B5DA2", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getsize" - ), - storage!( - WIC, - "IWICBitmapSource", - "00000120-a8f2-4877-ba0a-fd2b6645fb94", - "GetPixelFormat", - 4, - "D45F675B2B76A3A9BE908AFBAC03BF4CEC2BD5D8162C1BF28F01FA558B2B6F98", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getpixelformat" - ), - storage!( - WIC, - "IWICBitmapSource", - "00000120-a8f2-4877-ba0a-fd2b6645fb94", - "GetResolution", - 5, - "3545A1714671B8C7223BF21693848300001272CDD14E1BE6C188680EA5BD75DD", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-getresolution" - ), - storage!( - WIC, - "IWICBitmapSource", - "00000120-a8f2-4877-ba0a-fd2b6645fb94", - "CopyPalette", - 6, - "CBBEDB597008ED4EA9032EE361F19AC676DA973DA93A1CB8B0B7D67E24CA4A8C", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypalette" - ), - storage!( - WIC, - "IWICBitmapSource", - "00000120-a8f2-4877-ba0a-fd2b6645fb94", - "CopyPixels", - 7, - "78BA461831509B5574CB3F8485FE071B875E1AA1FF4ABC4EBB4ADE74A1AE0A9A", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmapsource-copypixels" - ), - storage!( - WIC, - "IWICBitmap", - BITMAP_IID, - "Lock", - 8, - "BE432E367AC62157C546DB3F21AE11B89025F930D4AE397ECC5B6A6F2016D154", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-lock" - ), - storage!( - WIC, - "IWICBitmap", - BITMAP_IID, - "SetPalette", - 9, - "D714FBE65EE1E239F04D9046C2270572CC8DE81094FCE549D81FF50242BC6F8F", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setpalette" - ), - storage!( - WIC, - "IWICBitmap", - BITMAP_IID, - "SetResolution", - 10, - "394965547E9C14CB338B9AD84677C27CA1D54BF22E4CDBA79A46D26F31C25EB6", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmap-setresolution" - ), - storage!( - WIC, - "IWICBitmapLock", - LOCK_IID, - "GetSize", - 3, - "5FBF3161D277C77796793A167F68999C7B678A182FCBB823CD721DC4BAC83F64", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getsize" - ), - storage!( - WIC, - "IWICBitmapLock", - LOCK_IID, - "GetStride", - 4, - "0DC2598054C7BCB1D19940355D5BE568D508B332E269D00956BAF22DC854F799", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getstride" - ), - storage!( - WIC, - "IWICBitmapLock", - LOCK_IID, - "GetDataPointer", - 5, - "FB4F6B8BD302FCA2BB91B231BF957E10D37AC979C39A88992E2526E53349F66C", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getdatapointer" - ), - storage!( - WIC, - "IWICBitmapLock", - LOCK_IID, - "GetPixelFormat", - 6, - "A065B19968592FDA319A1A9DAC7EC1EB51CE63F5D3FFA62C6DD38E92742065E6", - "https://learn.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-iwicbitmaplock-getpixelformat" - ), - storage!( - MF, - "IMFMediaBuffer", - MF_IID, - "Lock", - 3, - "1B9E2C63825F73EE5599F05E9EA180D52FD22F02EDD33BB23028711DDF335172", - "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-lock" - ), - storage!( - MF, - "IMFMediaBuffer", - MF_IID, - "Unlock", - 4, - "83FB2903C23EBD4BB98C182C6575135225ABD0C3EA78183CDADFB3B027B8107B", - "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-unlock" - ), - storage!( - MF, - "IMFMediaBuffer", - MF_IID, - "GetCurrentLength", - 5, - "AABA562CD26F16571A75D54894E001700500994E98949B4E7A7DA1B6CDE61862", - "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getcurrentlength" - ), - storage!( - MF, - "IMFMediaBuffer", - MF_IID, - "SetCurrentLength", - 6, - "75AB892B1685032D840B1E5FECB9CD9A87F8E1865492D24796996674372864CA", - "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-setcurrentlength" - ), - storage!( - MF, - "IMFMediaBuffer", - MF_IID, - "GetMaxLength", - 7, - "738D4850D037E6B9F76F28C7D0403B4D9BDF97F3B04C9B8E5A0EFBA18A3A962C", - "https://learn.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfmediabuffer-getmaxlength" - ), -]; - -impl Evidence { - pub(crate) fn entry(&self) -> ExactRegistryEntry { - let family = if self.effect.is_some() { - ExactFamilyId::AudioContext + let selector = ExactEntrySelector { + namespace: entry.namespace.clone(), + interface: entry.interface.clone(), + iid: entry.iid.clone(), + method: entry.method.clone(), + slot: entry.slot, + parameter: None, + }; + ExactRegistryEntry { + entry_id: selector.entry_id(family), selector, family_id: family, + contract_kind: if entry.effect.is_some() { ContractKind::ContextualEffect } else { ContractKind::BorrowedStorage }, + source_fingerprint: entry.fingerprint.clone(), + reason: if entry.effect.is_some() { + "Only the actual successful metadata-described native call may create immutable initialization or service-origin provenance" } else { - ExactFamilyId::BorrowedCopy - }; - let selector = ExactEntrySelector { - namespace: self.namespace.into(), - interface: self.interface.into(), - iid: self.iid.into(), - method: self.method.into(), - slot: self.slot, - parameter: None, - }; - ExactRegistryEntry { - entry_id: selector.entry_id(family), selector, family_id: family, - contract_kind: if self.effect.is_some() { ContractKind::ContextualEffect } else { ContractKind::BorrowedStorage }, - source_fingerprint: self.fingerprint.into(), - reason: if self.effect.is_some() { - "Only the actual successful metadata-described native call may create immutable initialization or service-origin provenance" - } else { - "Bounded owned-copy storage/extent/finalization plan; native borrowed bytes and unsupported methods are not public" - }.into(), - citation: self.citation.into(), - } + "Bounded owned-copy storage/extent/finalization plan; native borrowed bytes and unsupported methods are not public" + }.into(), + citation: entry.citation.clone(), } } pub fn evidence_for(raw: &RawComMethod) -> Result, String> { - let selected = EVIDENCE.iter().find(|entry| { + let selected = all_evidence().iter().find(|entry| { entry.namespace == raw.declaring_namespace && entry.interface == raw.declaring_interface && entry.method == raw.metadata_name @@ -340,35 +69,39 @@ pub fn evidence_for(raw: &RawComMethod) -> Result, Str Ok(selected) } +fn candidate(meta: &ComInterfaceMeta) -> Option<&'static InterfaceRecord> { + registry().interfaces.iter().find(|entry| { + entry.namespace == meta.interface.namespace && entry.name == meta.interface.name + }) +} + pub fn is_audio_context(meta: &ComInterfaceMeta) -> bool { - meta.interface.namespace == AUDIO - && matches!( - meta.interface.name.as_str(), - "IAudioClient" | "IAudioClient2" | "IAudioClient3" - ) + candidate(meta).is_some_and(|entry| entry.context) } pub fn is_bounded_copy(meta: &ComInterfaceMeta) -> bool { - matches!( - ( - meta.interface.namespace.as_str(), - meta.interface.name.as_str() - ), - (AUDIO, "IAudioRenderClient" | "IAudioCaptureClient") - | (WIC, "IWICBitmap") - | (MF, "IMFMediaBuffer") - ) + // Detect a drifted IID as a candidate too, so validation rejects instead of + // falling back to a projection without its required copy/context evidence. + candidate(meta).is_some_and(|entry| { + registry() + .copies + .iter() + .any(|copy| copy.receiver == entry.identity()) + }) } pub fn is_copy_only(meta: &ComInterfaceMeta) -> bool { - is_bounded_copy(meta) && meta.interface.name != "IWICBitmap" + registry() + .select( + &meta.interface.namespace, + &meta.interface.name, + &meta.interface.iid, + ) + .is_some_and(|copy| copy.copy_only) } pub(crate) fn catalog_entries(meta: &ComInterfaceMeta) -> Vec { - if !is_audio_context(meta) - && !is_bounded_copy(meta) - && !(meta.interface.namespace == WIC && meta.interface.name == "IWICBitmapLock") - { + if !candidate(meta).is_some_and(|entry| entry.catalog) { return vec![]; } meta.raw_methods @@ -376,13 +109,11 @@ pub(crate) fn catalog_entries(meta: &ComInterfaceMeta) -> Vec Result<(), String> { - // Hash only relevant projections, not every interface in a census. Unknown - // metadata versions need reviewed selectors, never a name-based fallback. let matching = paths .split(';') .filter(|path| !path.trim().is_empty()) @@ -399,51 +130,20 @@ pub fn require_metadata_hash(paths: &str) -> Result<(), String> { } pub fn validate_interface(meta: &ComInterfaceMeta) -> Result<(), String> { - let (iid, bases, base_iids, own_start, last) = match ( - meta.interface.namespace.as_str(), - meta.interface.name.as_str(), - ) { - (AUDIO, "IAudioClient") => (CLIENT_IID, vec!["IUnknown"], vec![], 3, 14), - (AUDIO, "IAudioClient2") => ( - CLIENT2_IID, - vec!["IAudioClient", "IUnknown"], - vec![CLIENT_IID], - 15, - 17, - ), - (AUDIO, "IAudioClient3") => ( - CLIENT3_IID, - vec!["IAudioClient2", "IAudioClient", "IUnknown"], - vec![CLIENT2_IID, CLIENT_IID], - 18, - 20, - ), - (AUDIO, "IAudioRenderClient") => (RENDER_IID, vec!["IUnknown"], vec![], 3, 4), - (AUDIO, "IAudioCaptureClient") => (CAPTURE_IID, vec!["IUnknown"], vec![], 3, 5), - (WIC, "IWICBitmap") => ( - BITMAP_IID, - vec!["IWICBitmapSource", "IUnknown"], - vec!["00000120-a8f2-4877-ba0a-fd2b6645fb94"], - 8, - 10, - ), - (WIC, "IWICBitmapLock") => (LOCK_IID, vec!["IUnknown"], vec![], 3, 6), - (MF, "IMFMediaBuffer") => (MF_IID, vec!["IUnknown"], vec![], 3, 7), - _ => return Err("Not an exact borrowed-copy/context interface".into()), - }; + let entry = candidate(meta).ok_or("Not an exact borrowed-copy/context interface")?; let methods = meta .raw_methods .as_deref() .ok_or("Borrowed-copy/context raw evidence is absent")?; - if meta.interface.iid != iid + if meta.interface.iid != entry.iid || !meta.is_iunknown_rooted || meta.base_offset != 3 - || meta.own_methods_start != own_start - || meta.base_chain != bases - || meta.base_iids != base_iids + || meta.own_methods_start != entry.own_start + || meta.base_chain != entry.bases + || meta.base_iids != entry.base_iids || meta.interface.generic_piid.is_some() || !meta.interface.generic_args.is_empty() - || methods.len() != last - 2 + || methods.len() != entry.last - 2 || meta.interface.methods.len() != methods.len() || methods .iter() @@ -456,28 +156,23 @@ pub fn validate_interface(meta: &ComInterfaceMeta) -> Result<(), String> { )); } for raw in methods { - let entry = evidence_for(raw)?; - if !is_audio_context(meta) && entry.is_none() { + let evidence = evidence_for(raw)?; + if (!entry.context || entry.required_evidence.contains(&raw.vtable_index)) + && evidence.is_none() + { return Err(format!( - "Absent borrowed-storage evidence at slot {}", + "Absent borrowed-storage/context evidence at slot {}", raw.vtable_index )); } } - if is_audio_context(meta) { - for slot in [3, 4, 14].into_iter().chain((last == 20).then_some(20)) { - let raw = &methods[slot - 3]; - if evidence_for(raw)?.is_none() { - return Err(format!("Absent audio context evidence at slot {slot}")); - } - } - } Ok(()) } #[cfg(test)] mod tests { use super::*; + #[test] fn borrowed_copy_metadata_evidence_and_fail_closed_drift() { let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { @@ -498,7 +193,7 @@ mod tests { drift.raw_methods = None; assert!(validate_interface(&drift).is_err()); let mut drift = meta.clone(); - drift.interface.iid = CLIENT_IID.into(); + drift.interface.iid = "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2".into(); assert!(validate_interface(&drift).is_err()); for index in 0..meta.raw_methods.as_ref().unwrap().len() { if evidence_for(&meta.raw_methods.as_ref().unwrap()[index]) diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index a6fe921c..801823cc 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -441,9 +441,9 @@ pub(crate) fn validate_exact_entry_catalog( pub(crate) fn statically_declared_exact_entry_ids() -> Result, String> { let mut ids = BTreeSet::new(); ids.extend( - crate::com_metadata::borrowed::EVIDENCE + crate::com_metadata::borrowed::all_evidence() .iter() - .map(|entry| entry.entry().entry_id), + .map(|entry| crate::com_metadata::borrowed::catalog_entry(entry).entry_id), ); ids.extend( crate::com_safe_array_registry::all_safe_array_evidence() diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 063c17b1..cb18652d 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -176,7 +176,7 @@ enum Commands { } const COM_MANIFEST_FILE: &str = ".dynwinrt-com-manifest.json"; -const COM_MANIFEST_VERSION: u32 = 4; +const COM_MANIFEST_VERSION: u32 = 5; #[derive(Debug, Default, Deserialize, Serialize)] struct ComGenerationManifest { @@ -9002,7 +9002,7 @@ mod tests { fn com_context_manifest_mismatch_requires_clean_regeneration() { let output = test_directory("com-context-manifest").join("com"); fs::create_dir_all(&output).unwrap(); - for version in [1, 2, 3] { + for version in [1, 2, 3, 4] { let content = serde_json::to_string(&ComGenerationManifest { version, roots: BTreeMap::new(), From 3d3e8c4c5881103327b20701276915b8f35116d1 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 8 Sep 2026 21:32:55 +0800 Subject: [PATCH 3/4] Guard managed COM arguments before native dispatch Retain shared apartment and lifecycle contexts across interface aliases and supported containers. Recheck receivers and inputs after native coercion, preserve deferred WinRT lifetime behavior, and reject poisoned buffer inputs before IMFSample can retain them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- bindings/js/__test__/borrowed-copy-child.cjs | 45 +- bindings/js/__test__/borrowed-copy.e2e.ts | 8 +- bindings/js/src/com.rs | 276 ++++++-- bindings/js/src/com_input.rs | 397 +++++++++++ bindings/js/src/com_input_tests.rs | 653 ++++++++++++++++++ bindings/js/src/lib.rs | 490 +++++++------ crates/dynwinrt/Cargo.toml | 2 +- crates/dynwinrt/src/call.rs | 32 +- crates/dynwinrt/src/com.rs | 205 +++++- crates/dynwinrt/src/com_automation.rs | 15 + crates/dynwinrt/src/com_borrowed.rs | 26 +- .../dynwinrt/src/com_borrowed_test_support.rs | 9 +- crates/dynwinrt/src/native_call.rs | 132 ++-- docs/architecture/classic-com-support.md | 15 + docs/guides/windows/classic-com-usage.md | 7 + 15 files changed, 1983 insertions(+), 329 deletions(-) create mode 100644 bindings/js/src/com_input.rs create mode 100644 bindings/js/src/com_input_tests.rs diff --git a/bindings/js/__test__/borrowed-copy-child.cjs b/bindings/js/__test__/borrowed-copy-child.cjs index c646e83b..adcb95b1 100644 --- a/bindings/js/__test__/borrowed-copy-child.cjs +++ b/bindings/js/__test__/borrowed-copy-child.cjs @@ -10,7 +10,8 @@ const com = require('../dist/com.js') const unsafe = require('../dist/com-unsafe.js') const generatedRoot = process.env.DYNWINRT_BORROWED_GENERATED const generated = require(join(generatedRoot, 'com', 'index.js')) -const { IAudioClient, IAudioClient3, IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer } = generated +const { IAudioClient, IAudioClient3, IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer, IMFSample } = + generated const { DynComAudioFormat, projectAs } = com const scenario = process.argv[2] @@ -166,6 +167,29 @@ if (scenario === 'audio') { const f = fixture() const media = wrap(f, 'media', IMFMediaBuffer) const alias = wrap(f, 'mediaUnknown', IMFMediaBuffer) + const input = f.object('media') + const inputAlias = f.object('mediaUnknown') + const sample = wrap(f, 'sample', IMFSample) + sample.addBuffer(inputAlias) + assert.equal(sample.getBufferCount(), 1) + const inputArray = native.DynCom.interfaceArray(IMFMediaBuffer.IID, [inputAlias]) + const inputVariant = native.DynComVariant.unknown(inputAlias) + const iid = native.WinGuid.parse('109302ce-8b8e-4e90-ad9c-5b988abc94b1') + const receiverType = native.DynCom.registerIUnknownInterface('ArgumentGuardReceiver', iid).addMethodAt( + 3, + 'Accept', + new native.DynComMethodSig().addIn(native.DynCom.interfaceType(IMFMediaBuffer.IID)), + ) + let calls = 0 + const receiver = native.DynCom.createIUnknownSink(receiverType, (_slot, argument) => { + calls++ + argument.release() + return 0 + }) + native.DynCom.bindComObject(receiver) + const accept = receiverType.method(3) + accept.invokeAll(receiver, [inputAlias]) + assert.equal(calls, 1) const copy = media.readCopy() assert.deepEqual(copy, Buffer.from([0, 1, 2, 3])) media.replaceCopy(Buffer.from([9, 8, 7])) @@ -182,10 +206,29 @@ if (scenario === 'audio') { f.configure('mediaUnlockHr', 0x80004005) assert.throws(() => media.readCopy()) const unlocks = count(f, 'media.unlock') + assert.throws(() => sample.addBuffer(input), /poisoned/i) + assert.throws(() => sample.addBuffer(inputAlias), /poisoned/i) + assert.equal(sample.getBufferCount(), 1, 'poisoned input must not be retained by IMFSample') + sample.removeAllBuffers() + sample.release() + for (const value of [input, inputAlias, inputArray]) { + assert.throws(() => accept.invokeAll(receiver, [value]), /poisoned/i) + } + assert.throws(() => native.DynCom.variant(inputVariant), /poisoned/i) + assert.throws(() => native.DynCom.interfaceArray(IMFMediaBuffer.IID, [inputAlias]), /poisoned/i) + assert.equal(calls, 1, 'poisoned arguments must not enter the other receiver') media.release() assert.throws(() => alias.readCopy(), /poisoned/i) assert.equal(count(f, 'media.unlock'), unlocks) alias.release() + input.release() + inputAlias.release() + inputVariant.release() + f.releaseOwners() + assert.throws(() => accept.invokeAll(receiver, [inputArray]), /poisoned/i) + inputArray.release() + assert.equal(count(f, 'drop.media'), 1) + receiver.release() } else if (scenario === 'wic' || scenario === 'mta') { const f = fixture() const bitmap = wrap(f, 'bitmap', IWICBitmap) diff --git a/bindings/js/__test__/borrowed-copy.e2e.ts b/bindings/js/__test__/borrowed-copy.e2e.ts index 829ccd8d..9858dce8 100644 --- a/bindings/js/__test__/borrowed-copy.e2e.ts +++ b/bindings/js/__test__/borrowed-copy.e2e.ts @@ -24,7 +24,7 @@ test.before((t) => { '--winmd', winmd!, '--class-name', - 'Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.Media.Audio.IAudioClient3,Windows.Win32.Media.Audio.IAudioRenderClient,Windows.Win32.Media.Audio.IAudioCaptureClient,Windows.Win32.Graphics.Imaging.IWICBitmap,Windows.Win32.Media.MediaFoundation.IMFMediaBuffer', + 'Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.Media.Audio.IAudioClient3,Windows.Win32.Media.Audio.IAudioRenderClient,Windows.Win32.Media.Audio.IAudioCaptureClient,Windows.Win32.Graphics.Imaging.IWICBitmap,Windows.Win32.Media.MediaFoundation.IMFMediaBuffer,Windows.Win32.Media.MediaFoundation.IMFSample', '--output', output, ] @@ -42,11 +42,15 @@ test.before((t) => { writeFileSync( join(output, 'borrowed-types.mts'), [ - "import { IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer } from './com/index.js'", + "import { IAudioRenderClient, IAudioCaptureClient, IWICBitmap, IMFMediaBuffer, IMFSample } from './com/index.js'", + "import type { DynWinRtValue } from '@microsoft/dynwinrt/com'", 'declare const render: IAudioRenderClient', 'declare const capture: IAudioCaptureClient', 'declare const bitmap: IWICBitmap', 'declare const media: IMFMediaBuffer', + 'declare const sample: IMFSample', + 'declare const mediaValue: DynWinRtValue', + 'sample.addBuffer(mediaValue)', 'render.writeFramesCopy(new Uint8Array(8)); render.writeSilence(2)', 'const packet = capture.readPacketCopy(); if (packet?.kind === "data") packet.data?.subarray(0)', 'const pixels: Buffer = bitmap.readLockedBgra8Copy({ x: 0, y: 0, width: 2, height: 2 }).data', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index f94cf16b..1371ee33 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -8,6 +8,10 @@ use windows::core::{IUnknown, Interface as _, GUID}; use super::{com_raw::DynComRaw, DynWinRTType, DynWinRTValue, WinGUID, TABLE}; +#[cfg(all(test, feature = "test-hooks"))] +#[path = "com_input_tests.rs"] +mod input_tests; + #[allow(dead_code)] pub(super) enum NativePointerOwner { Uint8Array { @@ -72,7 +76,7 @@ impl AutomationValue { } } - fn ensure_owner_thread(&self) -> napi::Result<()> { + pub(super) fn ensure_owner_thread(&self) -> napi::Result<()> { if matches!(self.value, Some(AutomationValueKind::Bstr(_))) || std::thread::current().id() == self.owner_thread { @@ -1471,16 +1475,82 @@ pub(super) fn collect_native_invocation_leases( }) } +#[cfg(test)] pub(super) fn with_com_invocation_args( args: &[&DynWinRTValue], invoke: impl FnOnce(&[dynwinrt::com::Value]) -> napi::Result, ) -> napi::Result { + with_com_invocation_args_guarded(args, |args, _| invoke(args)) +} + +struct ComInputGuard { + pins: Vec, + bindings: Vec, +} + +impl ComInputGuard { + fn pin(args: &[&DynWinRTValue]) -> napi::Result { + // Admit the whole batch before cloning even its first interface reference. + for arg in args { + arg.check_com_input_state()?; + } + Ok(Self { + pins: args + .iter() + .filter_map(|arg| arg.7.as_ref()) + .map(super::com_input::InputBindings::pin) + .collect::>>()?, + bindings: args + .iter() + .filter_map(|arg| arg.6.as_ref().cloned()) + .collect(), + }) + } + + fn check(&self) -> napi::Result<()> { + for pin in &self.pins { + pin.ensure_idle()?; + } + for binding in &self.bindings { + binding.ensure_idle()?; + } + Ok(()) + } + + fn check_native(&self) -> windows::core::Result<()> { + self.check().map_err(|error| { + windows::core::Error::new( + windows::core::HRESULT(0x80070057u32 as i32), + error.reason.as_str(), + ) + }) + } +} + +fn admit_com_inputs(args: &[&DynWinRTValue]) -> napi::Result { + let guard = ComInputGuard::pin(args)?; + for arg in args { + arg.admit_com_input()?; + } + guard.check()?; + Ok(guard) +} + +fn with_com_invocation_args_guarded( + args: &[&DynWinRTValue], + invoke: impl FnOnce( + &[dynwinrt::com::Value], + &dyn Fn() -> windows::core::Result<()>, + ) -> napi::Result, +) -> napi::Result { + let guard = admit_com_inputs(args)?; let _leases = collect_native_invocation_leases(args)?; - let args = args + let converted = args .iter() .map(|arg| arg.to_com_value()) .collect::>>()?; - invoke(&args) + guard.check()?; + invoke(&converted, &|| guard.check_native()) } pub(super) fn take_native_output_pointer( @@ -1963,6 +2033,7 @@ fn optional_com_object( ) -> napi::Result> { value .map(|value| { + value.admit_com_input()?; value .0 .as_object() @@ -2391,19 +2462,28 @@ impl DynComMethodHandle { ) -> napi::Result> { if !self.0.has_context_effect() { obj.ensure_tracked_com_idle()?; - let raw = obj + let receiver_guard = ComInputGuard::pin(&[obj])?; + let view = obj .0 .as_object() - .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))? - .as_raw(); - return with_com_invocation_args(&args, |args| { - unsafe { self.0.invoke_values_with_output_kinds(raw, args) }.map_err(com_error) - }) - .map(|values| { - values - .into_iter() - .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) - .collect() + .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))?; + receiver_guard.check()?; + return with_com_invocation_args_guarded(&args, |args, check| { + unsafe { + self + .0 + .invoke_values_with_output_kinds_guarded(view.as_raw(), args, || { + receiver_guard.check_native()?; + check() + }) + } + .map_err(com_error) + .map(|values| { + values + .into_iter() + .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) + .collect() + }) }); } let context = obj.com_context()?; @@ -2412,11 +2492,11 @@ impl DynComMethodHandle { .as_object() .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))? .clone(); - let result = with_com_invocation_args(&args, |args| { - unsafe { dynwinrt::com::borrowed::invoke_managed(&self.0, &context, &view, args) } - .map_err(com_error) - })?; - Ok( + with_com_invocation_args_guarded(&args, |args, check| { + let result = unsafe { + dynwinrt::com::borrowed::invoke_managed_guarded(&self.0, &context, &view, args, check) + } + .map_err(com_error)?; result .values .into_iter() @@ -2427,20 +2507,21 @@ impl DynComMethodHandle { } Ok(value) }) - .collect::>>()?, - ) + .collect::>>() + }) } #[napi] pub fn get_string(&self, obj: &DynWinRTValue) -> napi::Result { obj.ensure_com_apartment()?; obj.ensure_tracked_com_idle()?; - let raw = obj + let receiver_guard = ComInputGuard::pin(&[obj])?; + let view = obj .0 .as_object() - .ok_or_else(|| napi::Error::from_reason("getString() requires a COM object"))? - .as_raw(); - unsafe { self.0.call_getter_hstring(raw) } + .ok_or_else(|| napi::Error::from_reason("getString() requires a COM object"))?; + receiver_guard.check()?; + unsafe { self.0.call_getter_hstring(view.as_raw()) } .map(|value| value.to_string()) .map_err(|error| napi::Error::from_reason(error.message())) } @@ -2482,31 +2563,38 @@ impl DynComMethodHandle { ) -> napi::Result { obj.ensure_com_apartment()?; obj.ensure_tracked_com_idle()?; - let raw = obj + let receiver_guard = ComInputGuard::pin(&[obj])?; + let view = obj .0 .as_object() - .ok_or_else(|| napi::Error::from_reason("invokeDispatch() requires a COM object"))? - .as_raw(); - let result = with_com_invocation_args(&args, |args| { - unsafe { self.0.invoke_dispatch(raw, args) }.map_err(com_error) - })?; - let (hresult, result, excep_info, arg_err, finalization_error) = result.into_parts(); - Ok(DynComDispatchInvokeResult { - hresult: hresult.0, - result: result.map(|value| { - DynWinRTValue::from_com_value( - dynwinrt::com::Value::Variant(value), - dynwinrt::com::PointerOutputKind::None, - ) - }), - excep_info: excep_info.map(|value| { - DynWinRTValue::from_com_value( - dynwinrt::com::Value::ExcepInfo(value), - dynwinrt::com::PointerOutputKind::None, - ) - }), - arg_err, - finalization_error: finalization_error.map(|error| error.message()), + .ok_or_else(|| napi::Error::from_reason("invokeDispatch() requires a COM object"))?; + receiver_guard.check()?; + with_com_invocation_args_guarded(&args, |args, check| { + let result = unsafe { + self.0.invoke_dispatch_guarded(view.as_raw(), args, || { + receiver_guard.check_native()?; + check() + }) + } + .map_err(com_error)?; + let (hresult, result, excep_info, arg_err, finalization_error) = result.into_parts(); + Ok(DynComDispatchInvokeResult { + hresult: hresult.0, + result: result.map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Variant(value), + dynwinrt::com::PointerOutputKind::None, + ) + }), + excep_info: excep_info.map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::ExcepInfo(value), + dynwinrt::com::PointerOutputKind::None, + ) + }), + arg_err, + finalization_error: finalization_error.map(|error| error.message()), + }) }) } } @@ -2540,24 +2628,30 @@ impl DynComRaw { dispatch.entered.set(false); obj.ensure_com_apartment()?; obj.ensure_tracked_com_idle()?; - let raw = obj + let receiver_guard = ComInputGuard::pin(&[obj])?; + let view = obj .0 .as_object() - .ok_or_else(|| napi::Error::from_reason("invokeAllTracked() requires a COM object"))? - .as_raw(); - with_com_invocation_args(&args, |args| { + .ok_or_else(|| napi::Error::from_reason("invokeAllTracked() requires a COM object"))?; + receiver_guard.check()?; + with_com_invocation_args_guarded(&args, |args, check| { unsafe { method .0 - .invoke_values_with_output_kinds_tracked(raw, args, || dispatch.entered.set(true)) + .invoke_values_with_output_kinds_guarded(view.as_raw(), args, || { + receiver_guard.check_native()?; + check()?; + dispatch.entered.set(true); + Ok(()) + }) } .map_err(|error| napi::Error::from_reason(error.message())) - }) - .map(|results| { - results - .into_iter() - .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) - .collect() + .map(|results| { + results + .into_iter() + .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) + .collect() + }) }) } } @@ -2770,14 +2864,21 @@ impl DynComNativeUnion { #[napi] pub struct DynComVariant { value: Option, + inputs: super::com_input::InputBindings, } impl DynComVariant { fn new(value: dynwinrt::com::VariantValue) -> Self { - Self { value: Some(value) } + let inputs = + super::com_input::InputBindings::capture(&dynwinrt::com::Value::Variant(value.clone())); + Self { + value: Some(value), + inputs, + } } fn value(&self) -> napi::Result<&dynwinrt::com::VariantValue> { + self.inputs.ensure_idle()?; self .value .as_ref() @@ -2787,7 +2888,7 @@ impl DynComVariant { impl Drop for DynComVariant { fn drop(&mut self) { - if super::winui_dispatcher_loop_exited() { + if !self.inputs.is_owner() || super::winui_dispatcher_loop_exited() { if let Some(value) = self.value.take() { std::mem::forget(value); } @@ -2995,8 +3096,11 @@ impl DynComVariant { } #[napi] - pub fn release(&mut self) { + pub fn release(&mut self) -> napi::Result<()> { + self.inputs.ensure_owner()?; self.value = None; + self.inputs = super::com_input::InputBindings::deferred(); + Ok(()) } } @@ -3004,13 +3108,18 @@ impl DynComVariant { pub struct DynComDispatchParams { owner_thread: std::thread::ThreadId, value: Option, + inputs: super::com_input::InputBindings, } impl DynComDispatchParams { fn from_value(value: dynwinrt::com::DispatchParamsValue) -> Self { + let inputs = super::com_input::InputBindings::capture(&dynwinrt::com::Value::DispatchParams( + value.clone(), + )); Self { owner_thread: std::thread::current().id(), value: Some(value), + inputs, } } @@ -3020,6 +3129,7 @@ impl DynComDispatchParams { "Apartment-bound DISPPARAMS used from a different thread", )); } + self.inputs.ensure_idle()?; self .value .as_ref() @@ -3098,6 +3208,7 @@ impl DynComDispatchParams { )); } self.value = None; + self.inputs = super::com_input::InputBindings::deferred(); Ok(()) } } @@ -3783,14 +3894,21 @@ pub struct DynComSafeArrayBound { #[napi] pub struct DynComSafeArray { value: Option, + inputs: super::com_input::InputBindings, } impl DynComSafeArray { fn new(value: dynwinrt::com::SafeArrayValue) -> Self { - Self { value: Some(value) } + let inputs = + super::com_input::InputBindings::capture(&dynwinrt::com::Value::SafeArray(value.clone())); + Self { + value: Some(value), + inputs, + } } fn value(&self) -> napi::Result<&dynwinrt::com::SafeArrayValue> { + self.inputs.ensure_idle()?; self .value .as_ref() @@ -3833,7 +3951,7 @@ impl DynComSafeArray { impl Drop for DynComSafeArray { fn drop(&mut self) { - if super::winui_dispatcher_loop_exited() { + if !self.inputs.is_owner() || super::winui_dispatcher_loop_exited() { if let Some(value) = self.value.take() { std::mem::forget(value); } @@ -3993,6 +4111,7 @@ impl DynComSafeArray { values: Vec<&DynWinRTValue>, bounds: Option>, ) -> napi::Result { + let _guard = admit_com_inputs(&values)?; let values = values .into_iter() .map(|value| { @@ -4009,6 +4128,7 @@ impl DynComSafeArray { values: Vec<&DynWinRTValue>, bounds: Option>, ) -> napi::Result { + let _guard = admit_com_inputs(&values)?; let values = values .into_iter() .map(|value| { @@ -4049,6 +4169,7 @@ impl DynComSafeArray { values: Vec<&DynWinRTValue>, bounds: Option>, ) -> napi::Result { + let _guard = admit_com_inputs(&values)?; let values = values .into_iter() .map(|value| { @@ -4226,8 +4347,11 @@ impl DynComSafeArray { } #[napi] - pub fn release(&mut self) { + pub fn release(&mut self) -> napi::Result<()> { + self.inputs.ensure_owner()?; self.value = None; + self.inputs = super::com_input::InputBindings::deferred(); + Ok(()) } } @@ -5431,6 +5555,7 @@ impl DynCom { iid: &WinGUID, values: Vec<&DynWinRTValue>, ) -> napi::Result { + let _guard = admit_com_inputs(&values)?; let values = values .into_iter() .map(|value| { @@ -5667,12 +5792,20 @@ impl DynCom { #[napi] pub fn take_com_array(value: &mut DynWinRTValue) -> napi::Result> { + value.admit_com_input()?; value .4 .take() .ok_or_else(|| napi::Error::from_reason("Value is not a managed COM array result"))? .into_com_values() - .map(|values| values.into_iter().map(DynWinRTValue::new).collect()) + .map(|values| { + values + .into_iter() + .map(|value| { + DynWinRTValue::from_com_result(value, dynwinrt::com::PointerOutputKind::None) + }) + .collect() + }) .map_err(com_error) } @@ -5695,6 +5828,7 @@ impl DynCom { #[napi] pub fn take_variant_array(value: &mut DynWinRTValue) -> napi::Result> { + value.admit_com_input()?; value .4 .take() @@ -5978,24 +6112,30 @@ impl DynCom { #[napi] pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { + value.admit_com_input()?; let result = value .5 .as_mut() .ok_or_else(|| napi::Error::from_reason("Value is not a COM VARIANT"))? .take_variant()?; value.5 = None; - Ok(DynComVariant::new(result)) + let result = DynComVariant::new(result); + value.7 = None; + Ok(result) } #[napi] pub fn take_safe_array(value: &mut DynWinRTValue) -> napi::Result { + value.admit_com_input()?; let result = value .5 .as_mut() .ok_or_else(|| napi::Error::from_reason("Value is not a COM SAFEARRAY"))? .take_safe_array()?; value.5 = None; - Ok(DynComSafeArray::new(result)) + let result = DynComSafeArray::new(result); + value.7 = None; + Ok(result) } #[napi] diff --git a/bindings/js/src/com_input.rs b/bindings/js/src/com_input.rs new file mode 100644 index 00000000..52d67da8 --- /dev/null +++ b/bindings/js/src/com_input.rs @@ -0,0 +1,397 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Apartment-local lifetime pins for managed COM inputs, including containers. + +use std::{ + mem::ManuallyDrop, + rc::Rc, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, MutexGuard, OnceLock, + }, + thread::ThreadId, +}; + +use super::{ComApartmentBinding, DynWinRTValue}; + +fn type_has_interfaces(typ: &dynwinrt::TypeHandle) -> bool { + typ.kind().is_com_pointer() + || typ.kind() == dynwinrt::TypeKind::ArrayOfIUnknown + || (typ.is_array() && type_has_interfaces(&typ.array_element_type())) + || (matches!(typ.kind(), dynwinrt::TypeKind::Struct(_)) + && (0..typ.field_count()).any(|index| type_has_interfaces(&typ.field_type(index)))) +} + +pub(super) fn winrt_has_interfaces(value: &dynwinrt::WinRTValue) -> bool { + match value { + dynwinrt::WinRTValue::Object(_) + | dynwinrt::WinRTValue::Async(_) + | dynwinrt::WinRTValue::ArrayOfIUnknown(_) => true, + dynwinrt::WinRTValue::Array(value) => type_has_interfaces(&value.element_type), + dynwinrt::WinRTValue::Struct(value) => type_has_interfaces(&value.type_handle()), + _ => false, + } +} + +struct State { + owner: Arc>, + bindings: ManuallyDrop>, + children: Vec, + initialized: bool, + error: Option, +} + +// Before claiming an owner, this state contains only thread-safe bookkeeping. +// Afterwards, every access to its apartment-local bindings checks that owner +// while holding the mutex. Foreign destruction never touches their Rc counts. +unsafe impl Send for State {} + +impl Drop for State { + fn drop(&mut self) { + if self.owner.get().is_none() + || (self.owner.get() == Some(&std::thread::current().id()) + && !super::winui_dispatcher_loop_exited()) + { + unsafe { ManuallyDrop::drop(&mut self.bindings) }; + } + } +} + +struct SharedState { + value: Mutex, + contains_interfaces: AtomicBool, +} + +pub(super) struct InputBindings { + // Pointer-free owner tokens also reach pre-existing arrays/struct snapshots. + // An unclaimed token imposes no affinity on an ordinary WinRT carrier. + apartment_tokens: Vec>>, + state: Arc, +} + +impl InputBindings { + pub(super) fn deferred() -> Self { + Self::with_children(Vec::new(), None) + } + + fn with_children(children: Vec, error: Option) -> Self { + let owner = Arc::new(OnceLock::new()); + let mut apartment_tokens = vec![owner.clone()]; + for child in &children { + apartment_tokens.extend(child.apartment_tokens.iter().cloned()); + } + Self { + apartment_tokens, + state: Arc::new(SharedState { + contains_interfaces: AtomicBool::new(error.is_some()), + value: Mutex::new(State { + owner, + bindings: ManuallyDrop::new(Vec::new()), + children, + initialized: false, + error, + }), + }), + } + } + + pub(super) fn capture(value: &dynwinrt::com::Value) -> Self { + let result = Self::deferred(); + if let Err(error) = result.initialize(value) { + return Self::with_children(vec![result], Some(error.reason.clone())); + } + result + } + + pub(super) fn is_owner(&self) -> bool { + let current = std::thread::current().id(); + self + .apartment_tokens + .iter() + .all(|token| token.get().is_none_or(|owner| *owner == current)) + } + + pub(super) fn is_apartment_bound(&self) -> bool { + self + .apartment_tokens + .iter() + .any(|token| token.get().is_some()) + } + + pub(super) fn contains_interfaces(&self) -> bool { + self.state.contains_interfaces.load(Ordering::Relaxed) + } + + pub(super) fn ensure_owner(&self) -> napi::Result<()> { + if !self.is_owner() { + return Err(napi::Error::from_reason( + "Managed COM input used from a different apartment thread", + )); + } + Ok(()) + } + + pub(super) fn pin(&self) -> napi::Result { + self.ensure_owner()?; + Ok(Self { + apartment_tokens: self.apartment_tokens.clone(), + state: self.state.clone(), + }) + } + + fn locked(&self) -> napi::Result> { + let state = self + .state + .value + .lock() + .map_err(|_| napi::Error::from_reason("Managed COM input bookkeeping lock is poisoned"))?; + self.ensure_owner()?; + Ok(state) + } + + pub(super) fn bind_current_apartment(&self) -> napi::Result<()> { + let children = { + let state = self.locked()?; + if let Some(error) = &state.error { + return Err(napi::Error::from_reason(error.clone())); + } + state.owner.get_or_init(|| std::thread::current().id()); + self.ensure_owner()?; + state + .children + .iter() + .map(Self::pin) + .collect::>>()? + }; + for child in children { + child.bind_current_apartment()?; + } + Ok(()) + } + + // WinRT construction only copies private bookkeeping; it neither queries + // interfaces nor imposes COM lifecycle rules on the WinRT API. + pub(super) fn inherit(values: &[&DynWinRTValue]) -> Self { + Self::with_children( + values + .iter() + .map(|value| { + value + .7 + .as_ref() + .map_or_else(Self::deferred, Self::copy_bookkeeping) + }) + .collect(), + None, + ) + } + + pub(super) fn fields(values: &[Option]) -> Self { + Self::with_children( + values + .iter() + .map(|value| { + value + .as_ref() + .map_or_else(Self::deferred, Self::copy_bookkeeping) + }) + .collect(), + None, + ) + } + + pub(super) fn copy_bookkeeping(&self) -> Self { + match self.pin() { + Ok(pin) => pin, + Err(error) => self.failed_copy(error), + } + } + + fn failed_copy(&self, error: napi::Error) -> Self { + let mut result = Self::with_children(Vec::new(), Some(error.reason.clone())); + result + .apartment_tokens + .extend(self.apartment_tokens.iter().cloned()); + result + } + + pub(super) fn element_bookkeeping(&self, index: usize) -> Self { + // Preserve element positions, rather than retaining other elements' empty + // identity slots after the container's native references have been dropped. + match self.locked() { + Ok(state) => state + .children + .get(index) + .map_or_else(Self::deferred, Self::copy_bookkeeping), + Err(error) => self.failed_copy(error), + } + } + + pub(super) fn attach(&self, binding: &ComApartmentBinding) -> napi::Result<()> { + if binding.owner_thread != std::thread::current().id() { + return Err(napi::Error::from_reason( + "Managed COM binding belongs to a different apartment thread", + )); + } + self.bind_current_apartment()?; + let mut state = self.locked()?; + if !state + .bindings + .iter() + .any(|existing| Rc::ptr_eq(&existing.context, &binding.context)) + { + state.bindings.push(binding.clone()); + } + state.initialized = true; + self + .state + .contains_interfaces + .store(true, Ordering::Relaxed); + Ok(()) + } + + fn initialize(&self, value: &dynwinrt::com::Value) -> napi::Result<()> { + if let dynwinrt::com::Value::WinRt(value) = value { + return self.initialize_winrt(value); + } + self.bind_current_apartment()?; + let mut bindings = Vec::new(); + let result = value.visit_interfaces(&mut |object| { + let binding = ComApartmentBinding::for_object(object); + binding.refresh_context(object)?; + bindings.push(binding); + Ok(()) + }); + let mut state = self.locked()?; + state.bindings.extend(bindings); + state.initialized = true; + if let Err(error) = result { + state.error = Some(error.message()); + } + self.state.contains_interfaces.store( + !state.bindings.is_empty() || state.error.is_some(), + Ordering::Relaxed, + ); + Ok(()) + } + + fn initialize_winrt(&self, value: &dynwinrt::WinRTValue) -> napi::Result<()> { + self.bind_current_apartment()?; + let previous_children = { + let state = self.locked()?; + state + .children + .iter() + .map(Self::pin) + .collect::>>()? + }; + let mut bindings = Vec::new(); + let mut children = Vec::new(); + let mut initialize_child = |index: usize, value: dynwinrt::WinRTValue| -> napi::Result<()> { + let child = previous_children + .get(index) + .map(Self::pin) + .transpose()? + .unwrap_or_else(Self::deferred); + let initialized = child.locked()?.initialized; + if !initialized { + child.initialize_winrt(&value)?; + } + children.push(child); + Ok(()) + }; + let result = if let dynwinrt::WinRTValue::Array(array) = value { + (0..array.len()).try_for_each(|index| { + let value = array + .try_get(index) + .map_err(|error| napi::Error::from_reason(error.message()))?; + initialize_child(index, value) + }) + } else if let dynwinrt::WinRTValue::Struct(value) = value { + let typ = value.type_handle(); + (0..typ.field_count()).try_for_each(|index| { + let field = typ.field_type(index); + let value = if field.kind().is_com_pointer() { + value + .get_field_object(index) + .map_err(|error| napi::Error::from_reason(error.message()))? + .map_or(dynwinrt::WinRTValue::Null, dynwinrt::WinRTValue::Object) + } else if matches!(field.kind(), dynwinrt::TypeKind::Struct(_)) { + dynwinrt::WinRTValue::Struct( + value + .get_field_struct_checked(index) + .map_err(|error| napi::Error::from_reason(error.message()))?, + ) + } else { + dynwinrt::WinRTValue::Null + }; + initialize_child(index, value) + }) + } else { + dynwinrt::com::visit_winrt_interfaces(value, &mut |object| { + let binding = ComApartmentBinding::for_object(object); + binding.refresh_context(object)?; + bindings.push(binding); + Ok(()) + }) + .map_err(|error| napi::Error::from_reason(error.message())) + }; + let mut state = self.locked()?; + state.bindings.extend(bindings); + let old_children = std::mem::replace(&mut state.children, children); + state.initialized = true; + if let Err(error) = result { + state.error = Some(error.reason.clone()); + } + self.state.contains_interfaces.store( + !state.bindings.is_empty() + || state.error.is_some() + || state.children.iter().any(Self::contains_interfaces), + Ordering::Relaxed, + ); + drop(state); + drop(old_children); + Ok(()) + } + + pub(super) fn admit_winrt(&self, value: &dynwinrt::WinRTValue) -> napi::Result<()> { + self.ensure_idle()?; + let initialized = self.locked()?.initialized; + if !initialized { + // The COM boundary, not normal WinRT construction, resolves identities. + self.initialize_winrt(value)?; + } + self.ensure_idle() + } + + pub(super) fn ensure_idle(&self) -> napi::Result<()> { + let (children, bindings) = { + let state = self.locked()?; + if let Some(error) = &state.error { + return Err(napi::Error::from_reason(error.clone())); + } + ( + state + .children + .iter() + .map(Self::pin) + .collect::>>()?, + state.bindings.to_vec(), + ) + }; + for child in children { + child.ensure_idle()?; + } + for binding in bindings { + binding.ensure_idle()?; + } + Ok(()) + } + + #[cfg(test)] + pub(super) fn state_alive_probe(&self) -> impl Fn() -> bool + Send + Sync + 'static { + let weak = Arc::downgrade(&self.state); + move || weak.strong_count() != 0 + } +} diff --git a/bindings/js/src/com_input_tests.rs b/bindings/js/src/com_input_tests.rs new file mode 100644 index 00000000..5bdcf1fa --- /dev/null +++ b/bindings/js/src/com_input_tests.rs @@ -0,0 +1,653 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +use dynwinrt::com::borrowed::{ + testing::CopyFixture, BorrowedCopyContract, BorrowedCopyPlan, CopyKind, MF_BUFFER, +}; +use std::{ + cell::{Cell, RefCell}, + ffi::c_void, + rc::Rc, + sync::{ + atomic::{AtomicU32, Ordering}, + Arc, + }, +}; +use windows::core::{IUnknown_Vtbl, HRESULT}; + +fn media(fixture: &CopyFixture) -> DynWinRTValue { + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Object( + fixture.object("media").unwrap(), + )); + value.bind_current_com_apartment().unwrap(); + value +} + +fn plan() -> BorrowedCopyPlan { + BorrowedCopyPlan::prepare( + &TABLE, + BorrowedCopyContract::expected(CopyKind::MediaBuffer), + ) + .unwrap() +} + +fn poison(fixture: &CopyFixture, value: &DynWinRTValue) { + fixture.configure("mediaUnlockHr", 0x80004005).unwrap(); + assert!(plan() + .read_copy(&value.com_context().unwrap(), &value.0.as_object().unwrap()) + .is_err()); +} + +fn assert_rejected(value: &DynWinRTValue, reason: &str) { + let entered = Cell::new(false); + let error = with_com_invocation_args(&[value], |_| { + entered.set(true); + Ok(()) + }) + .unwrap_err(); + assert!(error.reason.contains(reason), "{}", error.reason); + assert!(!entered.get()); +} + +fn containers(value: &DynWinRTValue) -> Vec { + let variant = DynComVariant::unknown(Some(value)).unwrap(); + let array = DynComSafeArray::unknown(vec![value], None).unwrap(); + let nested = DynComVariant::safe_array(&array).unwrap(); + let variants = DynComSafeArray::variant(vec![&nested], None).unwrap(); + let dispatch = DynComDispatchParams::new(vec![&nested], None).unwrap(); + let winrt = super::super::DynWinRTArray::from_object_values( + vec![value], + &DynWinRTType(TABLE.interface(MF_BUFFER)), + ) + .unwrap(); + vec![ + DynCom::interface_array(&WinGUID(MF_BUFFER), vec![value]).unwrap(), + DynCom::variant_array(vec![&variant]).unwrap(), + DynCom::variant(&variant).unwrap(), + DynCom::safe_array(&array).unwrap(), + DynCom::variant(&nested).unwrap(), + DynCom::safe_array(&variants).unwrap(), + DynCom::dispatch_params(&dispatch).unwrap(), + winrt.to_value().unwrap(), + ] +} + +#[test] +fn com_arguments_reject_poisoned_objects_and_preexisting_aliases() { + let fixture = CopyFixture::default(); + let value = media(&fixture); + let alias = media(&fixture); + with_com_invocation_args(&[&alias], |_| Ok(())).unwrap(); + poison(&fixture, &value); + assert_rejected(&value, "poisoned"); + assert_rejected(&alias, "poisoned"); + assert!(alias + .to_com_value() + .unwrap_err() + .reason + .contains("poisoned")); + // Identity and deterministic release are not ordinary input admission. + let mut queried = alias.cast(&WinGUID(MF_BUFFER)).unwrap(); + queried.release().unwrap(); +} + +#[test] +fn com_argument_containers_pin_later_poison_after_originals_are_released() { + let mut fixture = CopyFixture::default(); + let mut value = media(&fixture); + let mut alias = media(&fixture); + let admission = admit_com_inputs(&[&alias]).unwrap(); + let containers = containers(&alias); + let mut variant_only = DynComVariant::unknown(Some(&alias)).unwrap(); + let mut array_only = DynComSafeArray::unknown(vec![&alias], None).unwrap(); + let mut dispatch_only = DynComDispatchParams::new(vec![&variant_only], None).unwrap(); + for container in &containers { + with_com_invocation_args(&[container], |_| Ok(())).unwrap(); + } + poison(&fixture, &value); + value.release().unwrap(); + alias.release().unwrap(); + fixture.release_owners(); + assert!(admission.check().unwrap_err().reason.contains("poisoned")); + drop(admission); + assert!(!fixture.events().contains(&"drop.media".to_string())); + for container in &containers { + assert_rejected(container, "poisoned"); + } + assert!(DynCom::variant(&variant_only) + .err() + .unwrap() + .reason + .contains("poisoned")); + assert!(DynCom::safe_array(&array_only) + .err() + .unwrap() + .reason + .contains("poisoned")); + assert!(DynCom::dispatch_params(&dispatch_only) + .err() + .unwrap() + .reason + .contains("poisoned")); + variant_only.release().unwrap(); + array_only.release().unwrap(); + dispatch_only.release().unwrap(); + drop(containers); + assert_eq!( + fixture + .events() + .iter() + .filter(|e| *e == "drop.media") + .count(), + 1 + ); +} + +#[test] +fn com_argument_busy_guard_runs_without_a_javascript_callback() { + let fixture = CopyFixture::default(); + let value = media(&fixture); + let alias = media(&fixture); + let containers = containers(&alias); + let observed = Rc::new(Cell::new(false)); + let observed_hook = observed.clone(); + fixture.hook(Some(Rc::new(move |event| { + if event == "media.acquire" { + assert_rejected(&alias, "busy"); + for container in &containers { + assert_rejected(container, "busy"); + } + observed_hook.set(true); + } + }))); + plan() + .read_copy(&value.com_context().unwrap(), &value.0.as_object().unwrap()) + .unwrap(); + fixture.hook(None); + assert!(observed.get()); + with_com_invocation_args(&[&value], |_| Ok(())).unwrap(); +} + +const TEST_IID: GUID = GUID::from_u128(0x109302ce_8b8e_4e90_ad9c_5b988abc94b1); +thread_local! { + static ON_QUERY: RefCell>> = RefCell::new(None); +} + +#[derive(Default)] +struct Counts { + queries: AtomicU32, + addrefs: AtomicU32, + releases: AtomicU32, + calls: AtomicU32, +} + +#[repr(C)] +struct TestObject { + vtable: &'static TestVtable, + references: AtomicU32, + counts: Arc, +} + +#[repr(C)] +struct TestVtable { + base: IUnknown_Vtbl, + call: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT, +} + +unsafe extern "system" fn test_query( + this: *mut c_void, + iid: *const GUID, + out: *mut *mut c_void, +) -> HRESULT { + let object = unsafe { &*this.cast::() }; + object.counts.queries.fetch_add(1, Ordering::SeqCst); + if unsafe { *iid } != IUnknown::IID && unsafe { *iid } != TEST_IID { + unsafe { *out = std::ptr::null_mut() }; + return HRESULT(0x80004002u32 as i32); + } + if unsafe { *iid } == TEST_IID { + let hook = ON_QUERY.with(|hook| hook.borrow_mut().take()); + if let Some(hook) = hook { + hook(); + } + } + unsafe { + *out = this; + test_addref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn test_addref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counts.addrefs.fetch_add(1, Ordering::SeqCst); + object.references.fetch_add(1, Ordering::SeqCst) + 1 +} + +unsafe extern "system" fn test_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counts.releases.fetch_add(1, Ordering::SeqCst); + let remaining = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + if remaining == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + remaining +} + +unsafe extern "system" fn test_call(this: *mut c_void, _: *mut c_void, _: *mut c_void) -> HRESULT { + unsafe { &*this.cast::() } + .counts + .calls + .fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +static TEST_VTABLE: TestVtable = TestVtable { + base: IUnknown_Vtbl { + QueryInterface: test_query, + AddRef: test_addref, + Release: test_release, + }, + call: test_call, +}; + +fn test_object() -> (DynWinRTValue, Arc) { + let (mut value, counts) = unbound_test_object(); + value.bind_current_com_apartment().unwrap(); + (value, counts) +} + +fn unbound_test_object() -> (DynWinRTValue, Arc) { + let counts = Arc::new(Counts::default()); + let object = Box::new(TestObject { + vtable: &TEST_VTABLE, + references: AtomicU32::new(1), + counts: counts.clone(), + }); + let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; + let value = DynWinRTValue::new(dynwinrt::WinRTValue::Object(unknown)); + (value, counts) +} + +fn unbound_async_value() -> DynWinRTValue { + let operation = windows_future::IAsyncOperation::::ready(Ok(42)); + DynWinRTValue::new(dynwinrt::WinRTValue::Async(dynwinrt::AsyncInfo { + info: operation.cast().unwrap(), + async_type: TABLE.async_operation(&TABLE.i32_type()), + })) +} + +#[test] +fn unbound_winrt_bookkeeping_allows_cross_thread_use_and_frees_on_drop() { + use super::super::{com_input::InputBindings, DynWinRTArray, DynWinRTStruct}; + fn send_sync() {} + send_sync::(); + + let (value, counts) = unbound_test_object(); + let async_value = unbound_async_value(); + let object_alive = value.7.as_ref().unwrap().state_alive_probe(); + let async_alive = async_value.7.as_ref().unwrap().state_alive_probe(); + std::thread::spawn(move || { + let alias = value.cast(&WinGUID(TEST_IID)).unwrap(); + let array = + DynWinRTArray::from_object_values(vec![&alias], &DynWinRTType(TABLE.interface(TEST_IID))) + .unwrap(); + let mut structure = DynWinRTStruct::create(&DynWinRTType( + TABLE.struct_type("UnboundTransferField", &[TABLE.interface(TEST_IID)]), + )) + .unwrap(); + structure.set_object(0.0, &alias).unwrap(); + let array_value = array.to_value().unwrap(); + let struct_value = structure.to_value().unwrap(); + let async_alias = async_value + .cast(&WinGUID(windows_future::IAsyncOperation::::IID)) + .unwrap(); + let operation: windows_future::IAsyncOperation = + async_alias.0.as_object().unwrap().cast().unwrap(); + assert_eq!(operation.GetResults().unwrap(), 42); + for value in [ + &value, + &alias, + &array_value, + &struct_value, + &async_value, + &async_alias, + ] { + assert!(!value.7.as_ref().unwrap().is_apartment_bound()); + } + }) + .join() + .unwrap(); + assert!( + !object_alive(), + "unbound array/struct aliases must not leak their shared bookkeeping" + ); + assert!( + !async_alive(), + "unbound async bookkeeping must be freed on its consumer thread" + ); + assert_eq!( + counts.releases.load(Ordering::SeqCst), + counts.addrefs.load(Ordering::SeqCst) + 1, + ); +} + +#[test] +fn deferred_com_ownership_is_claimed_once_without_leaking_empty_state() { + use super::super::com_input::InputBindings; + let state = InputBindings::deferred(); + let alive = state.state_alive_probe(); + let first = state.pin().unwrap(); + let second = state.pin().unwrap(); + let barrier = Arc::new(std::sync::Barrier::new(3)); + let first_barrier = barrier.clone(); + let first = std::thread::spawn(move || { + first_barrier.wait(); + first.bind_current_apartment().is_ok() + }); + let second_barrier = barrier.clone(); + let second = std::thread::spawn(move || { + second_barrier.wait(); + second.bind_current_apartment().is_ok() + }); + barrier.wait(); + assert_ne!(first.join().unwrap(), second.join().unwrap()); + drop(state); + assert!( + !alive(), + "a claimed state with no apartment bindings must still be freed" + ); +} + +#[test] +fn unbound_winrt_values_first_enter_com_on_the_consumer_thread() { + use super::super::{DynWinRTArray, DynWinRTStruct}; + for explicit_binding in [false, true] { + let (mut value, counts) = unbound_test_object(); + let async_value = unbound_async_value(); + let object_alive = value.7.as_ref().unwrap().state_alive_probe(); + let async_alive = async_value.7.as_ref().unwrap().state_alive_probe(); + let array = + DynWinRTArray::from_object_values(vec![&value], &DynWinRTType(TABLE.interface(TEST_IID))) + .unwrap(); + let array_value = array.to_value().unwrap(); + let mut structure = DynWinRTStruct::create(&DynWinRTType( + TABLE.struct_type("ConsumerAdmissionField", &[TABLE.interface(TEST_IID)]), + )) + .unwrap(); + structure.set_object(0.0, &value).unwrap(); + let snapshot = structure.to_value().unwrap(); + std::thread::spawn(move || { + if explicit_binding { + value.bind_current_com_apartment().unwrap(); + } + // In the implicit case the pre-existing container reaches COM first. + with_com_invocation_args(&[&array_value, &snapshot, &value, &async_value], |_| Ok(())) + .unwrap(); + value.bind_current_com_apartment().unwrap(); + let mut extracted = array.get(0.0).unwrap(); + extracted.bind_current_com_apartment().unwrap(); + assert!(Rc::ptr_eq( + &value.6.as_ref().unwrap().context, + &extracted.6.as_ref().unwrap().context, + )); + for input in [&array_value, &snapshot, &value, &async_value] { + let inputs = input.7.as_ref().unwrap(); + assert!(inputs.is_apartment_bound()); + assert!(inputs.is_owner()); + } + drop(structure); + }) + .join() + .unwrap(); + assert!(!object_alive()); + assert!(!async_alive()); + assert_eq!( + counts.releases.load(Ordering::SeqCst), + counts.addrefs.load(Ordering::SeqCst) + 1, + ); + } +} + +#[test] +fn com_argument_apartment_rejection_precedes_all_interface_refcount_and_qi_actions() { + let (mut value, counts) = unbound_test_object(); + let winrt_array = super::super::DynWinRTArray::from_object_values( + vec![&value], + &DynWinRTType(TABLE.interface(TEST_IID)), + ) + .unwrap(); + let extracted = winrt_array.get(0.0).unwrap(); + let mut structure = super::super::DynWinRTStruct::create(&DynWinRTType( + TABLE.struct_type("ApartmentGuardField", &[TABLE.interface(TEST_IID)]), + )) + .unwrap(); + structure.set_object(0.0, &value).unwrap(); + let struct_value = structure.to_value().unwrap(); + value.bind_current_com_apartment().unwrap(); + let array = DynCom::interface_array(&WinGUID(TEST_IID), vec![&value]).unwrap(); + let variant = DynComVariant::unknown(Some(&value)).unwrap(); + let carrier = DynCom::variant(&variant).unwrap(); + let before = ( + counts.queries.load(Ordering::SeqCst), + counts.addrefs.load(Ordering::SeqCst), + counts.releases.load(Ordering::SeqCst), + ); + let returned = std::thread::spawn(move || { + for input in [&value, &array, &carrier, &extracted, &struct_value] { + assert_rejected(input, "different apartment thread"); + assert!(input.to_com_value().is_err()); + } + assert!(winrt_array.get(0.0).is_err()); + assert!(winrt_array.to_values().is_err()); + assert!(winrt_array.to_value().is_err()); + assert!(structure.get_object(0.0).is_err()); + assert!(structure.to_value().is_err()); + assert!(struct_value.as_struct().is_err()); + assert!(super::super::DynWinRTArray::from_object_values( + vec![&value], + &DynWinRTType(TABLE.interface(TEST_IID)), + ) + .is_err()); + ( + value, + array, + carrier, + winrt_array, + extracted, + structure, + struct_value, + ) + }) + .join() + .unwrap(); + assert_eq!( + before, + ( + counts.queries.load(Ordering::SeqCst), + counts.addrefs.load(Ordering::SeqCst), + counts.releases.load(Ordering::SeqCst) + ) + ); + drop(returned); +} + +fn argument_method() -> DynComMethodHandle { + DynComMethodHandle( + dynwinrt::com::register_interface( + &TABLE, + "argument-guard", + TEST_IID, + dynwinrt::com::InterfaceBase::IUnknown, + ) + .add_method_at( + 3, + "Use", + dynwinrt::com::MethodSignature::new(&TABLE) + .add_in(dynwinrt::com::Type::winrt(TABLE.interface(TEST_IID))) + .add_in(dynwinrt::com::Type::winrt(TABLE.interface(MF_BUFFER))), + ) + .unwrap() + .method(3) + .unwrap(), + ) +} + +#[test] +fn com_argument_rechecks_after_native_qi_before_the_dispatch_marker() { + let fixture = Rc::new(CopyFixture::default()); + let value = Rc::new(media(&fixture)); + let (receiver, counts) = test_object(); + let (trigger, _) = test_object(); + let method = argument_method(); + let marker = DynComRawDispatchState { + entered: Cell::new(false), + }; + DynComRaw::invoke_all_tracked(&method, &receiver, vec![&trigger, &value], &marker).unwrap(); + assert!(marker.entered.get()); + assert_eq!(counts.calls.load(Ordering::SeqCst), 1); + let poisoned = value.clone(); + ON_QUERY.with(|hook| *hook.borrow_mut() = Some(Box::new(move || poison(&fixture, &poisoned)))); + let error = DynComRaw::invoke_all_tracked(&method, &receiver, vec![&trigger, &value], &marker) + .err() + .unwrap(); + assert!(error.reason.contains("poisoned"), "{}", error.reason); + assert!(!marker.entered.get()); + assert_eq!(counts.calls.load(Ordering::SeqCst), 1); +} + +#[test] +fn com_receiver_rechecks_after_argument_qi_with_idle_arguments() { + for tracked in [false, true] { + let fixture = Rc::new(CopyFixture::default()); + let poison_target = Rc::new(media(&fixture)); + let (mut receiver, counts) = test_object(); + // Give the counted native receiver the fixture's lifecycle context without + // pretending that its vtable implements IMFMediaBuffer. + receiver + .retain_com_context(poison_target.com_context().unwrap()) + .unwrap(); + let healthy_fixture = CopyFixture::default(); + let healthy = media(&healthy_fixture); + let (trigger, _) = test_object(); + let method = argument_method(); + let marker = DynComRawDispatchState { + entered: Cell::new(false), + }; + let invoke = || { + if tracked { + DynComRaw::invoke_all_tracked(&method, &receiver, vec![&trigger, &healthy], &marker) + .map(|_| ()) + } else { + method + .invoke(&receiver, vec![&trigger, &healthy]) + .map(|_| ()) + } + }; + invoke().unwrap(); + assert_eq!(counts.calls.load(Ordering::SeqCst), 1); + ON_QUERY + .with(|hook| *hook.borrow_mut() = Some(Box::new(move || poison(&fixture, &poison_target)))); + let error = invoke().unwrap_err(); + assert!(error.reason.contains("poisoned"), "{}", error.reason); + healthy.ensure_tracked_com_idle().unwrap(); + trigger.ensure_tracked_com_idle().unwrap(); + assert_eq!(counts.calls.load(Ordering::SeqCst), 1); + if tracked { + assert!(!marker.entered.get()); + } + } +} + +#[test] +fn com_argument_guard_preserves_plain_values_and_winrt_array_construction() { + let scalar = DynWinRTValue::new(dynwinrt::WinRTValue::I32(42)); + let buffer = DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(dynwinrt::com::ComBufferValue::from_owned_bytes( + vec![1, 2], + 2, + )), + dynwinrt::com::PointerOutputKind::None, + ); + let prop = DynComPropVariant::i32(7.0).unwrap(); + let prop = DynCom::prop_variant(&prop).unwrap(); + with_com_invocation_args(&[&scalar, &buffer, &prop], |values| { + assert_eq!(values.len(), 3); + Ok(()) + }) + .unwrap(); + let fixture = CopyFixture::default(); + let value = media(&fixture); + poison(&fixture, &value); + // Constructing/projecting a WinRT array is unchanged; COM admission is later. + let array = super::super::DynWinRTArray::from_object_values( + vec![&value], + &DynWinRTType(TABLE.interface(MF_BUFFER)), + ) + .unwrap(); + assert_eq!(array.0.len(), 1); + assert_rejected(&array.to_value().unwrap(), "poisoned"); +} + +#[test] +fn com_argument_winrt_array_extraction_retains_only_the_selected_identity() { + let mut fixture = CopyFixture::default(); + let mut value = media(&fixture); + let other_fixture = CopyFixture::default(); + let other = media(&other_fixture); + let array = super::super::DynWinRTArray::from_object_values( + vec![&value, &other], + &DynWinRTType(TABLE.interface(MF_BUFFER)), + ) + .unwrap(); + let extracted = array.get(0.0).unwrap(); + let idle = array.get(1.0).unwrap(); + let all = array.to_values().unwrap(); + drop(array); + poison(&fixture, &value); + value.release().unwrap(); + fixture.release_owners(); + assert_rejected(&extracted, "poisoned"); + assert_rejected(&all[0], "poisoned"); + with_com_invocation_args(&[&idle, &all[1]], |_| Ok(())).unwrap(); +} + +#[test] +fn com_argument_typed_struct_fields_keep_independent_snapshot_bindings() { + use super::super::{DynWinRTArray, DynWinRTStruct}; + let mut fixture = CopyFixture::default(); + let mut value = media(&fixture); + let typ = DynWinRTType(TABLE.struct_type("InputInterfaceField", &[TABLE.interface(MF_BUFFER)])); + let outer_type = DynWinRTType(TABLE.struct_type("InputNestedField", &[typ.0.clone()])); + let mut inner = DynWinRTStruct::create(&typ).unwrap(); + inner.set_object(0.0, &value).unwrap(); + let mut outer = DynWinRTStruct::create(&outer_type).unwrap(); + outer.set_struct(0.0, &inner).unwrap(); + let snapshot = outer.to_value().unwrap(); + let field = snapshot + .as_struct() + .unwrap() + .get_struct(0.0) + .unwrap() + .get_object(0.0) + .unwrap(); + let array = DynWinRTArray::from_object_values(vec![&snapshot], &outer_type) + .unwrap() + .to_value() + .unwrap(); + with_com_invocation_args(&[&snapshot, &array], |_| Ok(())).unwrap(); + inner + .set_object(0.0, &DynWinRTValue::new(dynwinrt::WinRTValue::Null)) + .unwrap(); + outer.set_struct(0.0, &inner).unwrap(); + poison(&fixture, &value); + value.release().unwrap(); + fixture.release_owners(); + assert_rejected(&snapshot, "poisoned"); + assert_rejected(&field, "poisoned"); + assert_rejected(&array, "poisoned"); + with_com_invocation_args(&[&outer.to_value().unwrap()], |_| Ok(())).unwrap(); +} diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index be370c91..b75e9274 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -33,6 +33,7 @@ mod com_borrowed; mod com_completion; #[cfg(feature = "test-hooks")] mod com_completion_test_hooks; +mod com_input; #[cfg(feature = "test-hooks")] mod generated_unsafe_test_hooks; mod managed_tsfn; @@ -966,10 +967,11 @@ pub struct DynWinRTValue( Option, Option, Option, + Option, ); -// COM carriers check their owner before accessing/cloning the private Rc sidecar. -// Off-thread destruction leaks that sidecar and its COM owners instead of -// changing an Rc count or releasing an apartment reference on the wrong thread. +// Unbound WinRT bookkeeping is thread-safe. Once COM ownership is established, +// owner checks protect apartment-local Rc state; foreign destruction leaks only +// that bound state and its native owners instead of releasing them off-thread. unsafe impl Send for DynWinRTValue {} unsafe impl Sync for DynWinRTValue {} @@ -1033,10 +1035,40 @@ impl ComApartmentBinding { } Ok(()) } + + fn refresh_context(&self, object: &IUnknown) -> dynwinrt::Result<()> { + if self.owner_thread != std::thread::current().id() { + return Err(dynwinrt::Error::WindowsError(windows::core::Error::new( + windows::core::HRESULT(0x80070057u32 as i32), + "Classic COM object used from a different apartment thread", + ))); + } + if self.context.borrow().is_none() { + let context = dynwinrt::com::borrowed::Identity::lookup(object)?; + *self.context.borrow_mut() = context; + } + Ok(()) + } + + fn ensure_idle(&self) -> napi::Result<()> { + if self.owner_thread != std::thread::current().id() { + return Err(napi::Error::from_reason( + "Classic COM object used from a different apartment thread", + )); + } + self.ensure_identity()?; + if let Some(context) = self.context.borrow().as_ref() { + context + .ensure_idle() + .map_err(|error| napi::Error::from_reason(error.message()))?; + } + Ok(()) + } } impl DynWinRTValue { fn new(value: dynwinrt::WinRTValue) -> Self { + let inputs = com_input::winrt_has_interfaces(&value).then(com_input::InputBindings::deferred); Self( value, None, @@ -1045,10 +1077,22 @@ impl DynWinRTValue { None, None, None, + inputs, ) } pub(crate) fn bind_current_com_apartment(&mut self) -> napi::Result<()> { + if !matches!( + self.0, + dynwinrt::WinRTValue::Object(_) | dynwinrt::WinRTValue::Async(_) + ) { + return Err(napi::Error::from_reason( + "Classic COM apartment binding requires a managed COM object", + )); + } + if let Some(inputs) = &self.7 { + inputs.bind_current_apartment()?; + } let current = std::thread::current().id(); if self .6 @@ -1070,6 +1114,9 @@ impl DynWinRTValue { )); } self.existing_com_context()?; + if let Some(inputs) = &self.7 { + inputs.attach(self.6.as_ref().expect("bound COM object"))?; + } Ok(()) } @@ -1087,6 +1134,11 @@ impl DynWinRTValue { } pub(crate) fn ensure_existing_com_apartment(&self) -> napi::Result<()> { + if let Some(inputs) = &self.7 { + if inputs.is_apartment_bound() { + inputs.ensure_owner()?; + } + } if self.6.is_some() { self.ensure_com_apartment() } else { @@ -1115,22 +1167,15 @@ impl DynWinRTValue { self.ensure_com_apartment()?; let binding = self.6.as_ref().expect("checked apartment"); binding.ensure_identity()?; - if let Some(context) = binding.context.borrow().as_ref() { - return Ok(Some(context.clone())); - } - if !dynwinrt::com::borrowed::has_live_contexts() - .map_err(|error| napi::Error::from_reason(error.message()))? - { - return Ok(None); - } - let object = self - .0 - .as_object() - .ok_or_else(|| napi::Error::from_reason("COM object is released"))?; - let context = dynwinrt::com::borrowed::Identity::lookup(&object) + let object = match &self.0 { + dynwinrt::WinRTValue::Object(object) => object, + dynwinrt::WinRTValue::Async(value) => (&value.info).into(), + _ => return Err(napi::Error::from_reason("COM object is released")), + }; + binding + .refresh_context(object) .map_err(|error| napi::Error::from_reason(error.message()))?; - *binding.context.borrow_mut() = context.clone(); - Ok(context) + Ok(binding.context.borrow().clone()) } fn ensure_tracked_com_idle(&self) -> napi::Result<()> { @@ -1158,6 +1203,9 @@ impl DynWinRTValue { let binding = ComApartmentBinding::for_object(object); *binding.context.borrow_mut() = Some(context); self.6 = Some(binding); + if let Some(inputs) = &self.7 { + inputs.attach(self.6.as_ref().unwrap())?; + } self.6.as_ref().unwrap().ensure_identity() } @@ -1170,6 +1218,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1182,6 +1231,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1197,6 +1247,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1212,6 +1263,7 @@ impl DynWinRTValue { Some(buffer), None, None, + None, ) } @@ -1239,156 +1291,81 @@ impl DynWinRTValue { } else { None }; - Self(value, None, provenance, None, None, None, apartment) + let mut result = Self::new(value); + if let (Some(inputs), Some(binding)) = (&result.7, &apartment) { + inputs + .attach(binding) + .expect("native COM output belongs to the current thread"); + } + result.2 = provenance; + result.6 = apartment; + result } fn from_com_value( value: dynwinrt::com::Value, output_kind: dynwinrt::com::PointerOutputKind, ) -> Self { - match value { + let inputs = com_input::InputBindings::capture(&value); + let mut result = match value { dynwinrt::com::Value::WinRt(value) => Self::from_com_result(value, output_kind), - dynwinrt::com::Value::Bstr(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::Bstr(value))), - None, - ), - dynwinrt::com::Value::NativeStruct(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - Some(value), - None, - None, - None, - ), - dynwinrt::com::Value::NativeUnion(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new( - dynwinrt::com::Value::NativeUnion(value), - )), - None, - ), - dynwinrt::com::Value::Variant(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::Variant( - value, - ))), - None, - ), - dynwinrt::com::Value::SafeArray(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::SafeArray( - value, - ))), - None, - ), - dynwinrt::com::Value::PropVariant(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new( - dynwinrt::com::Value::PropVariant(value), - )), - None, - ), - dynwinrt::com::Value::DispatchParams(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new( - dynwinrt::com::Value::DispatchParams(value), - )), - None, - ), - dynwinrt::com::Value::ExcepInfo(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::ExcepInfo( - value, - ))), - None, - ), - dynwinrt::com::Value::StatStg(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::StatStg( - value, - ))), - None, - ), - dynwinrt::com::Value::FormatEtc(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::FormatEtc( - value, - ))), - None, - ), - dynwinrt::com::Value::StgMedium(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new(dynwinrt::com::Value::StgMedium( - value, - ))), - None, - ), - dynwinrt::com::Value::AudioFormat(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - None, - Some(com::AutomationValue::new( - dynwinrt::com::Value::AudioFormat(value), - )), - None, - ), - dynwinrt::com::Value::Buffer(value) => Self( - dynwinrt::WinRTValue::Null, - None, - com::PointerProvenance::None, - None, - Some(value), - None, - None, - ), + dynwinrt::com::Value::NativeStruct(value) => { + let mut result = Self::new(dynwinrt::WinRTValue::Null); + result.3 = Some(value); + result + } + dynwinrt::com::Value::Buffer(value) => { + let mut result = Self::new(dynwinrt::WinRTValue::Null); + result.4 = Some(value); + result + } + value @ (dynwinrt::com::Value::Bstr(_) + | dynwinrt::com::Value::NativeUnion(_) + | dynwinrt::com::Value::Variant(_) + | dynwinrt::com::Value::SafeArray(_) + | dynwinrt::com::Value::PropVariant(_) + | dynwinrt::com::Value::DispatchParams(_) + | dynwinrt::com::Value::ExcepInfo(_) + | dynwinrt::com::Value::StatStg(_) + | dynwinrt::com::Value::FormatEtc(_) + | dynwinrt::com::Value::StgMedium(_) + | dynwinrt::com::Value::AudioFormat(_)) => { + let mut result = Self::new(dynwinrt::WinRTValue::Null); + result.5 = Some(com::AutomationValue::new(value)); + result + } + }; + result.7 = inputs.contains_interfaces().then_some(inputs); + result + } + + fn check_com_input_state(&self) -> napi::Result<()> { + if let Some(inputs) = &self.7 { + inputs.ensure_idle()?; } + if let Some(binding) = &self.6 { + binding.ensure_idle()?; + } + if let Some(automation) = &self.5 { + automation.ensure_owner_thread()?; + } + Ok(()) + } + + fn admit_com_input(&self) -> napi::Result<()> { + self.check_com_input_state()?; + self.ensure_existing_com_apartment()?; + if let Some(inputs) = &self.7 { + inputs.admit_winrt(&self.0)?; + } + if self.6.is_some() { + self.ensure_tracked_com_idle()?; + } + Ok(()) } fn to_com_value(&self) -> napi::Result { + self.admit_com_input()?; if let Some(value) = &self.5 { value.to_com_value() } else if let Some(value) = &self.4 { @@ -1442,15 +1419,22 @@ impl DynWinRTValue { impl Drop for DynWinRTValue { fn drop(&mut self) { if self - .6 + .7 .as_ref() - .is_some_and(|binding| binding.owner_thread != std::thread::current().id()) + .is_some_and(|inputs| inputs.is_apartment_bound() && !inputs.is_owner()) + || self + .6 + .as_ref() + .is_some_and(|binding| binding.owner_thread != std::thread::current().id()) { let value = mem::replace(&mut self.0, dynwinrt::WinRTValue::Null); mem::forget(value); if let Some(binding) = self.6.take() { mem::forget(binding); } + if let Some(value) = self.4.take() { + mem::forget(value); + } return; } // After Application.Start returns, XAML has already torn down its thread @@ -1480,6 +1464,11 @@ impl Drop for DynWinRTValue { impl DynWinRTValue { #[napi] pub fn release(&mut self) -> napi::Result<()> { + if let Some(inputs) = &self.7 { + if inputs.is_apartment_bound() { + inputs.ensure_owner()?; + } + } if self.6.is_some() { self.ensure_com_apartment()?; } @@ -1491,6 +1480,7 @@ impl DynWinRTValue { self.4 = None; self.5 = None; self.6 = None; + self.7 = None; Ok(()) } @@ -1798,6 +1788,10 @@ impl DynWinRTValue { .map_err(|e| napi::Error::from_reason(format!("QueryInterface failed: {}", e.message())))?; let mut result = DynWinRTValue::new(result); result.6 = self.6.clone(); + result.7 = self + .7 + .as_ref() + .map(com_input::InputBindings::copy_bookkeeping); Ok(result) } @@ -1930,8 +1924,15 @@ impl DynWinRTValue { #[napi] pub fn as_array(&self) -> napi::Result { + self.ensure_existing_com_apartment()?; match &self.0 { - dynwinrt::WinRTValue::Array(data) => Ok(DynWinRTArray(data.clone())), + dynwinrt::WinRTValue::Array(data) => Ok(DynWinRTArray( + data.clone(), + self + .7 + .as_ref() + .map(com_input::InputBindings::copy_bookkeeping), + )), _ => Err(napi::Error::from_reason("Value is not an Array")), } } @@ -1943,8 +1944,11 @@ impl DynWinRTValue { #[napi] pub fn as_struct(&self) -> napi::Result { + self.ensure_existing_com_apartment()?; match &self.0 { - dynwinrt::WinRTValue::Struct(data) => Ok(DynWinRTStruct(data.clone())), + dynwinrt::WinRTValue::Struct(data) => { + Ok(DynWinRTStruct::from_data(data.clone(), self.7.as_ref())) + } _ => Err(napi::Error::from_reason("Value is not a Struct")), } } @@ -1955,10 +1959,46 @@ impl DynWinRTValue { // ====================================================================== #[napi] -pub struct DynWinRTArray(dynwinrt::ArrayData); +pub struct DynWinRTArray(dynwinrt::ArrayData, Option); + +impl DynWinRTArray { + fn new(data: dynwinrt::ArrayData) -> Self { + Self(data, None) + } + + fn element_value(&self, index: usize) -> DynWinRTValue { + let mut value = DynWinRTValue::new(self.0.get(index)); + if let Some(inputs) = &self.1 { + value.7 = Some(inputs.element_bookkeeping(index)); + } + value + } + + fn ensure_existing_com_apartment(&self) -> napi::Result<()> { + if let Some(inputs) = &self.1 { + if inputs.is_apartment_bound() { + inputs.ensure_owner()?; + } + } + Ok(()) + } +} unsafe impl Send for DynWinRTArray {} unsafe impl Sync for DynWinRTArray {} +impl Drop for DynWinRTArray { + fn drop(&mut self) { + if self + .1 + .as_ref() + .is_some_and(|inputs| inputs.is_apartment_bound() && !inputs.is_owner()) + { + let empty = dynwinrt::ArrayData::empty(self.0.element_type.clone()); + mem::forget(mem::replace(&mut self.0, empty)); + } + } +} + #[napi] impl DynWinRTArray { #[napi] @@ -1969,6 +2009,7 @@ impl DynWinRTArray { /// Per-element access (works for all element types). #[napi] pub fn get(&self, index: f64) -> napi::Result { + self.ensure_existing_com_apartment()?; let index = js_u32(index, "get")? as usize; if index >= self.0.len() { return Err(napi::Error::from_reason(format!( @@ -1976,15 +2017,14 @@ impl DynWinRTArray { self.0.len(), ))); } - Ok(DynWinRTValue::new(self.0.get(index))) + Ok(self.element_value(index)) } /// Convert all elements to DynWinRTValue array. #[napi] - pub fn to_values(&self) -> Vec { - (0..self.0.len()) - .map(|i| DynWinRTValue::new(self.0.get(i))) - .collect() + pub fn to_values(&self) -> napi::Result> { + self.ensure_existing_com_apartment()?; + Ok((0..self.0.len()).map(|i| self.element_value(i)).collect()) } // -- Typed batch conversions -- @@ -2163,14 +2203,14 @@ impl DynWinRTArray { .into_iter() .map(|v| dynwinrt::WinRTValue::I8(v as i8)) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.i8_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.i8_type(), &wvals)) } #[napi] pub fn from_u8_values(values: Vec) -> DynWinRTArray { let wvals: Vec = values.into_iter().map(dynwinrt::WinRTValue::U8).collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.u8_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.u8_type(), &wvals)) } /// Build a u8 DynWinRtArray from a JS `Uint8Array` (zero-copy view into V8 @@ -2183,7 +2223,7 @@ impl DynWinRTArray { .iter() .map(|&v| dynwinrt::WinRTValue::U8(v)) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.u8_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.u8_type(), &wvals)) } #[napi] @@ -2192,7 +2232,7 @@ impl DynWinRTArray { .into_iter() .map(|v| dynwinrt::WinRTValue::I16(v as i16)) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.i16_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.i16_type(), &wvals)) } #[napi] @@ -2201,21 +2241,21 @@ impl DynWinRTArray { .into_iter() .map(|v| dynwinrt::WinRTValue::U16(v as u16)) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.u16_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.u16_type(), &wvals)) } #[napi] pub fn from_i32_values(values: Vec) -> DynWinRTArray { let wvals: Vec = values.into_iter().map(dynwinrt::WinRTValue::I32).collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.i32_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.i32_type(), &wvals)) } #[napi] pub fn from_u32_values(values: Vec) -> DynWinRTArray { let wvals: Vec = values.into_iter().map(dynwinrt::WinRTValue::U32).collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.u32_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.u32_type(), &wvals)) } #[napi] @@ -2224,14 +2264,14 @@ impl DynWinRTArray { .into_iter() .map(|v| dynwinrt::WinRTValue::F32(v as f32)) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.f32_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.f32_type(), &wvals)) } #[napi] pub fn from_f64_values(values: Vec) -> DynWinRTArray { let wvals: Vec = values.into_iter().map(dynwinrt::WinRTValue::F64).collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.f64_type(), &wvals)) + DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.f64_type(), &wvals)) } #[napi] @@ -2243,7 +2283,7 @@ impl DynWinRTArray { js_i64(value, &format!("fromI64Values[{index}]")).map(dynwinrt::WinRTValue::I64) }) .collect::>()?; - Ok(DynWinRTArray(dynwinrt::ArrayData::from_values( + Ok(DynWinRTArray::new(dynwinrt::ArrayData::from_values( TABLE.i64_type(), &wvals, ))) @@ -2258,7 +2298,7 @@ impl DynWinRTArray { js_u64(value, &format!("fromU64Values[{index}]")).map(dynwinrt::WinRTValue::U64) }) .collect::>()?; - Ok(DynWinRTArray(dynwinrt::ArrayData::from_values( + Ok(DynWinRTArray::new(dynwinrt::ArrayData::from_values( TABLE.u64_type(), &wvals, ))) @@ -2270,7 +2310,7 @@ impl DynWinRTArray { .into_iter() .map(|s| dynwinrt::WinRTValue::HString(HSTRING::from(&s))) .collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values( + DynWinRTArray::new(dynwinrt::ArrayData::from_values( TABLE.make(dynwinrt::TypeKind::HString), &wvals, )) @@ -2286,18 +2326,27 @@ impl DynWinRTArray { pub fn from_object_values( values: Vec<&DynWinRTValue>, element_type: &DynWinRTType, - ) -> DynWinRTArray { + ) -> napi::Result { + for value in &values { + value.ensure_existing_com_apartment()?; + } + let inputs = com_input::InputBindings::inherit(&values); let wvals: Vec = values.iter().map(|v| v.0.clone()).collect(); - DynWinRTArray(dynwinrt::ArrayData::from_values( - element_type.0.clone(), - &wvals, + Ok(DynWinRTArray( + dynwinrt::ArrayData::from_values(element_type.0.clone(), &wvals), + Some(inputs), )) } /// Wrap as DynWinRTValue::Array for passing to call(). #[napi] - pub fn to_value(&self) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::Array(self.0.clone())) + pub fn to_value(&self) -> napi::Result { + self.ensure_existing_com_apartment()?; + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Array(self.0.clone())); + if let Some(inputs) = &self.1 { + value.7 = Some(inputs.copy_bookkeeping()); + } + Ok(value) } } @@ -2307,7 +2356,7 @@ mod js_boundary_tests { #[test] fn hresult_arrays_use_the_i32_projection() { - let array = DynWinRTArray(dynwinrt::ArrayData::from_values( + let array = DynWinRTArray::new(dynwinrt::ArrayData::from_values( TABLE.hresult(), &[dynwinrt::WinRTValue::HResult(windows::core::HRESULT( 0x80004005u32 as i32, @@ -2404,11 +2453,30 @@ mod js_boundary_tests { // ====================================================================== #[napi] -pub struct DynWinRTStruct(dynwinrt::ValueTypeData); +pub struct DynWinRTStruct( + dynwinrt::ValueTypeData, + Vec>, +); unsafe impl Send for DynWinRTStruct {} unsafe impl Sync for DynWinRTStruct {} impl DynWinRTStruct { + fn from_data(data: dynwinrt::ValueTypeData, inputs: Option<&com_input::InputBindings>) -> Self { + let fields = (0..data.type_handle().field_count()) + .map(|index| inputs.map(|inputs| inputs.element_bookkeeping(index))) + .collect(); + Self(data, fields) + } + + fn ensure_existing_com_apartment(&self) -> napi::Result<()> { + for input in self.1.iter().flatten() { + if input.is_apartment_bound() { + input.ensure_owner()?; + } + } + Ok(()) + } + fn checked_field_index( &self, index: f64, @@ -2416,6 +2484,7 @@ impl DynWinRTStruct { expected: &str, accepts: impl Fn(dynwinrt::TypeKind) -> bool, ) -> napi::Result { + self.ensure_existing_com_apartment()?; let index = js_u32(index, method)? as usize; let handle = self.0.type_handle(); if index >= handle.field_count() { @@ -2434,6 +2503,20 @@ impl DynWinRTStruct { } } +impl Drop for DynWinRTStruct { + fn drop(&mut self) { + if self + .1 + .iter() + .flatten() + .any(|input| input.is_apartment_bound() && !input.is_owner()) + { + let empty = self.0.type_handle().default_value(); + mem::forget(mem::replace(&mut self.0, empty)); + } + } +} + #[napi] impl DynWinRTStruct { /// Create a zero-initialized struct of the given type. @@ -2445,7 +2528,7 @@ impl DynWinRTStruct { typ.0.kind(), ))); } - Ok(DynWinRTStruct(typ.0.default_value())) + Ok(DynWinRTStruct::from_data(typ.0.default_value(), None)) } #[napi] @@ -2681,11 +2764,15 @@ impl DynWinRTStruct { let index = self.checked_field_index(index, "getStruct", "struct", |kind| { matches!(kind, dynwinrt::TypeKind::Struct(_)) })?; - Ok(DynWinRTStruct(self.0.get_field_struct(index))) + Ok(DynWinRTStruct::from_data( + self.0.get_field_struct(index), + self.1[index].as_ref(), + )) } #[napi] pub fn set_struct(&mut self, index: f64, value: &DynWinRTStruct) -> napi::Result<()> { + value.ensure_existing_com_apartment()?; let index = self.checked_field_index(index, "setStruct", "struct", |kind| { matches!(kind, dynwinrt::TypeKind::Struct(_)) })?; @@ -2696,7 +2783,9 @@ impl DynWinRTStruct { "setStruct: field {index} requires {expected:?}, found {actual:?}", ))); } + let inputs = com_input::InputBindings::fields(&value.1); self.0.set_field_struct(index, &value.0); + self.1[index] = Some(inputs); Ok(()) } @@ -2710,16 +2799,24 @@ impl DynWinRTStruct { .get_field_object(index) .map_err(|error| napi::Error::from_reason(error.message()))? { - Some(object) => Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Object(object))), + Some(object) => { + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Object(object)); + if let Some(inputs) = &self.1[index] { + value.7 = Some(inputs.copy_bookkeeping()); + } + Ok(value) + } None => Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)), } } #[napi] pub fn set_object(&mut self, index: f64, value: &DynWinRTValue) -> napi::Result<()> { + value.ensure_existing_com_apartment()?; let index = self.checked_field_index(index, "setObject", "WinRT object", |kind| { kind.is_com_pointer() })?; + let inputs = com_input::InputBindings::inherit(&[value]); match &value.0 { dynwinrt::WinRTValue::Object(obj) => self .0 @@ -2732,13 +2829,20 @@ impl DynWinRTStruct { _ => Err(napi::Error::from_reason( "setObject requires a WinRT object or null value", )), - } + }?; + self.1[index] = Some(inputs.element_bookkeeping(0)); + Ok(()) } /// Wrap as DynWinRTValue::Struct for passing to call(). #[napi] - pub fn to_value(&self) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::Struct(self.0.clone())) + pub fn to_value(&self) -> napi::Result { + self.ensure_existing_com_apartment()?; + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Struct(self.0.clone())); + if value.7.is_some() { + value.7 = Some(com_input::InputBindings::fields(&self.1)); + } + Ok(value) } } diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index ad531a8c..f74f05cc 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -8,7 +8,7 @@ repository = "https://github.com/microsoft/dynwinrt" authors = ["Microsoft"] [features] -test-hooks = [] +test-hooks = ["windows/Win32_Media_MediaFoundation"] [dependencies] dynwinrt-com-contracts = { path = "../dynwinrt-com-contracts", version = "0.1.0" } diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index 4eca2706..bf1c53e8 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -649,7 +649,7 @@ pub(crate) fn call_method_dynamic( ) -> windows_core::Result> where A: ArgumentList + ?Sized, - F: FnOnce(), + F: FnOnce() -> windows_core::Result<()>, { match call_method_dynamic_impl( vtable_index, @@ -669,7 +669,7 @@ where } } -pub(crate) fn call_method_dynamic_captured( +pub(crate) fn call_method_dynamic_captured( vtable_index: usize, obj: *mut c_void, parameters: &[Parameter], @@ -677,7 +677,11 @@ pub(crate) fn call_method_dynamic_captured( out_count: usize, return_kind: &MethodReturn, cif: &libffi::middle::Cif, -) -> windows_core::Result { + before_dispatch: F, +) -> windows_core::Result +where + F: FnOnce() -> windows_core::Result<()>, +{ match call_method_dynamic_impl( vtable_index, obj, @@ -686,7 +690,7 @@ pub(crate) fn call_method_dynamic_captured( out_count, return_kind, cif, - || {}, + before_dispatch, )? { DynamicCallOutcome::Captured(call) => Ok(call), DynamicCallOutcome::Values(_) => Err(windows_core::Error::new( @@ -708,7 +712,7 @@ fn call_method_dynamic_impl( ) -> windows_core::Result where A: ArgumentList + ?Sized, - F: FnOnce(), + F: FnOnce() -> windows_core::Result<()>, { use crate::metadata_table::ValueTypeData; use libffi::middle::CodePtr; @@ -1413,7 +1417,7 @@ where let mut mark_dispatched = || { mark_dispatched .take() - .expect("native dispatch marker must run exactly once")(); + .expect("native dispatch marker must run exactly once")() }; let call_result: windows_core::Result<( Option, @@ -1421,12 +1425,12 @@ where )> = unsafe { match return_kind { MethodReturn::HResult => { - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); Ok((None, Some(hr))) } MethodReturn::SemanticHResult => { - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); Ok(( hr.is_ok() @@ -1435,24 +1439,24 @@ where )) } MethodReturn::PreservedHResult => { - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); Ok((Some(NativeCallValue::WinRt(WinRTValue::HResult(hr))), None)) } MethodReturn::CapturedHResult(_) => { - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); Ok((None, Some(hr))) } MethodReturn::Void => { - mark_dispatched(); + mark_dispatched()?; cif.call::<()>(CodePtr(fptr), &ffi_args); Ok((None, None)) } MethodReturn::Value { typ, .. } => { if let crate::native_call::ParameterType::NativeStruct(layout) = typ { NativeStructStorage::zeroed(layout).and_then(|mut storage| { - mark_dispatched(); + mark_dispatched()?; cif.call_return_into(CodePtr(fptr), &ffi_args, storage.as_ret()); storage.validate_canaries()?; crate::com::NativeStructValue::new(layout.clone(), storage.to_vec()) @@ -1466,7 +1470,7 @@ where }) } else if let crate::native_call::ParameterType::NativeUnion(layout) = typ { NativeUnionStorage::zeroed(layout).and_then(|mut storage| { - mark_dispatched(); + mark_dispatched()?; cif.call_return_into(CodePtr(fptr), &ffi_args, storage.as_ret()); storage.validate_canaries()?; crate::com::NativeUnionValue::from_returned_bytes( @@ -1482,7 +1486,7 @@ where }) }) } else { - mark_dispatched(); + mark_dispatched()?; let value = match typ.abi_type() { AbiType::Bool => AbiValue::Bool(cif.call(CodePtr(fptr), &ffi_args)), AbiType::I8 => AbiValue::I8(cif.call(CodePtr(fptr), &ffi_args)), diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index bb5bd6dd..96ad4ef0 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -1477,6 +1477,126 @@ pub enum Value { Buffer(ComBufferValue), } +/// Visits only typed, owned interface values, never unclassified pointer bits. +/// The caller must already have admitted the value's apartment before traversal. +#[doc(hidden)] +pub fn visit_winrt_interfaces( + value: &WinRTValue, + visitor: &mut dyn FnMut(&IUnknown) -> result::Result<()>, +) -> result::Result<()> { + match value { + WinRTValue::Object(object) => visitor(object)?, + WinRTValue::Async(value) => visitor((&value.info).into())?, + WinRTValue::ArrayOfIUnknown(array) => { + for object in array.0.iter().flatten() { + visitor(object)?; + } + } + WinRTValue::Array(array) => { + for index in 0..array.len() { + visit_winrt_interfaces(&array.try_get(index)?, visitor)?; + } + } + WinRTValue::Struct(value) => { + let typ = value.type_handle(); + for index in 0..typ.field_count() { + let field = typ.field_type(index); + if field.kind().is_com_pointer() { + if let Some(object) = value.get_field_object(index)? { + visitor(&object)?; + } + } else if matches!(field.kind(), crate::TypeKind::Struct(_)) { + visit_winrt_interfaces( + &WinRTValue::Struct(value.get_field_struct_checked(index)?), + visitor, + )?; + } + } + } + _ => {} + } + Ok(()) +} + +impl Value { + #[doc(hidden)] + pub fn visit_interfaces( + &self, + visitor: &mut dyn FnMut(&IUnknown) -> result::Result<()>, + ) -> result::Result<()> { + match self { + Self::WinRt(value) => visit_winrt_interfaces(value, visitor)?, + Self::Variant(value) => visit_variant_interfaces(value, visitor)?, + Self::SafeArray(value) => visit_safe_array_interfaces(value, visitor)?, + Self::DispatchParams(value) => { + for argument in value.arguments()? { + visit_variant_interfaces(&argument, visitor)?; + } + } + Self::Buffer(value) => match &value.storage { + ComBufferStorage::InterfaceArray { values, .. } => { + for value in values { + visitor(value)?; + } + } + ComBufferStorage::OwnedCom { values } => { + for value in values { + visit_winrt_interfaces(value, visitor)?; + } + } + ComBufferStorage::VariantArray { values } + | ComBufferStorage::OwnedVariants { values } => { + for value in values { + visit_variant_interfaces(value, visitor)?; + } + } + _ => {} + }, + // The supported PROPVARIANT set is scalar/vector POD and owned + // strings; STGMEDIUM is copied HGLOBAL bytes, not stream/storage. + Self::Bstr(_) + | Self::NativeStruct(_) + | Self::NativeUnion(_) + | Self::PropVariant(_) + | Self::ExcepInfo(_) + | Self::StatStg(_) + | Self::FormatEtc(_) + | Self::StgMedium(_) + | Self::AudioFormat(_) => {} + } + Ok(()) + } +} + +fn visit_variant_interfaces( + value: &VariantValue, + visitor: &mut dyn FnMut(&IUnknown) -> result::Result<()>, +) -> result::Result<()> { + match value.data()? { + VariantData::Unknown(Some(object)) | VariantData::Dispatch(Some(object)) => { + visitor(&object)? + } + VariantData::SafeArray(value) => visit_safe_array_interfaces(&value, visitor)?, + _ => {} + } + Ok(()) +} + +fn visit_safe_array_interfaces( + value: &SafeArrayValue, + visitor: &mut dyn FnMut(&IUnknown) -> result::Result<()>, +) -> result::Result<()> { + for element in value.elements()? { + match element { + SafeArrayElementValue::Unknown(Some(object)) + | SafeArrayElementValue::Dispatch(Some(object)) => visitor(&object)?, + SafeArrayElementValue::Variant(value) => visit_variant_interfaces(&value, visitor)?, + _ => {} + } + } + Ok(()) +} + fn is_null_input_value(value: &Value) -> bool { match value { Value::WinRt(WinRTValue::RawPtr(pointer)) => pointer.is_null(), @@ -4642,6 +4762,21 @@ impl ComCallPlan { ) -> result::Result> where F: FnOnce(), + { + self.invoke_values_guarded(obj, args, || { + mark_dispatched(); + Ok(()) + }) + } + + fn invoke_values_guarded( + &self, + obj: *mut c_void, + args: &[Value], + mark_dispatched: F, + ) -> result::Result> + where + F: FnOnce() -> windows_core::Result<()>, { if matches!(self.return_plan, ComReturnPlan::DispatchInvokeHResult(_)) { return Err(invalid_argument( @@ -5094,6 +5229,18 @@ impl ComCallPlan { obj: *mut c_void, args: &[Value], ) -> result::Result { + self.invoke_dispatch_guarded(obj, args, || Ok(())) + } + + fn invoke_dispatch_guarded( + &self, + obj: *mut c_void, + args: &[Value], + before_dispatch: F, + ) -> result::Result + where + F: FnOnce() -> windows_core::Result<()>, + { let ComReturnPlan::DispatchInvokeHResult(plan) = &self.return_plan else { return Err(invalid_argument( "method does not use the IDispatch::Invoke captured HRESULT convention", @@ -5111,7 +5258,7 @@ impl ComCallPlan { let captured = self .native - .call_com_dynamic_captured(obj, args) + .call_com_dynamic_captured(obj, args, before_dispatch) .map_err(result::Error::WindowsError)?; let mut outputs = captured.outputs; let result = match outputs[plan.result_output_index].take() { @@ -5230,7 +5377,19 @@ impl ComCallPlan { obj: *mut c_void, args: &[Value], ) -> result::Result> { - let values = self.invoke_values(obj, args)?; + self.invoke_values_with_output_kinds_guarded(obj, args, || Ok(())) + } + + fn invoke_values_with_output_kinds_guarded( + &self, + obj: *mut c_void, + args: &[Value], + before_dispatch: F, + ) -> result::Result> + where + F: FnOnce() -> windows_core::Result<()>, + { + let values = self.invoke_values_guarded(obj, args, before_dispatch)?; if values.len() != self.results.len() { return Err(invalid_argument(format!( "COM result plan mismatch: native call returned {} value(s), plan describes {}", @@ -7026,11 +7185,34 @@ impl MethodHandle { ) -> result::Result> where F: FnOnce(), + { + unsafe { + self.invoke_values_with_output_kinds_guarded(obj, args, || { + mark_dispatched(); + Ok(()) + }) + } + } + + /// Like the tracked invocation, but permits a final admission check after + /// native argument preparation (including interface QI) and before dispatch. + /// + /// # Safety + /// `obj` must satisfy the same live interface contract as `invoke`. + #[doc(hidden)] + pub unsafe fn invoke_values_with_output_kinds_guarded( + &self, + obj: *mut c_void, + args: &[Value], + before_dispatch: F, + ) -> result::Result> + where + F: FnOnce() -> windows_core::Result<()>, { let values = self .0 .plan - .invoke_values_tracked(obj, args, mark_dispatched)?; + .invoke_values_guarded(obj, args, before_dispatch)?; if values.len() != self.0.plan.results.len() { return Err(invalid_argument(format!( "COM result plan mismatch: native call returned {} value(s), plan describes {}", @@ -7062,6 +7244,23 @@ impl MethodHandle { self.0.plan.invoke_dispatch(obj, args) } + /// # Safety + /// `obj` must satisfy the live IDispatch contract of `invoke_dispatch`. + #[doc(hidden)] + pub unsafe fn invoke_dispatch_guarded( + &self, + obj: *mut c_void, + args: &[Value], + before_dispatch: F, + ) -> result::Result + where + F: FnOnce() -> windows_core::Result<()>, + { + self.0 + .plan + .invoke_dispatch_guarded(obj, args, before_dispatch) + } + /// # Safety /// /// `obj` must point to a live COM interface whose vtable contains this diff --git a/crates/dynwinrt/src/com_automation.rs b/crates/dynwinrt/src/com_automation.rs index 18f54983..0500478f 100644 --- a/crates/dynwinrt/src/com_automation.rs +++ b/crates/dynwinrt/src/com_automation.rs @@ -674,6 +674,21 @@ impl DispatchParamsValue { self.inner.arguments.len() } + #[doc(hidden)] + pub fn arguments(&self) -> result::Result> { + self.inner + .arguments + .iter() + .rev() + .map(|argument| { + let copy = VariantValue::empty(); + unsafe { VariantCopy(copy.raw_mut(), argument) }.map_err(windows_error)?; + copy.validate_supported()?; + Ok(copy) + }) + .collect() + } + pub fn named_dispids(&self) -> Vec { self.inner.named_dispids.iter().rev().copied().collect() } diff --git a/crates/dynwinrt/src/com_borrowed.rs b/crates/dynwinrt/src/com_borrowed.rs index 359a067e..a8b640dc 100644 --- a/crates/dynwinrt/src/com_borrowed.rs +++ b/crates/dynwinrt/src/com_borrowed.rs @@ -612,6 +612,22 @@ pub unsafe fn invoke_managed( view: &IUnknown, args: &[Value], ) -> result::Result { + unsafe { invoke_managed_guarded(method, context, view, args, || Ok(())) } +} + +/// # Safety +/// The receiver and pointer-shaped inputs must satisfy the registered native ABI. +#[doc(hidden)] +pub unsafe fn invoke_managed_guarded( + method: &MethodHandle, + context: &Identity, + view: &IUnknown, + args: &[Value], + before_dispatch: F, +) -> result::Result +where + F: FnOnce() -> windows_core::Result<()>, +{ context.ensure_idle()?; let transaction = method .0 @@ -623,7 +639,13 @@ pub unsafe fn invoke_managed( } let Some(effect) = method.0.context_effect else { return Ok(ManagedCallOutput { - values: unsafe { method.invoke_values_with_output_kinds(view.as_raw(), args)? }, + values: unsafe { + method.invoke_values_with_output_kinds_guarded( + view.as_raw(), + args, + before_dispatch, + )? + }, output_context: None, }); }; @@ -681,7 +703,7 @@ pub unsafe fn invoke_managed( .context_hresult_plan .as_ref() .expect("validated context call") - .invoke_values_with_output_kinds(view.as_raw(), args)?; + .invoke_values_with_output_kinds_guarded(view.as_raw(), args, before_dispatch)?; let hresult = values.remove(0).0; let hr = match hresult { Value::WinRt(WinRTValue::I32(value)) => value, diff --git a/crates/dynwinrt/src/com_borrowed_test_support.rs b/crates/dynwinrt/src/com_borrowed_test_support.rs index 2c9301ea..1d056d0a 100644 --- a/crates/dynwinrt/src/com_borrowed_test_support.rs +++ b/crates/dynwinrt/src/com_borrowed_test_support.rs @@ -960,6 +960,14 @@ impl Default for CopyFixture { impl CopyFixture { pub fn object(&self, kind: &str) -> result::Result { + if kind == "sample" { + if self.objects.is_empty() { + return Err(error("Fixture owners have been released")); + } + return unsafe { windows::Win32::Media::MediaFoundation::MFCreateSample() }? + .cast() + .map_err(result::Error::WindowsError); + } if kind == "mediaUnknown" { return super::query(&self.object("media")?, &IUnknown::IID); } @@ -1055,7 +1063,6 @@ impl CopyFixture { })); Ok(()) } - #[cfg(test)] pub fn hook(&self, hook: Option>) { *self.control.hook.borrow_mut() = hook; } diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 004e422d..8953606e 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -1762,7 +1762,7 @@ impl Method { obj: *mut std::ffi::c_void, args: &[WinRTValue], ) -> windows_core::Result> { - self.call_dynamic_tracked(obj, args, || {}) + self.call_dynamic_tracked(obj, args, || Ok(())) } pub(crate) fn call_dynamic_tracked( @@ -1772,7 +1772,7 @@ impl Method { mark_dispatched: F, ) -> windows_core::Result> where - F: FnOnce(), + F: FnOnce() -> windows_core::Result<()>, { if args.len() != self.info.input_count { return Err(invalid_argument(&format!( @@ -1806,13 +1806,13 @@ impl Method { let mut mark_dispatched = || { mark_dispatched .take() - .expect("native dispatch marker must run exactly once")(); + .expect("native dispatch marker must run exactly once")() }; match &self.strategy { CallStrategy::Direct0In0Out => { // 0 in + 0 out: fn(this) -> HRESULT - mark_dispatched(); + mark_dispatched()?; let hr = call::call_winrt_method_0(self.info.index, obj); hr.ok()?; Ok(vec![]) @@ -1821,7 +1821,7 @@ impl Method { // 0 in + 1 out: fn(this, out) -> HRESULT let param = &self.info.parameters[0]; let mut out = param.typ.default_value(); - mark_dispatched(); + mark_dispatched()?; let hr = call::call_winrt_method_1(self.info.index, obj, out.out_ptr()); if hr.is_err() { if let WinRTValue::RawPtr(ptr) = &mut out { @@ -1842,7 +1842,7 @@ impl Method { } CallStrategy::Direct1In0Out => { // 1 in + 0 out: fn(this, val) -> HRESULT - mark_dispatched(); + mark_dispatched()?; let hr = call::call_1in(self.info.index, obj, args.get_value(0)); hr.ok()?; Ok(vec![]) @@ -1851,7 +1851,7 @@ impl Method { // 1 in + 1 out: fn(this, val, out) -> HRESULT let out_param = self.info.parameters.iter().find(|p| p.is_out()).unwrap(); let mut out = out_param.typ.default_value(); - mark_dispatched(); + mark_dispatched()?; let hr = call::call_1in_1out(self.info.index, obj, args.get_value(0), out.out_ptr()); if hr.is_err() { @@ -1876,7 +1876,7 @@ impl Method { let mut length: u32 = 0; let mut data_ptr: *mut std::ffi::c_void = std::ptr::null_mut(); let fptr = call::get_vtable_function_ptr(obj, self.info.index); - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = unsafe { let method: unsafe extern "system" fn( *mut std::ffi::c_void, @@ -1919,7 +1919,7 @@ impl Method { let buffer = array_data.serialize_for_abi(); let mut out = out_param.typ.default_value(); let fptr = call::get_vtable_function_ptr(obj, self.info.index); - mark_dispatched(); + mark_dispatched()?; let hr: windows_core::HRESULT = unsafe { let method: unsafe extern "system" fn( *mut std::ffi::c_void, @@ -1969,7 +1969,12 @@ impl Method { unsafe { windows::Win32::System::Com::CoTaskMemAlloc(total_bytes) as *mut u8 }; assert!(!buffer_ptr.is_null(), "CoTaskMemAlloc failed for FillArray"); unsafe { std::ptr::write_bytes(buffer_ptr, 0, total_bytes) }; - mark_dispatched(); + let array = crate::array::ArrayData::from_cotaskmem( + elem_type, + buffer_ptr as _, + capacity as usize, + ); + mark_dispatched()?; let hr: windows_core::HRESULT = unsafe { let method: unsafe extern "system" fn( *mut std::ffi::c_void, @@ -1979,22 +1984,7 @@ impl Method { -> windows_core::HRESULT = std::mem::transmute(fptr); method(obj, capacity, buffer_ptr) }; - if hr.is_err() { - // Callee may have written elements before failing. - // Buffer was zero-initialized, so null slots are safe to release. - // Use capacity as cleanup length — ArrayData::Drop skips null elements. - let _ = crate::array::ArrayData::from_cotaskmem( - elem_type.clone(), - buffer_ptr as _, - capacity as usize, - ); - hr.ok()?; - } - let array = crate::array::ArrayData::from_cotaskmem( - elem_type, - buffer_ptr as _, - capacity as usize, - ); + hr.ok()?; Ok(vec![WinRTValue::Array(array)]) } CallStrategy::Direct1InFillArray => { @@ -2017,8 +2007,13 @@ impl Method { unsafe { windows::Win32::System::Com::CoTaskMemAlloc(total_bytes) as *mut u8 }; assert!(!buffer_ptr.is_null(), "CoTaskMemAlloc failed for FillArray"); unsafe { std::ptr::write_bytes(buffer_ptr, 0, total_bytes) }; + let array = crate::array::ArrayData::from_cotaskmem( + elem_type, + buffer_ptr as _, + capacity as usize, + ); let fptr = call::get_vtable_function_ptr(obj, self.info.index); - mark_dispatched(); + mark_dispatched()?; let hr = call::call_fill_array_1in( fptr, obj, @@ -2026,20 +2021,7 @@ impl Method { capacity, buffer_ptr, ); - if hr.is_err() { - // Buffer was zero-initialized; use capacity for cleanup. - let _ = crate::array::ArrayData::from_cotaskmem( - elem_type.clone(), - buffer_ptr as _, - capacity as usize, - ); - hr.ok()?; - } - let array = crate::array::ArrayData::from_cotaskmem( - elem_type, - buffer_ptr as _, - capacity as usize, - ); + hr.ok()?; Ok(vec![WinRTValue::Array(array)]) } CallStrategy::Libffi(cif) => call::call_method_dynamic( @@ -2323,7 +2305,7 @@ impl Method { mark_dispatched: F, ) -> windows_core::Result> where - F: FnOnce(), + F: FnOnce() -> windows_core::Result<()>, { if matches!(self.info.return_kind, MethodReturn::CapturedHResult(_)) { return Err(invalid_argument( @@ -2366,11 +2348,15 @@ impl Method { }) } - pub(crate) fn call_com_dynamic_captured( + pub(crate) fn call_com_dynamic_captured( &self, obj: *mut std::ffi::c_void, args: &[crate::com::Value], - ) -> windows_core::Result { + before_dispatch: F, + ) -> windows_core::Result + where + F: FnOnce() -> windows_core::Result<()>, + { let invocation_args = self.prepare_com_invocation_args(args)?; let CallStrategy::Libffi(cif) = &self.strategy else { return Err(invalid_argument( @@ -2385,6 +2371,7 @@ impl Method { self.info.out_count, &self.info.return_kind, cif, + before_dispatch, ) } } @@ -2510,6 +2497,63 @@ mod tests { assert_eq!(method.info.parameters[2].input_index, None); } + #[test] + fn rejecting_dispatch_guard_skips_fill_array_fast_paths() { + unsafe extern "system" fn fill( + this: *mut std::ffi::c_void, + _capacity: u32, + _data: *mut u8, + ) -> windows_core::HRESULT { + unsafe { record_i32(this, 0) } + } + unsafe extern "system" fn fill_after_scalar( + this: *mut std::ffi::c_void, + _value: u32, + capacity: u32, + data: *mut u8, + ) -> windows_core::HRESULT { + unsafe { fill(this, capacity, data) } + } + + let table = MetadataTable::new(); + let array_type = table.array(&table.i32_type()); + for with_scalar in [false, true] { + let mut signature = AbiMethodSignature::new(&table); + let mut args = Vec::new(); + if with_scalar { + signature = signature.add_in_type(ParameterType::winrt(table.u32_type())); + args.push(WinRTValue::U32(7)); + } + let method = signature + .add_out_fill_type(ParameterType::winrt(array_type.clone())) + .build(0); + assert!(matches!( + (&method.strategy, with_scalar), + (CallStrategy::DirectFillArray, false) | (CallStrategy::Direct1InFillArray, true) + )); + args.push(WinRTValue::Array(crate::array::ArrayData::from_values( + table.i32_type(), + &[WinRTValue::I32(0), WinRTValue::I32(0)], + ))); + let vtable = Box::new([if with_scalar { + fill_after_scalar as *mut std::ffi::c_void + } else { + fill as *mut std::ffi::c_void + }]); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + let error = method + .call_dynamic_tracked((&mut object as *mut FakeComObject).cast(), &args, || { + Err(windows_core::HRESULT(0x80004004u32 as i32).into()) + }) + .unwrap_err(); + assert_eq!(error.code().0, 0x80004004u32 as i32); + assert_eq!(object.calls.load(Ordering::Relaxed), 0); + } + } + #[test] fn fast_accessors_reject_incompatible_method_shapes() { let table = MetadataTable::new(); diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 72bec6e0..b47c3d68 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -327,6 +327,21 @@ reference or cycle. QI, `projectAs`, and independently rewrapped aliases recover the same context while any managed holder retains it. Conflicting mappings fail closed. +Ordinary COM invocation also admits every managed interface argument, not just +the receiver. The shared input boundary checks apartment ownership and the +current busy/poisoned state before conversion and native dispatch. Supported +interface-bearing containers retain the same canonical-identity context slots +as their elements; they do not gain a fresh lifecycle by cloning native +references. A container created while idle must still reject a subsequently +poisoned element, including after the original wrappers have been released. +This is a common argument rule, not an `IMFSample::AddBuffer` special case. +Standard identity handling and deterministic release remain available for +cleanup; ordinary invocation does not make every unrelated idle object busy. +The final admission check runs after native argument coercion, including QI, +so reentrancy cannot invalidate an earlier check unnoticed. Rejection keeps +the dispatch marker clear and releases call-local storage. The private lowering +hook is generic; COM state policy stays in the COM binding layer. + The receiver and required owner gates enter `Acquiring` **before** native dispatch. No registry/state lock is held across a native call. A successful acquire arms cleanup before pointer/range validation or allocation. Direct JS diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 0b5a7d09..59c20bd5 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -804,6 +804,13 @@ Cleanup failure throws, discards copy results and permanently poisons the shared context; it is not retried by a finalizer. Writes may have taken effect before a later error, so do not assume transactional rollback. +A busy or poisoned object also cannot be passed to another COM object's method. +The same rule applies to aliases and supported interface-bearing containers: +an array built before a cleanup failure is checked again when used, and +releasing the original wrapper does not clear state retained by that array. +Release managed holders normally after a failure; do not try to reuse the +object through `IMFSample.addBuffer()` or another input path. + Render/capture and MF are intentionally copy-only facades, not complete native interfaces. General `IMF2DBuffer`/`IMF2DBuffer2` pitch/plane access and writable external WIC locks are not supported. See the From c0c0c7b4b43824680bc95216c1a7bfde300d803f Mon Sep 17 00:00:00 2001 From: leileizhang Date: Wed, 9 Sep 2026 09:45:27 +0800 Subject: [PATCH 4/4] Project ambiguous COM overloads as explicit slot-named methods (#147) Preserve existing arity/shape dispatch for distinguishable groups. Emit stable AtSlot names for previously unsupported ordinary overloads without guessing ABI behavior, retain each validated method plan, reject alias collisions, and update exact coverage evidence. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 28 +- README.md | 18 +- .../classic-com-contract-evidence-registry.md | 42 ++- .../classic-com-generated-unsafe.md | 31 +- docs/architecture/classic-com-support.md | 43 ++- docs/guides/windows/classic-com-usage.md | 31 ++ docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 61 ++-- .../classic-com-capability-summary.json | 48 +-- .../classic-com-interface-support.csv | 48 +-- .../src/codegen/com/capability.rs | 24 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 7 +- .../src/codegen/com/project/mod.rs | 298 ++++++++++++++++-- .../tests/com_explicit_overload_test.rs | 186 +++++++++++ 13 files changed, 711 insertions(+), 154 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 13168688..81700d63 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -94,7 +94,7 @@ jobs: if ($result.eligible_interfaces -ne 7929) { throw "Classic COM census denominator changed: $($result.eligible_interfaces)" } - if ($result.complete_interfaces -lt 5697) { + if ($result.complete_interfaces -lt 5721) { throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" } if ($result.coverage_percent -lt 70.0) { @@ -111,14 +111,14 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $result = Get-Content (Join-Path $output 'classic-com-capability-summary.json') -Raw | ConvertFrom-Json - if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5697) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5721) { throw "Classic COM safe totals changed in capability census" } $support = Import-Csv (Join-Path $output 'classic-com-interface-support.csv') if ( @($support).Count -ne 7929 -or - @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5697 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2232 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5721 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2208 ) { throw "Classic COM compact interface support index changed" } @@ -129,9 +129,9 @@ jobs: } } $expected = @{ - x64 = @(412, 1431, 389) - i686 = @(411, 1408, 413) - arm64 = @(412, 1431, 389) + x64 = @(388, 1431, 389) + i686 = @(387, 1408, 413) + arm64 = @(388, 1431, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -144,16 +144,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5697 -or - $result.safeEvidence.standardDerived -ne 5332 -or - $result.safeEvidence.exactRegistryDependent -ne 365 -or - $result.safeEvidence.metadataFactOccurrences -ne 5983 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26134 -or + $result.safeEvidence.safeComplete -ne 5721 -or + $result.safeEvidence.standardDerived -ne 5355 -or + $result.safeEvidence.exactRegistryDependent -ne 366 -or + $result.safeEvidence.metadataFactOccurrences -ne 6012 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26247 -or $result.safeEvidence.registeredExactEntries -ne 532 -or $result.safeEvidence.metadataMatchedExactEntries -ne 532 -or $result.safeEvidence.safeConsumedExactEntries -ne 431 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 693 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 424 + $result.safeEvidence.exactEntryInterfaceDependencies -ne 694 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 425 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/README.md b/README.md index ffe26c57..48af4592 100644 --- a/README.md +++ b/README.md @@ -138,18 +138,20 @@ can omit the bootstrap call. Classic COM support is functional and tested, but remains a **preview under active development**. It targets a conservatively validated subset of `IUnknown`- and `IInspectable`-rooted interfaces from `Windows.Win32.winmd`; it -is not a general Automation or native Win32 projection, and it does not project -flat DLL exports. +is not a general Automation or native Win32 projection, and it does not provide +general flat DLL export projection. The current CI baseline against -`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,697 of 7,929 -eligible interfaces (71.85%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,721 of 7,929 +eligible interfaces (72.15%)** with complete safe code generation. Supported contracts include generated coclass activation and QueryInterface views, managed interface ownership, native POD layouts, typed counted buffers, BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, the target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, variable-length WAVEFORMATEX audio formats with exact CoTaskMem outputs, and synchronous JavaScript implementations of fully supported callback interfaces. +Separate bounded one-shot audio activation and owned-copy transactions are +also available; copy-only facades are not counted as complete interfaces. Seventeen stock-Windows Node E2E runners exercise representative Shell, Automation, stream, callback, HWND, and WinRT interop scenarios. @@ -178,6 +180,14 @@ the documented in-process, null-parameter audio endpoint subset and `activate(IAudioClient)` and `DynComAudioFormat.pcm()` format negotiation, without a per-interface native adapter. +Existing distinguishable overloads keep their APIs unchanged. Otherwise fully +validated normal COM overload groups with colliding JavaScript signatures or +projected buffers now expose every member as +`AtSlot`, with no ambiguous unsuffixed method. +This naming-only projection promotes 24 interfaces; it does not guess ABI +contracts or provide a universal overload parser. See the +[overload usage and limits](docs/guides/windows/classic-com-usage.md#58-explicit-overload-names). + - [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) diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 74a1afd3..3c2c4840 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -348,7 +348,7 @@ Current code registries are migrated without changing behavior: - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,697/7,929 safe census, generated unsafe manifests, and all live tests agree +5,721/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -448,19 +448,27 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,332 | -| `exact_registry_dependent` | 365 | -| **Total** | **5,697** | +| `standard_derived` | 5,355 | +| `exact_registry_dependent` | 366 | +| **Total** | **5,721** | The registry contains **532 declared entries**, all 532 match the pinned metadata, and 431 distinct entries are consumed by complete safe plans. These plans have -693 entry/interface dependencies and 424 family/interface dependencies. -Per-interface dependency-set totals also include 5,983 metadata-attribute -dependencies and 26,134 COM-standard-rule dependencies. +694 entry/interface dependencies and 425 family/interface dependencies. +Per-interface dependency-set totals also include 6,012 metadata-attribute +dependencies and 26,247 COM-standard-rule dependencies. + +PR4's explicit overload names promote 24 previously raw-metadata-complete +interfaces: 23 standard-derived and one exact-registry-dependent. +`IGenericDescriptor2` now consumes the existing `IGenericDescriptor::GetBody` +slot-6 ownership entry, bringing that entry's interface dependencies from one +to two. No entries are added: registered/matched and distinct safe-consumed +entry counts remain 532 and 431. The new names select already validated +normal methods; they do not supply missing ABI, ownership, or lifetime facts. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 182 | +| `ownership` | 183 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 10 | @@ -485,7 +493,7 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 169 | 118 | 123 | +| `com.ownership.v1` | 169 | 118 | 124 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | | `com.nullable-input.v1` | 2 | 2 | 2 | @@ -518,12 +526,12 @@ Universal rule dependencies are: | `com.automation.bstr-replacement.v1` | 99 | | `com.enumerator-next.generic.v1` | 25 | | `com.handle.borrowed-no-cleanup.v1` | 45 | -| `com.hresult.failure.v1` | 5,579 | -| `com.interface.input-borrow.v1` | 1,890 | -| `com.interface.typed-output-plus-one.v1` | 3,458 | -| `com.iunknown.identity-refcount.v1` | 5,697 | -| `com.query-interface.output-plus-one.v1` | 5,697 | -| `com.standard-cleanup.matching-allocator.v1` | 1,437 | +| `com.hresult.failure.v1` | 5,603 | +| `com.interface.input-borrow.v1` | 1,908 | +| `com.interface.typed-output-plus-one.v1` | 3,480 | +| `com.iunknown.identity-refcount.v1` | 5,721 | +| `com.query-interface.output-plus-one.v1` | 5,721 | +| `com.standard-cleanup.matching-allocator.v1` | 1,438 | These are dependency counts: an inherited contract can be consumed by several interfaces, and one interface can consume several IDs or kinds. They are not @@ -575,3 +583,7 @@ helpers. Delete existing generated bindings and completely regenerate every selected root with matching updated runtime/codegen versions; there is no in-place migration or support for mixed old/new generated classes. The contract-data schema is unaffected, as are other generated `.as(...)` paths. + +PR4 requires no further manifest change. Already-supported safe output, +including distinguishable overload dispatch, remains byte-identical; +previously rejected overload groups had no valid safe surface to migrate. diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index a6200663..9c8ffb55 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -123,6 +123,23 @@ Codegen uses the same capability classifier as `com-capability-census`. The complete inherited interface passes the existing safe semantic projection. Generate the existing safe class and no unsafe replacement. +PR4 resolves previously rejected overload groups only after every member has a +fully validated normal COM call plan. Colliding JavaScript arity/shapes or +projected buffers receive explicit +`AtSlot` names for every member, with no +ambiguous unsuffixed method. Existing distinguishable dispatch stays +unchanged; collisions with projected members and synthesized/dynamic-IID/ +non-normal groups still fail closed. Renderers consume the selected IR names +without guessing runtime types or native semantics. + +This promotes 24 raw-metadata-complete interfaces, bringing complete safe +coverage to **5,721 / 7,929** and leaving **2,208** incomplete interfaces. +Promoted interfaces receive no duplicate unsafe companion. Native ABI, +conversion, lifetime, and raw-runtime capabilities remain unchanged, and +PR3's copy-only facades remain excluded from complete safe coverage. +Already-supported safe output remains byte-identical, so PR4 needs no +additional manifest version. + ### Raw metadata complete Metadata contains every fact needed to express the outbound ABI through Phase 1 @@ -598,7 +615,7 @@ trailing dots/spaces, and Windows device names (`CON`, `PRN`, `AUX`, `NUL`, `CLOCK$`, `CONIN$`, `CONOUT$`, `COM1`-`COM9`, and `LPT1`-`LPT9`), including device names with extensions. -Retained schema-11 `modulePath` is never trusted. Codegen rederives it from the +Retained schema-12 `modulePath` is never trusted. Codegen rederives it from the validated qualified interface identity and exact `Unsafe` class name, requires an exact match, and then checks the case-insensitive path key. Case-only namespaces or type names therefore fail instead of aliasing on @@ -707,17 +724,19 @@ Stage 2 is implemented: arguments; - parameter requirements come from the same per-target classifier analysis; - runtime-blocked methods remain omitted; -- support schema 11 records every parameter index/name, strategy type, exact +- support schema 12 records every parameter index/name, strategy type, exact reason, native direction/nullability, and known target pointee layouts; and - a raw pointer is never substituted for missing ownership. -For official 71.0.14 metadata, **1,442 of 1,446** x64 manual-contract interfaces -have at least one portable executable generated high-level method. **1,441** +For official 71.0.14-preview metadata, **1,427 of 1,431** x64 manual-contract interfaces +have at least one portable executable generated high-level method. **1,426** have an executable manual method, one retains only metadata-complete methods, and four have no portable executable method because every candidate is blocked -on another generated target. There are **6,083** portable executable manual +on another generated target. There are **6,046** portable executable manual methods, **0** remaining portable manual-classified methods omitted, and -**1,163** cross-target runtime-blocked methods still omitted. +**1,161** cross-target runtime-blocked methods still omitted. The existing +`official_stage2_coverage_is_exact` test confirms these measurements are +unchanged by PR4; its promotions come from the raw-metadata-complete bucket. ### Stage 3 diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index b47c3d68..64ebc2e8 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -4,8 +4,8 @@ general Automation or native Win32 projection. > **Status: preview, under active development.** The current CI baseline against -> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,697 complete safe -> interface projections out of 7,929 eligible interfaces (71.85%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,721 complete safe +> interface projections out of 7,929 eligible interfaces (72.15%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -154,6 +154,31 @@ renderer cannot see `TypeMeta` or metadata attributes and has no default pointer/Buffer fallback; it only serializes the validated projected IR with exhaustive type matches. +## Explicit COM overload names + +Existing overload groups with distinguishable JavaScript arity/shape retain +their exact dispatch and generated API. PR4 handles previously rejected +groups only when every member is an otherwise fully validated **normal COM +method**. Groups with colliding JavaScript signatures or projected buffers +receive deterministic public names +`AtSlot` for **every** member; the ambiguous +unsuffixed method is absent. + +The slot is the absolute inherited vtable slot, not an overload ordinal. +For example, `ID2D1Device1::CreateDeviceContext` produces two explicit +`createDeviceContextAtSlot...` members; the generated declarations give their +exact names and return types. Native method names, slots, ABI signatures, +conversions, and lifetime plans are unchanged. Projection selects the names in +IR; the renderer only serializes them and adds no runtime type or ABI guesses. + +Alias collisions with actual projected members fail closed. Synthesized, +dynamic-IID, and other non-normal method groups still reject; this is not a +universal overloaded-method parser or a way around incomplete native +contracts. See the [usage guide](../guides/windows/classic-com-usage.md#58-explicit-overload-names). +PR4 does not change COM manifest version 4 or unsafe support schema 12: +already-supported safe output remains byte-identical, and the newly admitted +groups previously had no valid safe surface. + ## Bounded native one-shot completion The first supported flat export is the exact @@ -262,8 +287,8 @@ interface projections. They do not expose `GetBuffer`, `ReleaseBuffer`, `Lock`, or `Unlock` independently. WIC retains its previously complete native interface surface (including acquisition of an opaque owned lock) and adds the copy operation. An external lock never gains byte access or writable rights from -this operation. The complete safe census remains **5,697 / 7,929**; it does not -count the three copy-only facades as newly complete interfaces. +this operation. The three copy-only facades remain excluded from the current +**5,721 / 7,929** complete safe census. ### Private context and lifecycle @@ -793,7 +818,7 @@ not be described as solving every problem in the map above. | Fail-closed generation | Unknown/unsafe layouts, untagged/by-value/output unions, bitfields, flexible arrays, nested owned fields, unsupported VARTYPE/BYREF/SAFEARRAY/PROPVARIANT combinations, unsupported arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | | Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. The generated package root is always WinRT-only; COM-only output deliberately has no root entrypoint. | | Explicit vtable registration | Every generated method is registered with `.addMethodAt(vtableIndex, name, signature)`, keyed by its actual metadata-derived vtable slot. Methods are never deduplicated by name, so same-name overloads at different slots both register correctly. | -| Same-name overload projection | Overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) are grouped once during projection (not by renderer heuristics). A single public JS method dispatches to a private per-slot implementation using only a validated, mutually-distinguishable arity/shape key (`typeof`-based: boolean/number/bigint/string/object); ambiguous groups fail generation closed with a diagnostic naming the interface, method, and reason. The `.d.ts` emits one TypeScript overload signature per branch, contiguously. | +| Same-name overload projection | Existing distinguishable overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) retain their single public dispatcher, validated arity/shape keys, and contiguous TypeScript overload signatures. Previously rejected groups of fully validated normal methods use explicit `AtSlot` names for every member and omit the ambiguous unsuffixed name. Projection selects these names; the renderer does not infer ABI semantics. Collisions and non-normal groups fail closed. | | Lifecycle ergonomics | Generated interface wrappers declare a protected constructor (`protected constructor(obj: unknown);`) so only generated coclasses can subclass them. Coclasses expose a public zero-argument constructor, and every wrapper provides an idempotent `release()` that delegates to the managed native value. Factory-activated interop wrappers retain `static create()` with JSDoc reminding callers to initialize COM first. | | Doc-link rendering | When win32metadata attaches a `DocumentationAttribute` (a `learn.microsoft.com` URL) to a method, the generator renders it as an `@see {@link ...}` comment in both `.js` and `.d.ts`. No raw metadata is imported into the renderer — the URL is threaded through `ProjectedComMethod.doc`, populated once during projection. | | Acronym-aware parameter casing | Parameter names are lowered using the same acronym-run-aware rule as method names, so a Hungarian-prefixed trailing acronym like `hwndMDI` projects as `mdi` (not the previous naive `mDI`). | @@ -1609,13 +1634,15 @@ restricting InOut to proven caller-allocation-preserving contracts, bringing that census to 5,691. The variable-length WAVEFORMATEX model and three pinned audio method contracts promote five more interfaces, bringing that census to 5,696. The exact `IMMDevice::Activate` and `GetId` contracts promote one more -complete interface, bringing the current literal census to -**5,697 / 7,929 = 71.850170%**. The result remains above the +complete interface, bringing that census to 5,697, unchanged by PR2 completion +and PR3 copy-only facades. PR4's explicit overload names move 24 previously +raw-metadata-complete interfaces into the safe set, bringing the current +literal census to **5,721 / 7,929 = 72.152857%**. The result remains above the 70% target without admitting any unmodeled target-device, storage-medium, audio-output ownership, ownership-transfer, or callback shape. CI reproduces this number with `dynwinrt-codegen com-census --json` and fails -if the denominator changes, complete generation drops below 5,697, or coverage +if the denominator changes, complete generation drops below 5,721, or coverage falls below 70%. ## Public-code frequency snapshot diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 59c20bd5..694351be 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -817,6 +817,37 @@ external WIC locks are not supported. See the [exact lifecycle/evidence contract](../../architecture/classic-com-support.md#bounded-borrowed-buffer-copies) for supported formats, HRESULT handling, and validation. +### 5.8 Explicit overload names + +Existing overloads that codegen can distinguish by JavaScript arity/shape keep +their current names and dispatch unchanged. PR4 also admits previously +rejected groups of otherwise fully validated **normal COM methods** whose +JavaScript signatures collide or use projected buffers. Every member receives +`AtSlot`; there is no ambiguous unsuffixed method +and no extra slot argument to pass. + +For example, generate `Windows.Win32.Graphics.Direct2D.ID2D1Device1` and inspect +its `.d.ts`. Its two inherited `CreateDeviceContext` slots become distinct +`createDeviceContextAtSlot...` methods instead of `createDeviceContext`. +Schematically, where `N` and `M` mean the actual absolute metadata slots: + +```text +createDeviceContextAtSlotN(options) +createDeviceContextAtSlotM(options) +``` + +Use the exact name and typed signature from the generated declaration for the +native overload you need. These deterministic names preserve the native slot, +arguments, result conversion, and lifetime contract; changing JavaScript +values is not a way to select an absent unsuffixed method. + +Alias collisions with actual projected member names fail closed. +Synthesized, dynamic-IID, and other non-normal groups still reject, as do +incomplete ABI or ownership contracts. This is not a universal overload +parser. PR4 preserves already-supported generated APIs byte-for-byte and +requires no new manifest version; the manifest 4 / support schema 12 upgrade +requirements for older borrowed-copy output still apply. + ## 6. JavaScript projections of common native types | Native semantics | JavaScript/TypeScript | diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 78826204..967dc67e 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -32,17 +32,28 @@ B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D | Result | Interfaces | Percentage | | ---------------------------------------------------- | ---------: | ---------: | | Externally addressable Classic COM interfaces | 7,929 | 100% | -| Complete safe generation | 5,697 | 71.85% | -| Rejected because at least one contract is incomplete | 2,232 | 28.15% | +| Complete safe generation | 5,721 | 72.15% | +| Rejected because at least one contract is incomplete | 2,208 | 27.85% | The denominator contains addressable COM interface identities, not flat Win32 DLL exports. A complete interface means that its full inherited vtable can be generated without guessing ABI, layout, count relationships, ownership, or cleanup. -The 5,697 figure is semantic codegen coverage, not a claim that every interface +The 5,721 figure is semantic codegen coverage, not a claim that every interface has a dedicated live Windows test or can be activated on every machine. +PR4 promotes **24** previously raw-metadata-complete interfaces by naming +otherwise validated normal overloads explicitly. Every member of a formerly +rejected same-shape/arity or projected-buffer group receives +`AtSlot`; the ambiguous unsuffixed method is not +emitted. Existing distinguishable overload dispatch, native ABI/conversion/ +lifetime plans, and already-supported generated output remain unchanged. +Alias collisions and synthesized/dynamic-IID/non-normal groups still fail +closed. This needs no further manifest version change and does not turn the +PR3 bounded-copy facades into complete native interface projections. +See [overload usage and limits](../guides/windows/classic-com-usage.md#58-explicit-overload-names). + Reproduce the census with: ```powershell @@ -269,7 +280,7 @@ non-addressable identities block every method before companion selection. `MFASYNCRESULT` therefore produces no callable class. When an interface has no executable method, generation transactionally commits -a schema-11 report containing every blocked/manual method and exact reasons, +a schema-12 report containing every blocked/manual method and exact reasons, emits no class `.js`/`.d.ts`, and then exits nonzero. The metadata record is a sorted, deduplicated set of every loaded emission/reference/sibling winmd, with per-file hashes, a set hash, and an optional exact defining file; it contains no @@ -323,7 +334,7 @@ generated `runtime.js`/`.d.ts` provides closed pointee, pointer-output, handle, interface-replacement, counted-buffer, owned-pointer, and raw-fallback strategies. Generated methods validate strategy types before dispatch, clean dirty HRESULT failure outputs according to the selected strategy, and report -exact per-parameter requirements in support schema 11. +exact per-parameter requirements in support schema 12. Strategy capabilities are unforgeable frozen objects backed by private WeakMaps. Private generated helpers perform prepare, writable-span overlap @@ -370,25 +381,30 @@ and **1,161 runtime-blocked methods** still omitted. Stage 1 of the [Classic COM contract evidence registry](../architecture/classic-com-contract-evidence-registry.md) -classifies all 5,697 safe-complete interfaces exactly once: +classifies all 5,721 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,332 | -| `exact_registry_dependent` | 365 | +| `standard_derived` | 5,355 | +| `exact_registry_dependent` | 366 | The registry declares 532 selector-specific entries; all 532 match pinned -metadata, 431 distinct entries are consumed by complete safe plans, which contain 693 -entry/interface plus 424 family/interface dependencies. They also consume -5,983 metadata-attribute and 26,134 universal COM-rule dependency sets. +metadata, 431 distinct entries are consumed by complete safe plans, which contain 694 +entry/interface plus 425 family/interface dependencies. They also consume +6,012 metadata-attribute and 26,247 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 182, parameter-direction 45, bounded-two-call 16, +borrowed-handle 54, ownership 183, parameter-direction 45, bounded-two-call 16, counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 4, semantic-HRESULT 3, compound-dispatch 1, borrowed-storage 15, and contextual-effect 7. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. These are dependency counts, not net contribution; no ablation claim is made. +The 24 PR4 promotions comprise 23 standard-derived interfaces and one +exact-registry-dependent interface, `IGenericDescriptor2`. Its inherited +`GetBody` reuses an existing slot-6 ownership entry; no registry entries or +distinct safe-consumed entries are added. + Borrowed buffers now have synchronous **owned-copy** transactions for WASAPI render/capture, STA WIC BGRA8 locks, and linear `IMFMediaBuffer`. Audio requires observed successful initialization and GetService provenance; external @@ -415,7 +431,7 @@ placeholder WAVEFORMATEX. Other audio-format inputs remain required. contract, and `IMMDevice::GetId` adds a JSON-backed slot-5 CoTaskMem ownership entry. Both are consumed by the complete safe endpoint plan. The `com.ownership.v1` family now has 169 registered entries, 118 safe-used -entries, and 123 family/interface dependencies. +entries, and 124 family/interface dependencies. The storage-medium contracts also pin `IOleCache::SetData` (including inherited `IOleCache2` calls) to caller-retained ownership and describe the distinct @@ -440,19 +456,24 @@ allocator, or ownership declaration can corrupt memory or crash the process. For `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview (`Windows.Win32.winmd` SHA-256 `B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`), -the safe census is 5,697 of 7,929 interfaces. The separate outbound raw census -classifies the 2,232 safe-incomplete interfaces as: +the safe census is 5,721 of 7,929 interfaces. The separate outbound raw census +classifies the 2,208 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,431 | 389 | -| i686 | 411 | 1,408 | 413 | -| ARM64 | 412 | 1,431 | 389 | +| x64 | 388 | 1,431 | 389 | +| i686 | 387 | 1,408 | 413 | +| ARM64 | 388 | 1,431 | 389 | Including safe-complete interfaces, x64 and ARM64 have 6,109 metadata-complete, 1,431 manual, and 389 blocked interfaces. i686 has 6,108 metadata-complete, 1,408 manual, and 413 blocked interfaces. +These all-interface raw totals are unchanged by PR4: all 24 promotions come +from the safe-incomplete raw-metadata-complete bucket. Manual/runtime-blocked +classifications and the measured Stage 2 executable-method totals are +unchanged. + Pointer-shaped types are analyzed recursively. A missing pointee layout for an external input pointer is manual-contract; the same missing layout for a writable/readable `T*` caller-storage contract is runtime-blocked. Thus @@ -468,7 +489,7 @@ External pointer/callback requirements affect 1,089 x64/ARM64 interfaces and 1,090 i686 interfaces; 6,804 require external acquisition and all 7,929 retain the current-apartment rule. -For all 5,697 safe-complete interfaces, cleanup is derived from the validated +For all 5,721 safe-complete interfaces, cleanup is derived from the validated projected result conversions rather than the raw analyzer. Pure values, borrowed handles, caller buffers, and plain arrays are `none_required`. Managed COM/dynamic-IID adoption, BSTR, HSTRING, CoTaskMem, VARIANT, @@ -555,7 +576,7 @@ as ABI support. The legacy `com-census --json` output remains unchanged. ## Copyable user-facing statement > dynwinrt supports the Classic COM interface portion of Windows.Win32 -> metadata. With Win32Metadata 71.0.14-preview, 5,697 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,721 of 7,929 addressable COM > interfaces pass complete safe generation. Safe symbols never fall back to an > unsafe implementation; ordinary generation may instead emit an explicitly > named `*Unsafe` outbound companion containing only metadata-complete methods. diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 808f2d03..4df35312 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -80,19 +80,19 @@ "parsed_interface_identities": 7944, "eligible_interfaces": 7929, "not_addressable": 15, - "safe_complete": 5697, - "safe_incomplete": 2232, + "safe_complete": 5721, + "safe_incomplete": 2208, "safeEvidence": { - "safeComplete": 5697, - "standardDerived": 5332, - "exactRegistryDependent": 365, - "metadataFactOccurrences": 5983, - "comStandardFactOccurrences": 26134, + "safeComplete": 5721, + "standardDerived": 5355, + "exactRegistryDependent": 366, + "metadataFactOccurrences": 6012, + "comStandardFactOccurrences": 26247, "registeredExactEntries": 532, "metadataMatchedExactEntries": 532, "safeConsumedExactEntries": 431, - "exactEntryInterfaceDependencies": 693, - "exactFamilyInterfaceDependencies": 424, + "exactEntryInterfaceDependencies": 694, + "exactFamilyInterfaceDependencies": 425, "byContractKind": { "borrowed-handle": 54, "borrowed-storage": 15, @@ -104,7 +104,7 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 4, - "ownership": 182, + "ownership": 183, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 @@ -404,7 +404,7 @@ "com.ownership.entry.windows-win32-media-directshow-tv.iatsc-vct.26879a1832f946c691f0fb6479270e8c.getrecordname.slot-8.param-1-pwsname.v1": 1, "com.ownership.entry.windows-win32-media-directshow-tv.iatsccontentadvisorydescriptor.ff76e60c028343eaba32b422238547ee.getrecordratingdescriptiontext.slot-10.param-2-pptext.v1": 1, "com.ownership.entry.windows-win32-media-directshow-tv.idvb-st.4d5b9f232a0245debcda5d5dbfbfbe62.getdata.slot-5.param-0-ppdata.v1": 1, - "com.ownership.entry.windows-win32-media-directshow-tv.igenericdescriptor.6a5918f8a77a4f61aed05702bdcda3e6.getbody.slot-6.param-0-ppbval.v1": 1, + "com.ownership.entry.windows-win32-media-directshow-tv.igenericdescriptor.6a5918f8a77a4f61aed05702bdcda3e6.getbody.slot-6.param-0-ppbval.v1": 2, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure.ce14dfae40984af7bbf7d6511f835414.getdirectory.slot-4.param-0-ppszdirectoryname.v1": 3, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure3.7e2d2a1e71924bd780c1061fd1d10402.getnamespace.slot-16.param-0-ppsznamespace.v1": 1, "com.ownership.entry.windows-win32-media-directshow.iamdeviceremoval.f90a6130b65811d2ae490000f8754b99.deviceinfo.slot-3.param-1-pwszsymboliclink.v1": 1, @@ -552,7 +552,7 @@ "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, "com.nullable-input.v1": 2, - "com.ownership.v1": 123, + "com.ownership.v1": 124, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 3, @@ -563,9 +563,9 @@ }, "byMetadataAttribute": { "CanReturnMultipleSuccessValuesAttribute": 46, - "ConstAttribute": 3332, + "ConstAttribute": 3351, "FreeWithAttribute": 3, - "NativeArrayInfoAttribute": 2602 + "NativeArrayInfoAttribute": 2612 }, "byStandardRuleId": { "com.activation.output-plus-one.v1": 976, @@ -573,12 +573,12 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5579, - "com.interface.input-borrow.v1": 1890, - "com.interface.typed-output-plus-one.v1": 3458, - "com.iunknown.identity-refcount.v1": 5697, - "com.query-interface.output-plus-one.v1": 5697, - "com.standard-cleanup.matching-allocator.v1": 1437 + "com.hresult.failure.v1": 5603, + "com.interface.input-borrow.v1": 1908, + "com.interface.typed-output-plus-one.v1": 3480, + "com.iunknown.identity-refcount.v1": 5721, + "com.query-interface.output-plus-one.v1": 5721, + "com.standard-cleanup.matching-allocator.v1": 1438 }, "exactEntryStatus": { "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": { @@ -7419,7 +7419,7 @@ "registered": true, "metadataMatched": true, "safeConsumed": true, - "interfaceDependencies": 1 + "interfaceDependencies": 2 }, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure.ce14dfae40984af7bbf7d6511f835414.getdirectory.slot-4.param-0-ppszdirectoryname.v1": { "familyId": "com.ownership.v1", @@ -11356,7 +11356,7 @@ "raw_metadata_complete": 6109, "raw_manual_contract": 1431, "raw_runtime_blocked": 389, - "safe_incomplete_raw_metadata_complete": 412, + "safe_incomplete_raw_metadata_complete": 388, "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 }, @@ -11364,7 +11364,7 @@ "raw_metadata_complete": 6108, "raw_manual_contract": 1408, "raw_runtime_blocked": 413, - "safe_incomplete_raw_metadata_complete": 411, + "safe_incomplete_raw_metadata_complete": 387, "safe_incomplete_raw_manual_contract": 1408, "safe_incomplete_raw_runtime_blocked": 413 }, @@ -11372,7 +11372,7 @@ "raw_metadata_complete": 6109, "raw_manual_contract": 1431, "raw_runtime_blocked": 389, - "safe_incomplete_raw_metadata_complete": 412, + "safe_incomplete_raw_metadata_complete": 388, "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 } diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 7a0d55f1..f2848afe 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -13,7 +13,7 @@ Windows.Win32.AI.MachineLearning.DirectML,IDMLOperatorInitializer,427c1113-435c- Windows.Win32.AI.MachineLearning.DirectML,IDMLPageable,b1ab0825-4542-4a4b-8617-6dde6e8f6201,false,,external_pointee_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorAttributes,4b1b1759-ec40-466c-aab4-beb5347fd24c,false,,external_pointee_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernel,11c4b4a0-b467-4eaa-a1a6-b961d8d0ed79,true,standard_derived, -Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelContext,82536a28-f022-4769-9d3f-8b278f84c0c3,false,,safe_projection_incomplete +Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelContext,82536a28-f022-4769-9d3f-8b278f84c0c3,true,standard_derived, Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelCreationContext,5459b53d-a0fc-4665-addd-70171ef7e631,false,,incomplete_pointee_layout_for_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelFactory,ef15ad6f-0dc9-4908-ab35-a575a30dfbf8,true,standard_derived, Windows.Win32.AI.MachineLearning.WinML,IMLOperatorRegistry,2af9dd2d-b516-4672-9ab5-530c208493ad,false,,external_pointee_storage @@ -565,13 +565,13 @@ Windows.Win32.Graphics.Direct2D,ID2D1ComputeTransform,0d85573c-01e3-4f7d-bfd9-0d Windows.Win32.Graphics.Direct2D,ID2D1ConcreteTransform,1a799d8a-69f7-4e4c-9fed-437ccc6684cc,true,standard_derived, Windows.Win32.Graphics.Direct2D,ID2D1DCRenderTarget,1c51bc64-de61-46fd-9899-63a5d8f03950,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1Device,47dd575d-ac05-4cdd-8049-9b02cd16f44c,true,standard_derived, -Windows.Win32.Graphics.Direct2D,ID2D1Device1,d21768e1-23a4-4823-a14b-7c3eba85d658,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device2,a44472e1-8dfb-4e60-8492-6e2861c9ca8b,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device3,852f2087-802c-4037-ab60-ff2e7ee6fc01,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device4,d7bdb159-5683-4a46-bc9c-72dc720b858b,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device5,d55ba0a4-6405-4694-aef5-08ee1a4358b4,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device6,7bfef914-2d75-4bad-be87-e18ddb077b6d,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device7,f07c8968-dd4e-4ba6-9cbd-eb6d3752dcbb,false,,safe_projection_incomplete +Windows.Win32.Graphics.Direct2D,ID2D1Device1,d21768e1-23a4-4823-a14b-7c3eba85d658,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device2,a44472e1-8dfb-4e60-8492-6e2861c9ca8b,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device3,852f2087-802c-4037-ab60-ff2e7ee6fc01,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device4,d7bdb159-5683-4a46-bc9c-72dc720b858b,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device5,d55ba0a4-6405-4694-aef5-08ee1a4358b4,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device6,7bfef914-2d75-4bad-be87-e18ddb077b6d,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device7,f07c8968-dd4e-4ba6-9cbd-eb6d3752dcbb,true,standard_derived, Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext,e8f7fe7a-191c-466d-ad95-975678bda998,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext1,d37f57e4-6908-459f-a199-e72f24f79987,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext2,394ea6a3-0c34-4321-950b-6ca20f0be6c7,false,,incomplete_pointee_layout_for_storage @@ -968,7 +968,7 @@ Windows.Win32.Graphics.DirectComposition,IDCompositionDevice3,0987cb06-f916-48bf Windows.Win32.Graphics.DirectComposition,IDCompositionDevice4,85fc5cca-2da6-494c-86b6-4a775c049b8a,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionDevice5,2c6bebfe-a603-472f-af34-d2443356e61b,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionDeviceDebug,a1a3c64a-224f-4a81-9773-4f03a89d3c6c,true,standard_derived, -Windows.Win32.Graphics.DirectComposition,IDCompositionDynamicTexture,a1de1d3f-6405-447f-8e95-1383a34b0277,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectComposition,IDCompositionDynamicTexture,a1de1d3f-6405-447f-8e95-1383a34b0277,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionEffect,ec81b08f-bfcb-4e8d-b193-a915587999e8,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionEffectGroup,a7929a74-e6b2-4bd6-8b95-4040119ca34d,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionFilterEffect,30c421d5-8cb2-4e9f-b133-37be270d4ac2,true,standard_derived, @@ -1058,8 +1058,8 @@ Windows.Win32.Graphics.DirectWrite,IDWriteFont1,acd16696-8c14-4f5d-877e-fe3fc1d3 Windows.Win32.Graphics.DirectWrite,IDWriteFont2,29748ed6-8c9c-4a6a-be0b-d912e8538944,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteFont3,29748ed6-8c9c-4a6a-be0b-d912e8538944,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection,a84cee02-3eea-4eee-a827-87c1a02a0fcc,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection1,53585141-d9f8-4095-8321-d73cf6bd116c,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection2,514039c6-4617-4064-bf8b-92ea83e506e0,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection1,53585141-d9f8-4095-8321-d73cf6bd116c,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection2,514039c6-4617-4064-bf8b-92ea83e506e0,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection3,a4d055a6-f9e3-4e25-93b7-9e309f3af8e9,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontCollectionLoader,cca920e4-52f0-492b-bfa8-29c72ee0a468,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontDownloadListener,b06fe5b9-43ec-4393-881b-dbe4dc72fda7,true,standard_derived, @@ -1075,29 +1075,29 @@ Windows.Win32.Graphics.DirectWrite,IDWriteFontFace7,3945b85b-bc95-40f7-b72c-8b73 Windows.Win32.Graphics.DirectWrite,IDWriteFontFaceReference,5e7fa7ca-dde3-424c-89f0-9fcd6fed58cd,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFaceReference1,c081fe77-2fd1-41ac-a5a3-34983c4ba61a,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback,efa008f9-f7a1-48bf-b05c-f224713cc0ff,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback1,2397599d-dd0d-4681-bd6a-f4f31eaade77,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback1,2397599d-dd0d-4681-bd6a-f4f31eaade77,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFallbackBuilder,fd882d06-8aba-4fb8-b849-8be8b73e14de,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily,da20d8ef-812a-4c43-9802-62ec4abd7add,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily1,da20d8ef-812a-4c43-9802-62ec4abd7adf,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily2,3ed49e77-a398-4261-b9cf-c126c2131ef3,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily1,da20d8ef-812a-4c43-9802-62ec4abd7adf,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily2,3ed49e77-a398-4261-b9cf-c126c2131ef3,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFile,739d886a-cef5-47dc-8769-1a8b41bebbb0,false,,missing_allocator Windows.Win32.Graphics.DirectWrite,IDWriteFontFileEnumerator,72755049-5ff7-435d-8348-4be97cfa6c7c,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFileLoader,727cad4e-d6af-4c9e-8a08-d695b11caa49,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFileStream,6d4865fe-0ab8-4d91-8f62-5dd6be34a3e0,false,,external_pointee_storage Windows.Win32.Graphics.DirectWrite,IDWriteFontList,1a0d8438-1d97-4ec1-aef9-a2fb86ed6acb,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontList1,da20d8ef-812a-4c43-9802-62ec4abd7ade,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontList2,c0763a34-77af-445a-b735-08c37b0a5bf5,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontList1,da20d8ef-812a-4c43-9802-62ec4abd7ade,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontList2,c0763a34-77af-445a-b735-08c37b0a5bf5,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontResource,1f803a76-6871-48e8-987f-b975551c50f2,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSet,53585141-d9f8-4095-8321-d73cf6bd116b,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontSet,53585141-d9f8-4095-8321-d73cf6bd116b,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontSet1,7e9fda85-6c92-4053-bc47-7ae3530db4d3,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontSet2,dc7ead19-e54c-43af-b2da-4e2b79ba3f7f,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontSet3,7c073ef2-a7f4-4045-8c32-8ab8ae640f90,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontSet4,eec175fc-bea9-4c86-8b53-ccbdd7df0c82,false,,missing_count_relation -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder,2f642afe-9c68-4f40-b8be-457401afcb3d,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder1,3ff7715f-3cdc-4dc6-9b72-ec5621dccafd,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder2,ee5ba612-b131-463c-8f4f-3189b9401e45,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder,2f642afe-9c68-4f40-b8be-457401afcb3d,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder1,3ff7715f-3cdc-4dc6-9b72-ec5621dccafd,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder2,ee5ba612-b131-463c-8f4f-3189b9401e45,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop,1edd9491-9853-4299-898f-6432983b6f3a,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop1,4556be70-3abd-4f70-90be-421780a6f515,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop1,4556be70-3abd-4f70-90be-421780a6f515,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteGlyphRunAnalysis,7d97dbf7-e085-42d4-81e3-6a883bded118,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteInMemoryFontFileLoader,dc102f47-a12d-4b1c-822d-9e117e33043f,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteInlineObject,8339fde3-106f-47ab-8373-1c6295eb10b3,true,standard_derived, @@ -1122,7 +1122,7 @@ Windows.Win32.Graphics.DirectWrite,IDWriteTextAnalyzer1,80dad800-e21f-4e83-96ce- Windows.Win32.Graphics.DirectWrite,IDWriteTextAnalyzer2,553a9ff3-5693-4df7-b52b-74806f7f2eb9,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat,9c906818-31d7-4fd3-a151-7c5e225db55a,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat1,5f174b49-0d8b-4cfb-8bca-f1cce9d06c67,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat2,f67e0edd-9e3d-4ecc-8c32-4183253dfe70,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat2,f67e0edd-9e3d-4ecc-8c32-4183253dfe70,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat3,6d3b5641-e550-430d-a85b-b7bf48a93427,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteTextLayout,53737037-6d14-410b-9bfe-0b182bb70961,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteTextLayout1,9064d822-80a7-465c-a986-df65f78b8feb,false,,incomplete_pointee_layout_for_storage @@ -1945,7 +1945,7 @@ Windows.Win32.Media.DirectShow.Tv,IEnumTuneRequests,1993299c-ced6-4788-87a3-4200 Windows.Win32.Media.DirectShow.Tv,IEnumTuningSpaces,8b8eb248-fc2b-11d2-9d8c-00c04f72d980,true,exact_registry_dependent, Windows.Win32.Media.DirectShow.Tv,IEvalRat,c5c5c5b1-3abc-11d6-b25b-00c04fa0c026,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor,6a5918f8-a77a-4f61-aed0-5702bdcda3e6,true,exact_registry_dependent, -Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor2,bf02fb7e-9792-4e10-a68d-033a2cc246a5,false,,safe_projection_incomplete +Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor2,bf02fb7e-9792-4e10-a68d-033a2cc246a5,true,exact_registry_dependent, Windows.Win32.Media.DirectShow.Tv,IGpnvsCommonBase,907e0b5c-e42d-4f04-91f0-26f401f36907,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGuideData,61571138-5b01-43cd-aeaf-60b784a0bf93,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGuideDataEvent,efda0c80-f395-42c3-9b3c-56b37dec7bb7,true,standard_derived, @@ -1973,7 +1973,7 @@ Windows.Win32.Media.DirectShow.Tv,IIsdbHierarchicalTransmissionDescriptor,b7b3ae Windows.Win32.Media.DirectShow.Tv,IIsdbLogoTransmissionDescriptor,e0103f49-4ae1-4f07-9098-756db1fa88cd,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbSIParameterDescriptor,f837dc36-867c-426a-9111-f62093951a45,false,,incomplete_pointee_layout_for_storage Windows.Win32.Media.DirectShow.Tv,IIsdbSeriesDescriptor,07ef6370-1660-4f26-87fc-614adab24b11,false,,incomplete_pointee_layout_for_storage -Windows.Win32.Media.DirectShow.Tv,IIsdbSiParser2,900e4bb7-18cd-453f-98be-3be6aa211772,false,,safe_projection_incomplete +Windows.Win32.Media.DirectShow.Tv,IIsdbSiParser2,900e4bb7-18cd-453f-98be-3be6aa211772,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbTSInformationDescriptor,d7ad183e-38f5-4210-b55f-ec8d601bbd47,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbTerrestrialDeliverySystemDescriptor,39fae0a6-d151-44dd-a28a-765de5991670,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,ILanguageComponentType,b874c8ba-0fa2-11d3-9d8e-00c04f72d980,false,,incomplete_pointee_layout_for_storage diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 0bb45559..04375dbb 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4557,11 +4557,11 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_697); - assert_eq!(report.summary.safe_incomplete, 2_232); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_697); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_332); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 365); + assert_eq!(report.summary.safe_complete, 5_721); + assert_eq!(report.summary.safe_incomplete, 2_208); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_721); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_355); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 366); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4569,11 +4569,11 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.metadata_fact_occurrences, - 5_983 + 6_012 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_134 + 26_247 ); assert_eq!(report.summary.safe_evidence.registered_exact_entries, 532); assert_eq!( @@ -4589,14 +4589,14 @@ mod tests { .summary .safe_evidence .exact_entry_interface_dependencies, - 693 + 694 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 424 + 425 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4611,7 +4611,7 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 4), - ("ownership".into(), 182), + ("ownership".into(), 183), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 3), @@ -4619,7 +4619,7 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 123 + 124 ); assert_eq!( report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], @@ -4888,7 +4888,7 @@ mod tests { counts.safe_incomplete_raw_runtime_blocked, ), ( - 412 - usize::from(target == CensusTarget::I686), + 388 - usize::from(target == CensusTarget::I686), 1_431 - 23 * usize::from(target == CensusTarget::I686), 389 + 24 * usize::from(target == CensusTarget::I686) ) diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 5f0c3e00..78dabade 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -540,8 +540,9 @@ pub(super) enum ProjectedComMethodKind { /// overload dispatch — anything that can present as more than one shape (or /// that overlaps another candidate's shape, e.g. `Buffer` inputs being /// `typeof 'object'` just like a projected COM object) is deliberately left -/// unclassified (`None` from `dispatch_shape`) so overload grouping fails -/// closed instead of guessing. +/// unclassified (`None` from `dispatch_shape`). The projection can emit explicit +/// slot-named entries for validated ordinary methods, but never guesses an +/// implicit dispatcher. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum DispatchShape { Boolean, @@ -619,7 +620,7 @@ pub(super) struct ComSinkPlan { /// overload-dispatch purposes. Returns `None` for any type whose JS /// representation is ambiguous or overlaps another candidate shape (pointer /// types accept `Buffer`/`bigint`/`number` in ways that collide with other -/// categories), so overload grouping can fail closed rather than guess. +/// categories), so overload grouping cannot invent an implicit dispatcher. pub(super) fn dispatch_shape(typ: &ComType) -> Option { match typ { ComType::Primitive(ComPrimitive::Bool) | ComType::Win32Bool => Some(DispatchShape::Boolean), diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index aaccc8d9..bf202882 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -3184,7 +3184,7 @@ fn input_arity(method: &ProjectedComMethod) -> usize { } fn group_overloads( - methods: Vec, + mut methods: Vec, interface_name: &str, ) -> Result, String> { let mut order = Vec::new(); @@ -3200,12 +3200,17 @@ fn group_overloads( .push(index); } + let mut public_names = methods + .iter() + .map(|method| method.camel_name.clone()) + .collect::>(); let mut overloads = vec![None; methods.len()]; for name in &order { let indices = &groups[name]; if indices.len() < 2 { continue; } + let mut explicit = false; for &index in indices { let method = &methods[index]; if method.kind != ProjectedComMethodKind::Normal { @@ -3217,12 +3222,7 @@ fn group_overloads( )); } if method.string_buffer.is_some() || !method.typed_buffers.is_empty() { - return Err(format!( - "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ - because at least one uses a projected buffer, which is not a \ - safely dispatchable JS shape", - indices.len() - )); + explicit = true; } } @@ -3235,13 +3235,20 @@ fn group_overloads( .push(index); } + let mut planned = Vec::new(); for (arity, bucket) in arity_buckets { + if explicit { + break; + } if bucket.len() == 1 { - overloads[bucket[0]] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), - dispatch: OverloadDispatch::Arity, - }); + planned.push(( + bucket[0], + OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), + dispatch: OverloadDispatch::Arity, + }, + )); continue; } let key_param_index = (0..arity).find(|&key_index| { @@ -3258,26 +3265,49 @@ fn group_overloads( }) }); let Some(key_param_index) = key_param_index else { - return Err(format!( - "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ - position has mutually distinguishable JS shapes (arity/type/category); \ - overload dispatch cannot be safely generated", - bucket.len() - )); + explicit = true; + break; }; for &index in &bucket { let (_, param) = input_params_of(&methods[index])[key_param_index]; let shape = dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); - overloads[index] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[index].vtable_index), - dispatch: OverloadDispatch::ArityAndShape { - key_param_index, - shape, + planned.push(( + index, + OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[index].vtable_index), + dispatch: OverloadDispatch::ArityAndShape { + key_param_index, + shape, + }, }, + )); + } + } + if explicit { + for &index in indices { + let method = &mut methods[index]; + let alias = format!("{name}AtSlot{}", method.vtable_index); + if !public_names.insert(alias.clone()) { + return Err(format!( + "{interface_name}.{name}: explicit overload name `{alias}` collides with another projected member" + )); + } + method.camel_name = alias; + let note = format!( + "Explicit overload of `{name}` at native vtable slot {}. The ambiguous unsuffixed method is not exposed.", + method.vtable_index + ); + method.doc = Some(match method.doc.take() { + Some(doc) => format!("{doc}\n\n{note}"), + None => note, }); } + } else { + for (index, plan) in planned { + overloads[index] = Some(plan); + } } } @@ -3304,6 +3334,226 @@ fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComPara mod tests { use super::*; + fn overload_method(name: &str, slot: usize, types: Vec) -> ProjectedComMethod { + ProjectedComMethod { + name: name.into(), + camel_name: camel_case(name), + vtable_index: slot, + params: types + .into_iter() + .enumerate() + .map(|(index, typ)| ProjectedComParam { + name: format!("value{index}"), + typ, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }) + .collect(), + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + } + } + + #[test] + fn ambiguous_overloads_get_stable_explicit_slot_names() { + let methods = vec![ + overload_method("Pick", 3, Vec::new()), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 8, vec![ComType::Primitive(ComPrimitive::F64)]), + ]; + let projected = group_overloads(methods.clone(), "IExample").unwrap(); + assert_eq!( + projected + .iter() + .map(|method| method.camel_name.as_str()) + .collect::>(), + ["pickAtSlot3", "pickAtSlot4", "pickAtSlot8"] + ); + assert!(projected.iter().all(|method| method.overload.is_none())); + assert!(projected.iter().all(|method| method.name == "Pick")); + let mut reordered = methods; + reordered.reverse(); + let reordered = group_overloads(reordered, "IExample").unwrap(); + for method in reordered { + assert_eq!( + method.camel_name, + format!("pickAtSlot{}", method.vtable_index) + ); + assert!( + method + .doc + .unwrap() + .contains("ambiguous unsuffixed method is not exposed") + ); + } + } + + #[test] + fn distinguishable_overload_dispatch_is_unchanged() { + for methods in [ + vec![ + overload_method("Pick", 3, Vec::new()), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + ], + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::Bool)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + ], + ] { + let projected = group_overloads(methods, "IExample").unwrap(); + assert!(projected.iter().all(|method| method.camel_name == "pick")); + assert!(projected.iter().all(|method| method.overload.is_some())); + } + } + + #[test] + fn explicit_overload_names_never_overwrite_a_declared_member() { + let error = group_overloads( + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::U32)]), + overload_method("PickAtSlot3", 5, Vec::new()), + ], + "IExample", + ) + .unwrap_err(); + assert!( + error.contains("pickAtSlot3") && error.contains("collides"), + "{error}" + ); + } + + #[test] + fn explicit_overloads_do_not_relax_synthesized_method_contracts() { + let ordinary = overload_method("Pick", 3, Vec::new()); + let mut synthesized = overload_method("Pick", 4, Vec::new()); + synthesized.kind = ProjectedComMethodKind::FixedCapacityBytes { + guid_param_index: 0, + }; + let error = group_overloads(vec![ordinary, synthesized], "IExample").unwrap_err(); + assert!(error.contains("synthesized/dynamic-IID"), "{error}"); + } + + #[test] + fn explicit_overload_javascript_routes_without_runtime_guessing() { + let methods = group_overloads( + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::F64)]), + ], + "IOverloads", + ) + .unwrap(); + let interface = ProjectedComInterface { + name: "IOverloads".into(), + namespace: "Tests".into(), + iid: "73552640-8c23-43df-93f7-24d7842430f1".into(), + base_iids: Vec::new(), + is_iunknown_rooted: true, + methods, + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + sink: None, + evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, + }; + let output = + crate::codegen::com::javascript::render::render_com_interface(&interface).unwrap(); + let source = serde_json::to_string(&output.js).unwrap(); + let script = format!( + r#" +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const calls = []; +const registrations = []; +class Sig {{ addIn() {{ return this; }} }} +const runtime = {{ + DynComMethodSig: Sig, + WinGuid: {{ parse: value => value }}, + __registerComProjection() {{}}, + DynCom: {{ + i32Type() {{}}, f64Type() {{}}, bindComObject() {{}}, + i32: value => ['i32', value], f64: value => ['f64', value], + registerIUnknownInterface() {{ + return {{ + addMethodAt(slot, name) {{ registrations.push([slot, name]); return this; }}, + method(slot) {{ return {{ invoke(_object, args) {{ calls.push([slot, args]); }} }}; }} + }}; + }} + }} +}}; +const exported = {{}}; +vm.runInNewContext({source}, {{ require: () => runtime, exports: exported }}); +const raw = {{ cast() {{ return this; }}, release() {{}} }}; +const value = exported.IOverloads._fromNative(raw); +assert.equal(value.pick, undefined); +value.pickAtSlot3(7); +value.pickAtSlot4(1.5); +assert.deepEqual(registrations, [[3, 'Pick'], [4, 'Pick']]); +assert.deepEqual(JSON.parse(JSON.stringify(calls)), [[3, [['i32', 7]]], [4, [['f64', 1.5]]]]); +"# + ); + let result = std::process::Command::new("node") + .arg("-e") + .arg(script) + .output() + .expect("Node is required for explicit overload routing coverage"); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + } + + #[test] + fn buffer_overloads_use_explicit_entries_without_losing_their_plan() { + let mut buffer = overload_method( + "Put", + 4, + vec![ComType::TypedBuffer { + element: Box::new(ComType::Primitive(ComPrimitive::U8)), + }], + ); + buffer.params[0].direction = ComParamDirection::InputBuffer; + buffer.params.push(ProjectedComParam { + name: "count".into(), + typ: ComType::Primitive(ComPrimitive::U32), + direction: ComParamDirection::In, + surface_input: false, + surface_result: false, + nullable: false, + }); + let plan = TypedBufferPlan { + buffer_param_index: 0, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::Input { + count_param_index: 1, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Bytes, + }, + }; + buffer.typed_buffers.push(plan.clone()); + let result = group_overloads( + vec![ + overload_method("Put", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + buffer, + ], + "IExample", + ) + .unwrap(); + assert_eq!(result[0].camel_name, "putAtSlot3"); + assert_eq!(result[1].camel_name, "putAtSlot4"); + assert_eq!(result[1].typed_buffers, [plan]); + } + #[test] fn endpoint_activation_preserves_the_semantic_call_plan() { let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { diff --git a/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs new file mode 100644 index 00000000..a0a4c40b --- /dev/null +++ b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt_codegen::{codegen::com, com_metadata}; +use std::{fs, path::Path, process::Command}; + +#[test] +fn ambiguous_native_overloads_expose_exact_callable_slots() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + for (namespace, interface_name, method_name, camel_name) in [ + ( + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device1", + "CreateDeviceContext", + "createDeviceContext", + ), + ( + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device7", + "CreateDeviceContext", + "createDeviceContext", + ), + ( + "Windows.Win32.Graphics.DirectWrite", + "IDWriteFontCollection1", + "GetFontFamily", + "getFontFamily", + ), + ( + "Windows.Win32.AI.MachineLearning.WinML", + "IMLOperatorKernelContext", + "GetOutputTensor", + "getOutputTensor", + ), + ( + "Windows.Win32.Graphics.DirectComposition", + "IDCompositionDynamicTexture", + "SetTexture", + "setTexture", + ), + ] { + let interface = + com_metadata::parse_com_interface(&winmd, namespace, interface_name).unwrap(); + let output = com::generate_com_interface_files(&interface, &winmd) + .unwrap_or_else(|error| panic!("{interface_name}: {error}")); + let slots = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter(|method| method.metadata_name == method_name) + .map(|method| method.vtable_index) + .collect::>(); + assert!( + slots.len() >= 2, + "{interface_name} must exercise inherited overloads" + ); + for slot in slots { + let name = format!("{camel_name}AtSlot{slot}"); + assert!( + output.dts.contains(&format!("{name}(")), + "{interface_name}: missing {name}" + ); + assert!( + output.js.contains(&format!("{name}(")), + "{interface_name}: missing {name}" + ); + assert!( + output.js.contains(&format!(".method({slot}).invoke")), + "{interface_name}: lost slot {slot}" + ); + assert!( + output + .js + .contains(&format!(".addMethodAt({slot}, '{method_name}'")), + "{interface_name}: registration changed" + ); + } + + assert!(!output.dts.contains(&format!(" {camel_name}("))); + assert!(!output.js.contains(&format!(" {camel_name}("))); + } +} + +#[test] +fn generated_explicit_overload_declarations_typecheck() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let package = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .parent() + .unwrap() + .join(r"bindings\js"); + let tsc = package.join(r"node_modules\typescript\bin\tsc"); + if !tsc.is_file() { + eprintln!("Skipping: repository TypeScript compiler not available"); + return; + } + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let output = std::env::temp_dir().join(format!( + "dynwinrt-com-overloads-{}-{nonce}", + std::process::id() + )); + let generation = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd", &winmd, "--class-name", + "Windows.Win32.Graphics.Direct2D.ID2D1Device1,Windows.Win32.Graphics.DirectWrite.IDWriteFontCollection1", + "--output"]) + .arg(&output) + .output() + .expect("run overload codegen"); + assert!( + generation.status.success(), + "{}", + String::from_utf8_lossy(&generation.stderr) + ); + let device = com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device1", + ) + .unwrap(); + let slots = device + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter(|method| method.metadata_name == "CreateDeviceContext") + .map(|method| method.vtable_index) + .collect::>(); + let calls = slots + .iter() + .map(|slot| format!("device.createDeviceContextAtSlot{slot}(0);")) + .collect::>() + .join("\n"); + fs::write( + output.join("usage.ts"), + format!( + "import type {{ ID2D1Device1 }} from './com/index.js';\n\ + declare const device: ID2D1Device1;\n{calls}\n\ + // @ts-expect-error ambiguous unsuffixed overload is intentionally absent\n\ + device.createDeviceContext(0);\n\ + // @ts-expect-error the native enum input remains typed\n\ + device.createDeviceContextAtSlot{}('invalid');\n", + slots[0] + ), + ) + .unwrap(); + let config = serde_json::json!({ + "compilerOptions": { + "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", + "strict": true, "noEmit": true, "skipLibCheck": false, + "baseUrl": output, + "typeRoots": [package.join(r"node_modules\@types")], + "paths": { + "@microsoft/dynwinrt/com": [package.join(r"dist\com.d.ts")], + "@microsoft/dynwinrt/com/unsafe": [package.join(r"dist\com-unsafe.d.ts")] + } + }, + "include": ["usage.ts", "com/**/*.d.ts"] + }); + fs::write( + output.join("tsconfig.json"), + serde_json::to_vec(&config).unwrap(), + ) + .unwrap(); + let checked = Command::new("node") + .arg(tsc) + .args(["--noEmit", "-p"]) + .arg(output.join("tsconfig.json")) + .output() + .expect("run overload tsc"); + fs::remove_dir_all(&output).unwrap(); + assert!( + checked.status.success(), + "{}\n{}", + String::from_utf8_lossy(&checked.stdout), + String::from_utf8_lossy(&checked.stderr) + ); +}