From 4416bdb8a026b7371e6cf5992b1c6e2883e137e0 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Mon, 7 Sep 2026 23:25:08 +0800 Subject: [PATCH 1/4] Add safe COM projection and endpoint activation Provide non-consuming COM projectAs with registered safe descriptors, restricted in-process IMMDevice activation with native NULL parameters, and exact GetId ownership. Preserve the WinRT root and dynamic architecture; require complete COM regeneration with manifest v3. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 35 +-- README.md | 13 +- bindings/js/Cargo.toml | 2 +- .../generated-unsafe-companion.e2e.ts | 145 +++++++++++- bindings/js/__test__/index.spec.ts | 9 +- bindings/js/runtime/com-projection.cjs | 50 +++++ bindings/js/scripts/generate-entrypoints.mjs | 25 +++ bindings/js/src/com.rs | 5 + .../js/src/generated_unsafe_test_hooks.rs | 211 +++++++++++++++++- .../classic-com-contract-evidence-registry.md | 77 +++++-- docs/architecture/classic-com-support.md | 57 ++++- docs/guides/windows/classic-com-usage.md | 106 +++++++-- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 74 +++--- .../classic-com-capability-summary.json | 121 ++++++---- .../classic-com-interface-support.csv | 2 +- tests/e2e/runners/com/persist-file.mjs | 24 +- .../contracts/classic-com/manifest.json | 2 +- .../classic-com/ownership-outputs.json | 49 ++++ .../src/codegen/com/capability.rs | 65 ++++-- .../src/codegen/com/generated_unsafe.rs | 8 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 8 + .../src/codegen/com/javascript/render.rs | 63 +++++- .../src/codegen/com/model/metadata.rs | 21 +- .../src/codegen/com/model/method.rs | 8 + .../src/codegen/com/project/mod.rs | 90 ++++++++ tools/dynwinrt-codegen/src/com_metadata.rs | 84 ++++++- .../dynwinrt-codegen/src/contract_registry.rs | 5 +- tools/dynwinrt-codegen/src/main.rs | 7 +- .../IDataTransferManagerInterop.js | 3 +- .../snapshots/ishelllinkw/IShellLinkW.js | 3 +- .../snapshots/itaskbarlist3/ITaskbarList.js | 3 +- .../snapshots/itaskbarlist3/ITaskbarList2.js | 3 +- .../snapshots/itaskbarlist3/ITaskbarList3.js | 3 +- .../snapshots/itaskbarlist3/ITaskbarList4.js | 3 +- .../snapshots/itaskbarlist3/TaskbarList.js | 3 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 40 ++++ 36 files changed, 1236 insertions(+), 191 deletions(-) create mode 100644 bindings/js/runtime/com-projection.cjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f62b7588..c22e5ef0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -90,7 +90,7 @@ jobs: if ($result.eligible_interfaces -ne 7929) { throw "Classic COM census denominator changed: $($result.eligible_interfaces)" } - if ($result.complete_interfaces -lt 5696) { + if ($result.complete_interfaces -lt 5697) { throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" } if ($result.coverage_percent -lt 70.0) { @@ -107,21 +107,21 @@ 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 5696) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5697) { 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 5696 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2233 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5697 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2232 ) { throw "Classic COM compact interface support index changed" } $expected = @{ - x64 = @(412, 1432, 389) - i686 = @(411, 1409, 413) - arm64 = @(412, 1432, 389) + x64 = @(412, 1431, 389) + i686 = @(411, 1408, 413) + arm64 = @(412, 1431, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -134,22 +134,24 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5696 -or + $result.safeEvidence.safeComplete -ne 5697 -or $result.safeEvidence.standardDerived -ne 5333 -or - $result.safeEvidence.exactRegistryDependent -ne 363 -or - $result.safeEvidence.metadataFactOccurrences -ne 5982 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26129 -or - $result.safeEvidence.registeredExactEntries -ne 504 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 504 -or - $result.safeEvidence.safeConsumedExactEntries -ne 413 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 669 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 416 + $result.safeEvidence.exactRegistryDependent -ne 364 -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 ) { throw "Classic COM safe evidence dependency census changed" } $statuses = @($result.safeEvidence.exactEntryStatus.psobject.Properties.Value) if ( @($statuses | Where-Object { -not $_.registered -or -not $_.metadataMatched }).Count -ne 0 -or + @($statuses | Where-Object { $_.familyId -eq 'com.ownership.v1' }).Count -ne 169 -or + @($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 @@ -351,5 +353,6 @@ jobs: bindings/js/dist/winrt.d.ts bindings/js/dist/com.js bindings/js/dist/com.d.ts + bindings/js/dist/com-projection.js bindings/js/dist/com-unsafe.js bindings/js/dist/com-unsafe.d.ts diff --git a/README.md b/README.md index c6e7f72e..ffe26c57 100644 --- a/README.md +++ b/README.md @@ -142,8 +142,8 @@ is not a general Automation or native Win32 projection, and it does not project flat DLL exports. The current CI baseline against -`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,696 of 7,929 -eligible interfaces (71.84%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,697 of 7,929 +eligible interfaces (71.85%)** 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 @@ -169,6 +169,15 @@ COM-only generated packages also require the explicit `com/` entrypoint; the generated package root and `@microsoft/dynwinrt` runtime root remain WinRT-only. +`projectAs(value, InterfaceClass)` safely queries a borrowed managed native +value or generated wrapper into a separately owned wrapper of a registered +generated safe COM interface; it accepts neither raw pointers nor unsafe +target classes. `IMMDevice` now supports typed `activate(InterfaceClass)` for +the documented in-process, null-parameter audio endpoint subset and +`getId(): string`. The usage guide shows endpoint discovery through +`activate(IAudioClient)` and `DynComAudioFormat.pcm()` format negotiation, +without a per-interface native adapter. + - [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/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index a9be7a15..bc5c0e16 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager"] +test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_UI_Shell_PropertiesSystem"] [dependencies] napi = { version = "3", features = ["napi7"] } diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 593c807b..9cd7cefd 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -33,7 +33,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr '--winmd', winmd!, '--class-name', - 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext,Windows.Win32.Media.DeviceManager.IMDSPDeviceControl,Windows.Win32.Media.DeviceManager.IWMDMDeviceControl', + 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext,Windows.Win32.Media.DeviceManager.IMDSPDeviceControl,Windows.Win32.Media.DeviceManager.IWMDMDeviceControl,Windows.Win32.Media.Audio.IMMDevice', '--output', output, ] @@ -95,6 +95,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr const wbemClassObjectBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'system', 'wmi', 'IWbemClassObjectUnsafe') const thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') const audioBase = join(output, 'com', 'windows', 'win32', 'media', 'audio', 'IAudioClient') + const mmDeviceBase = join(output, 'com', 'windows', 'win32', 'media', 'audio', 'IMMDevice') const mdspDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IMDSPDeviceControl') const wmdmDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IWMDMDeviceControl') const evaluationBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'ai', 'machine-learning', 'win-ml', 'IWinMLEvaluationContextUnsafe') @@ -106,7 +107,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr "const assert = require('node:assert/strict')", "const { pathToFileURL } = require('node:url')", `const runtime = require(${JSON.stringify(join(packageRoot, 'dist', 'index.js'))})`, - "const { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } = require('@microsoft/dynwinrt/com')", + "const { DynComAudioFormat, DynComFormatEtc, DynComStgMedium, projectAs } = require('@microsoft/dynwinrt/com')", "const { DynComRaw, DynComRawMemory, DynComRawOwnedComPointer, DynComRawPointer, WinGuid } = require('@microsoft/dynwinrt/com/unsafe/raw')", `const strategyRuntime = require(${JSON.stringify(join(output, 'com', 'unsafe', 'runtime.js'))})`, 'const { UnsafePointee, UnsafePointerOutput, UnsafeHandleOutput, UnsafeInterfaceReplacement, UnsafeCountedBuffer, UnsafeRawCall, __prepareStrategy, __prepareWritableStorage, __prepareExactWritableSpan, __strategyArgument, __assertRawContract, __validateStrategySpans, __activateStrategies, __markDispatchEntered, __finishStrategy, __failStrategy, __releaseExtracted, __attachUnsafeOutputs, __testRunOwnedFinalizer, __testCreateOwnedPointer } = strategyRuntime', @@ -118,6 +119,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr `const wbemClassObject = require(${JSON.stringify(`${wbemClassObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, + `const mmDevice = require(${JSON.stringify(`${mmDeviceBase}.js`)})`, `const mdspDeviceControl = require(${JSON.stringify(`${mdspDeviceControlBase}.js`)})`, `const wmdmDeviceControl = require(${JSON.stringify(`${wmdmDeviceControlBase}.js`)})`, `const evaluation = require(${JSON.stringify(`${evaluationBase}.js`)})`, @@ -144,6 +146,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ` const esmWbemClassObject = await import(pathToFileURL(${JSON.stringify(`${wbemClassObjectBase}.js`)}).href)`, ` const esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, + ` const esmMmDevice = await import(pathToFileURL(${JSON.stringify(`${mmDeviceBase}.js`)}).href)`, ` const esmMdspDeviceControl = await import(pathToFileURL(${JSON.stringify(`${mdspDeviceControlBase}.js`)}).href)`, ` const esmWmdmDeviceControl = await import(pathToFileURL(${JSON.stringify(`${wmdmDeviceControlBase}.js`)}).href)`, ` const esmEvaluation = await import(pathToFileURL(${JSON.stringify(`${evaluationBase}.js`)}).href)`, @@ -157,14 +160,18 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr " assert.equal(typeof wbemClassObject.IWbemClassObjectUnsafe, 'function')", " assert.equal(typeof thumbnail.IThumbnailProvider, 'function')", " assert.equal(typeof audio.IAudioClient, 'function')", + " assert.equal(typeof mmDevice.IMMDevice, 'function')", + " assert.equal(typeof projectAs, 'function')", " assert.equal(typeof mdspDeviceControl.IMDSPDeviceControl, 'function')", " assert.equal(typeof wmdmDeviceControl.IWMDMDeviceControl, 'function')", " assert.equal(typeof evaluation.IWinMLEvaluationContextUnsafe, 'function')", ' assert.equal(esmAudio.IAudioClient, audio.IAudioClient)', + ' assert.equal(esmMmDevice.IMMDevice, mmDevice.IMMDevice)', ' assert.equal(esmMdspDeviceControl.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', ' assert.equal(esmWmdmDeviceControl.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(esmEvaluation.IWinMLEvaluationContextUnsafe, evaluation.IWinMLEvaluationContextUnsafe)', ' assert.equal(safeBarrel.IAudioClient, audio.IAudioClient)', + ' assert.equal(safeBarrel.IMMDevice, mmDevice.IMMDevice)', ' assert.equal(safeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', ' assert.equal(safeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', @@ -183,6 +190,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ' assert.equal(esmWbemClassObject.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmSafeBarrel.IMMDevice, mmDevice.IMMDevice)', ' assert.equal(esmSafeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', ' assert.equal(esmSafeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(esmSafeBarrel.IOleCache, oleCache.IOleCache)', @@ -456,6 +464,114 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ' safeAudioWrapper?.release()', ' safeAudioFake?.release()', ' }', + ' const projectionAudioStats = runtime.generatedAudioClientStats', + ' class UnregisteredAudio extends audio.IAudioClient {}', + ' let nativeAudio = runtime.createGeneratedAudioClientFake()', + ' let projectedAudio', + ' let projectedCopy', + ' let rejectedProjection', + ' try {', + ' assert.equal(projectionAudioStats().currentRefCount, 1)', + ' projectedAudio = projectAs(nativeAudio, audio.IAudioClient)', + ' assert.ok(projectedAudio instanceof audio.IAudioClient)', + ' assert.equal(projectionAudioStats().currentRefCount, 2)', + ' projectedCopy = projectAs(projectedAudio, audio.IAudioClient)', + ' assert.ok(projectedCopy instanceof audio.IAudioClient)', + ' assert.notEqual(projectedCopy, projectedAudio)', + ' assert.equal(projectionAudioStats().currentRefCount, 3)', + ' assert.equal(projectedAudio.getMixFormat().channels, 2)', + ' assert.equal(projectedCopy.getMixFormat().channels, 2)', + ' for (const source of [0, 0n, Buffer.alloc(DynComRaw.pointerSize()), DynComRawPointer.null()]) {', + ' assert.throws(() => { rejectedProjection = projectAs(source, audio.IAudioClient) }, /managed COM value|generated wrapper/i)', + ' assert.equal(projectionAudioStats().currentRefCount, 3)', + ' }', + ' for (const target of [UnregisteredAudio, evaluation.IWinMLEvaluationContextUnsafe]) {', + ' assert.throws(() => { rejectedProjection = projectAs(nativeAudio, target) }, /registered generated safe COM/i)', + ' assert.equal(projectionAudioStats().currentRefCount, 3)', + ' }', + ' assert.throws(() => { rejectedProjection = projectAs(nativeAudio, mmDevice.IMMDevice) }, /interface|0x80004002/i)', + ' assert.equal(projectionAudioStats().currentRefCount, 3)', + ' projectedAudio.release()', + ' projectedAudio = undefined', + ' assert.equal(projectionAudioStats().currentRefCount, 2)', + ' assert.equal(projectedCopy.getMixFormat().channels, 2)', + ' projectedCopy.release()', + ' projectedCopy = undefined', + ' assert.equal(projectionAudioStats().currentRefCount, 1)', + ' projectedAudio = projectAs(nativeAudio, audio.IAudioClient)', + ' assert.equal(projectedAudio.getMixFormat().channels, 2)', + ' projectedAudio.release()', + ' projectedAudio = undefined', + ' assert.equal(projectionAudioStats().currentRefCount, 1)', + ' nativeAudio.release()', + ' nativeAudio = undefined', + ' const released = projectionAudioStats()', + ' assert.equal(released.currentRefCount, 0)', + ' assert.equal(released.getMixFormatCalls, 4)', + ' assert.equal(released.releaseCalls, released.addRefCalls + 1)', + ' } finally {', + ' rejectedProjection?.release?.()', + ' projectedCopy?.release()', + ' projectedAudio?.release()', + ' nativeAudio?.release()', + ' }', + ' const createDevice = runtime.createGeneratedMmDeviceFake', + ' const deviceStats = runtime.generatedMmDeviceStats', + ' const setActivateMode = runtime.setGeneratedMmDeviceActivateMode', + " assert.equal(typeof createDevice, 'function')", + " assert.equal(typeof deviceStats, 'function')", + " assert.equal(typeof setActivateMode, 'function')", + ' let deviceFake = createDevice()', + ' let deviceWrapper', + ' let activatedAudio', + ' try {', + ' assert.equal(deviceStats().currentRefCount, 1)', + ' assert.throws(() => deviceFake.cast(audio.IAudioClient.IID), /interface|0x80004002/i)', + ' assert.equal(deviceStats().currentRefCount, 1)', + ' deviceWrapper = projectAs(deviceFake, mmDevice.IMMDevice)', + ' assert.equal(deviceStats().currentRefCount, 2)', + " assert.equal(deviceWrapper.getId(), 'dynwinrt-fake-audio-endpoint')", + ' assert.throws(() => { activatedAudio = deviceWrapper.activate(dataObject.IDataObject) }, /outside.*activation contract/i)', + ' for (const target of [UnregisteredAudio, evaluation.IWinMLEvaluationContextUnsafe]) {', + ' assert.throws(() => { activatedAudio = deviceWrapper.activate(target) }, /registered generated safe COM/i)', + ' }', + ' assert.equal(deviceStats().activateCalls, 0)', + ' activatedAudio = deviceWrapper.activate(audio.IAudioClient)', + ' assert.ok(activatedAudio instanceof audio.IAudioClient)', + ' assert.equal(projectionAudioStats().currentRefCount, 1)', + ' assert.equal(deviceStats().currentRefCount, 2)', + ' assert.equal(activatedAudio.getMixFormat().samplesPerSecond, 48000)', + ' activatedAudio.release()', + ' activatedAudio = undefined', + ' const releasedTarget = projectionAudioStats()', + ' assert.equal(releasedTarget.currentRefCount, 0)', + ' assert.equal(releasedTarget.releaseCalls, releasedTarget.addRefCalls + 1)', + ' setActivateMode(-1)', + ' assert.throws(() => { activatedAudio = deviceWrapper.activate(audio.IAudioClient) }, /native call failed|HRESULT|0x80004005/i)', + ' assert.deepEqual(projectionAudioStats(), releasedTarget)', + ' setActivateMode(1)', + ' assert.throws(() => { activatedAudio = deviceWrapper.activate(audio.IAudioClient) }, /null|pointer|owned|interface/i)', + ' assert.deepEqual(projectionAudioStats(), releasedTarget)', + ' setActivateMode(2)', + ' assert.throws(() => { activatedAudio = deviceWrapper.activate(audio.IAudioClient) }, /interface|0x80004002/i)', + ' const rejectedTarget = projectionAudioStats()', + ' assert.equal(rejectedTarget.currentRefCount, 0)', + ' assert.equal(rejectedTarget.releaseCalls, rejectedTarget.addRefCalls + 1)', + ' const completed = deviceStats()', + ' assert.deepEqual([completed.activateCalls, completed.validatedActivateCalls, completed.returnedAudioObjects, completed.getIdCalls, completed.currentRefCount], [4, 4, 2, 1, 2])', + ' deviceWrapper.release()', + ' deviceWrapper = undefined', + ' assert.equal(deviceStats().currentRefCount, 1)', + ' deviceFake.release()', + ' deviceFake = undefined', + ' const releasedDevice = deviceStats()', + ' assert.equal(releasedDevice.currentRefCount, 0)', + ' assert.equal(releasedDevice.releaseCalls, releasedDevice.addRefCalls + 1)', + ' } finally {', + ' activatedAudio?.release()', + ' deviceWrapper?.release()', + ' deviceFake?.release()', + ' }', ' const createAudio = runtime.createGeneratedEvaluationContextFake', ' const audioStats = runtime.generatedEvaluationContextStats', ' const setServiceMode = runtime.setGeneratedEvaluationContextOutputMode', @@ -899,6 +1015,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr "import { IOleCache2 } from './com/windows/win32/system/ole/IOleCache2.js'", "import { IThumbnailProvider } from './com/windows/win32/ui/shell/IThumbnailProvider.js'", "import { IAudioClient } from './com/windows/win32/media/audio/IAudioClient.js'", + "import { IMMDevice } from './com/windows/win32/media/audio/IMMDevice.js'", "import { IMDSPDeviceControl } from './com/windows/win32/media/device-manager/IMDSPDeviceControl.js'", "import { IWMDMDeviceControl } from './com/windows/win32/media/device-manager/IWMDMDeviceControl.js'", "import { IWinMLEvaluationContextUnsafe } from './com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js'", @@ -906,8 +1023,10 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr "import { UnsafePointee, UnsafePointerOutput } from './com/unsafe/runtime.js'", "import type { UnsafeOwnedPointer } from './com/unsafe/runtime.js'", "import type { DynComRawMemory, DynWinRtValue } from '@microsoft/dynwinrt/com/unsafe/raw'", - "import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } from '@microsoft/dynwinrt/com'", + "import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium, projectAs } from '@microsoft/dynwinrt/com'", 'declare const native: DynWinRtValue', + 'declare const unknownSource: unknown', + 'declare const device: IMMDevice', 'declare const storage: DynComRawMemory', 'declare const thumbnails: IThumbnailProvider', 'declare const dataObjects: IDataObject', @@ -934,6 +1053,26 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr '// @ts-expect-error SetData ownership transfer is intentionally hidden', 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', 'const audio = IAudioClient._fromNative(native)', + 'const endpointId: string = device.getId()', + 'void endpointId', + 'const activated = device.activate(IAudioClient)', + 'const activatedAudio: IAudioClient = activated', + 'activated.getMixFormat().toBuffer()', + '// @ts-expect-error Activate infers IAudioClient rather than any or IMMDevice', + 'activated.getId()', + 'const fromNativeAudio: IAudioClient = projectAs(native, IAudioClient)', + 'const fromWrapperAudio: IAudioClient = projectAs(fromNativeAudio, IAudioClient)', + 'const fromUnknownAudio: IAudioClient = projectAs(unknownSource, IAudioClient)', + 'fromUnknownAudio.release()', + 'fromWrapperAudio.release()', + 'fromNativeAudio.release()', + 'activatedAudio.release()', + '// @ts-expect-error Activate fixes CLSCTX instead of accepting a caller context', + 'device.activate(IAudioClient, 1)', + '// @ts-expect-error Activate fixes activation parameters to native NULL', + 'device.activate(IAudioClient, 1, null)', + '// @ts-expect-error Activate owns output storage and adoption instead of taking a strategy', + 'device.activate(IAudioClient, 1, null, UnsafePointerOutput.comOwned(IAudioClient.IID))', 'audio.isFormatSupported(0, DynComAudioFormat.pcm(2, 48_000, 16))', '// @ts-expect-error IsFormatSupported still requires an explicit audio format', 'audio.isFormatSupported(0, null)', diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 848ef47f..4bac0315 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -190,19 +190,22 @@ test('package facades exactly partition native exports', (t) => { t.deepEqual(moduleKeys(winrtCjsRuntime), expectedWinrt) t.deepEqual( moduleKeys(comCjsRuntime), - nativeKeys.filter((name) => safeComNames.has(name)), + [...nativeKeys.filter((name) => safeComNames.has(name)), 'projectAs'].sort(), ) t.deepEqual( moduleKeys(unsafeComRuntime), - nativeKeys.filter((name) => unsafeComNames.has(name)), + [...nativeKeys.filter((name) => unsafeComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid'].sort(), ) t.deepEqual( moduleKeys(rawComRuntime), - nativeKeys.filter((name) => rawComNames.has(name)), + [...nativeKeys.filter((name) => rawComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid'].sort(), ) t.is(winrtCjsRuntime.WinGuid, comCjsRuntime.WinGuid) t.is(comCjsRuntime.initializeCom, unsafeComRuntime.initializeCom) + t.is(comCjsRuntime.projectAs, unsafeComRuntime.projectAs) + t.false(Object.prototype.hasOwnProperty.call(winrtCjsRuntime, 'projectAs')) + t.false(Object.prototype.hasOwnProperty.call(comCjsRuntime, '__registerComProjection')) t.false(Object.prototype.hasOwnProperty.call(comCjsRuntime, 'DynWinRTValue')) t.false(Object.prototype.hasOwnProperty.call(comCjsRuntime, 'WinGUID')) t.false(Object.prototype.hasOwnProperty.call(unsafeComRuntime, 'DynWinRTValue')) diff --git a/bindings/js/runtime/com-projection.cjs b/bindings/js/runtime/com-projection.cjs new file mode 100644 index 00000000..189f8942 --- /dev/null +++ b/bindings/js/runtime/com-projection.cjs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const native = require('./index.js') +const projections = new WeakMap() + +function registerProjection(type, iid) { + if (typeof type !== 'function' || !(iid instanceof native.WinGuid)) { + throw new TypeError('A COM projection requires a generated class and an exact IID') + } + if (projections.has(type)) { + throw new TypeError('The COM projection is already registered') + } + projections.set(type, Object.freeze({ iid, prototype: type.prototype })) +} + +function descriptor(type) { + const projection = projections.get(type) + if (!projection) { + throw new TypeError('Expected a registered generated safe COM interface type; regenerate the bindings') + } + return projection +} + +function projectionIid(type) { + return descriptor(type).iid +} + +function projectAs(value, type) { + const projection = descriptor(type) + const source = value instanceof native.DynWinRtValue + ? value + : value !== null && typeof value === 'object' ? value._obj : undefined + if (!(source instanceof native.DynWinRtValue)) { + throw new TypeError('projectAs requires a managed COM value or generated wrapper') + } + // cast validates managed COM ownership and thread affinity before querying the IID. + const cast = source.cast(projection.iid) + try { + native.DynCom.bindComObject(cast) + return Object.assign(Object.create(projection.prototype), { _obj: cast }) + } catch (error) { + cast.release() + throw error + } +} + +module.exports = { projectAs, registerProjection, projectionIid } diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index b73dedeb..816a6154 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -217,6 +217,7 @@ writeFacade( comTypeExports, comExports, opaqueComDeclarations, + true, ) writeFacade( 'com-unsafe', @@ -224,6 +225,7 @@ writeFacade( comUnsafeTypeExports, comUnsafeExports, opaqueComDeclarations, + true, ) writeFacade( 'com-unsafe-raw', @@ -231,6 +233,12 @@ writeFacade( comUnsafeRawTypeExports, comUnsafeRawExports, [...opaqueComDeclarations, ...rawComDeclarations], + true, +) + +writeFileSync( + join(distDir, 'com-projection.js'), + readFileSync(join(packageDir, 'runtime', 'com-projection.cjs'), 'utf8'), ) function writeFacade( @@ -239,6 +247,7 @@ function writeFacade( typeExports = exports, requiredExports = [], extraTypeDeclarations = [], + comProjection = false, ) { const missing = [...requiredExports].filter((value) => !exports.includes(value)) if (missing.length > 0) { @@ -250,12 +259,28 @@ function writeFacade( "'use strict'", "const native = require('./index.js')", ...exports.map((value) => `module.exports.${value} = native.${value}`), + ...(comProjection ? [ + "const projection = require('./com-projection.js')", + 'module.exports.projectAs = projection.projectAs', + ...(name === 'com' ? [] : [ + 'module.exports.__registerComProjection = projection.registerProjection', + 'module.exports.__comProjectionIid = projection.projectionIid', + ]), + ] : []), '', ].join('\n') const dts = [ '// Generated by scripts/generate-entrypoints.mjs - do not edit', `export { ${typeExports.join(', ')} } from './index.js'`, ...extraTypeDeclarations, + ...(comProjection ? [ + "export interface ComInterfaceType { readonly IID: import('./index.js').WinGuid; _fromNative(value: unknown): T }", + 'export declare function projectAs(value: unknown, type: ComInterfaceType): T', + ...(name === 'com' ? [] : [ + "export declare function __registerComProjection(type: ComInterfaceType, iid: import('./index.js').WinGuid): void", + "export declare function __comProjectionIid(type: ComInterfaceType): import('./index.js').WinGuid", + ]), + ] : []), '', ].join('\n') diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 10951ef9..debc22c3 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -1215,6 +1215,11 @@ fn adopt_com_pointer( iid: Option<&WinGUID>, ) -> napi::Result { let ptr = take_native_output_pointer(value, PointerProvenance::ComOutput, "COM interface")?; + if ptr.is_null() { + return Err(napi::Error::from_reason( + "Owned COM interface output was null", + )); + } let adopted = unsafe { dynwinrt::com::adopt_com_pointer(ptr) }; match iid { Some(iid) => adopted diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 339a9ebc..e59b4ff2 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -9,15 +9,15 @@ use std::{ use napi::bindgen_prelude::BigInt; use napi_derive::napi; use windows::Win32::Media::{ - Audio::WAVEFORMATEX, + Audio::{IMMDevice, IMMDevice_Vtbl, DEVICE_STATE, WAVEFORMATEX}, DeviceManager::{ IMDSPDeviceControl, IMDSPDeviceControl_Vtbl, IWMDMDeviceControl, IWMDMDeviceControl_Vtbl, }, }; use windows::{ - core::{IUnknown, IUnknown_Vtbl, Interface, BOOL, GUID, HRESULT, PCWSTR}, + core::{IUnknown, IUnknown_Vtbl, Interface, BOOL, GUID, HRESULT, PCWSTR, PWSTR}, Win32::System::{ - Com::SAFEARRAY, + Com::{StructuredStorage::PROPVARIANT, CLSCTX, SAFEARRAY, STGM}, Ole::{IOleCache, IOleCache2, IOleCache2_Vtbl, IOleCache_Vtbl, UPDFCACHE_FLAGS}, Variant::VARIANT, Wmi::{ @@ -74,6 +74,14 @@ static AUDIO_GET_SERVICE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_ACTIVATE_CALLS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_VALIDATED_ACTIVATE_CALLS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_ACTIVATE_MODE: AtomicI32 = AtomicI32::new(0); +static MM_DEVICE_RETURNED_AUDIO_OBJECTS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_GET_ID_CALLS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); +static MM_DEVICE_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); static EVALUATION_BIND_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); static EVALUATION_GET_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); static EVALUATION_OUTPUT_MODE: AtomicI32 = AtomicI32::new(0); @@ -1830,6 +1838,7 @@ struct GeneratedAudioClientVtbl { struct GeneratedAudioClientFake { vtable: *const GeneratedAudioClientVtbl, references: AtomicU32, + supports_audio_client: bool, } unsafe extern "system" fn audio_query_interface( @@ -1842,7 +1851,8 @@ unsafe extern "system" fn audio_query_interface( } unsafe { *result = std::ptr::null_mut(); - if *iid != IUnknown::IID && *iid != IID_IAUDIO_CLIENT { + let object = &*this.cast::(); + if *iid != IUnknown::IID && (*iid != IID_IAUDIO_CLIENT || !object.supports_audio_client) { return E_NOINTERFACE; } *result = this; @@ -2098,8 +2108,7 @@ pub struct GeneratedAudioClientStats { pub current_ref_count: u32, } -#[napi] -pub fn create_generated_audio_client_fake() -> napi::Result { +fn create_generated_audio_client_unknown(supports_audio_client: bool) -> IUnknown { AUDIO_INITIALIZE_CALLS.store(0, Ordering::SeqCst); AUDIO_IS_FORMAT_SUPPORTED_CALLS.store(0, Ordering::SeqCst); AUDIO_GET_MIX_FORMAT_CALLS.store(0, Ordering::SeqCst); @@ -2114,9 +2123,14 @@ pub fn create_generated_audio_client_fake() -> napi::Result { let object = Box::new(GeneratedAudioClientFake { vtable: &AUDIO_VTABLE, references: AtomicU32::new(1), + supports_audio_client, }); - let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; - crate::com::apartment_bound_com_object(unknown) + unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) } +} + +#[napi] +pub fn create_generated_audio_client_fake() -> napi::Result { + crate::com::apartment_bound_com_object(create_generated_audio_client_unknown(true)) } #[napi] @@ -2156,6 +2170,187 @@ pub fn generated_audio_client_stats() -> GeneratedAudioClientStats { } } +#[repr(C)] +struct GeneratedMmDeviceFake { + vtable: *const IMMDevice_Vtbl, + references: AtomicU32, +} + +unsafe extern "system" fn mm_device_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + unsafe { + *result = std::ptr::null_mut(); + if *iid != IUnknown::IID && *iid != IMMDevice::IID { + return E_NOINTERFACE; + } + *result = this; + mm_device_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn mm_device_add_ref(this: *mut c_void) -> u32 { + MM_DEVICE_ADD_REF_CALLS.fetch_add(1, Ordering::SeqCst); + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + MM_DEVICE_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn mm_device_release(this: *mut c_void) -> u32 { + MM_DEVICE_RELEASE_CALLS.fetch_add(1, Ordering::SeqCst); + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + MM_DEVICE_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn mm_device_activate( + _this: *mut c_void, + iid: *const GUID, + context: CLSCTX, + activation_params: *const PROPVARIANT, + result: *mut *mut c_void, +) -> HRESULT { + MM_DEVICE_ACTIVATE_CALLS.fetch_add(1, Ordering::SeqCst); + if iid.is_null() || result.is_null() || context.0 != 1 || !activation_params.is_null() { + return HRESULT(0x80070057u32 as i32); + } + if unsafe { iid.read_unaligned() } != IID_IAUDIO_CLIENT { + return E_NOINTERFACE; + } + if unsafe { !(*result).is_null() } { + return E_POINTER; + } + MM_DEVICE_VALIDATED_ACTIVATE_CALLS.fetch_add(1, Ordering::SeqCst); + let mode = MM_DEVICE_ACTIVATE_MODE.load(Ordering::SeqCst); + match mode { + -1 => return HRESULT(0x80004005u32 as i32), + 1 => return HRESULT(0), + _ => {} + } + // The negative-QI mode still returns a real object with a complete audio vtable. + let audio = create_generated_audio_client_unknown(mode != 2); + MM_DEVICE_RETURNED_AUDIO_OBJECTS.fetch_add(1, Ordering::SeqCst); + unsafe { + result.write(audio.into_raw()); + } + HRESULT(0) +} + +unsafe extern "system" fn mm_device_open_property_store( + _this: *mut c_void, + _access: STGM, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn mm_device_get_id(_this: *mut c_void, result: *mut PWSTR) -> HRESULT { + MM_DEVICE_GET_ID_CALLS.fetch_add(1, Ordering::SeqCst); + if result.is_null() || unsafe { !(*result).0.is_null() } { + return E_POINTER; + } + let id = "dynwinrt-fake-audio-endpoint" + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>(); + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(id.len() * std::mem::size_of::()) } + .cast::(); + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping(id.as_ptr(), allocation, id.len()); + result.write(PWSTR(allocation)); + } + HRESULT(0) +} + +unsafe extern "system" fn mm_device_get_state( + _this: *mut c_void, + _state: *mut DEVICE_STATE, +) -> HRESULT { + E_NOTIMPL +} + +static MM_DEVICE_VTABLE: IMMDevice_Vtbl = IMMDevice_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: mm_device_query_interface, + AddRef: mm_device_add_ref, + Release: mm_device_release, + }, + Activate: mm_device_activate, + OpenPropertyStore: mm_device_open_property_store, + GetId: mm_device_get_id, + GetState: mm_device_get_state, +}; + +#[napi(object)] +pub struct GeneratedMmDeviceStats { + pub activate_calls: u32, + pub validated_activate_calls: u32, + pub returned_audio_objects: u32, + pub get_id_calls: u32, + pub add_ref_calls: u32, + pub release_calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_mm_device_fake() -> napi::Result { + MM_DEVICE_ACTIVATE_CALLS.store(0, Ordering::SeqCst); + MM_DEVICE_VALIDATED_ACTIVATE_CALLS.store(0, Ordering::SeqCst); + MM_DEVICE_ACTIVATE_MODE.store(0, Ordering::SeqCst); + MM_DEVICE_RETURNED_AUDIO_OBJECTS.store(0, Ordering::SeqCst); + MM_DEVICE_GET_ID_CALLS.store(0, Ordering::SeqCst); + MM_DEVICE_ADD_REF_CALLS.store(0, Ordering::SeqCst); + MM_DEVICE_RELEASE_CALLS.store(0, Ordering::SeqCst); + MM_DEVICE_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedMmDeviceFake { + vtable: &MM_DEVICE_VTABLE, + references: AtomicU32::new(1), + }); + let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; + crate::com::apartment_bound_com_object(unknown) +} + +#[napi] +pub fn set_generated_mm_device_activate_mode(mode: i32) -> napi::Result<()> { + if !(-1..=2).contains(&mode) { + return Err(napi::Error::from_reason( + "generated IMMDevice Activate mode must be -1, 0, 1, or 2", + )); + } + MM_DEVICE_ACTIVATE_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + +#[napi] +pub fn generated_mm_device_stats() -> GeneratedMmDeviceStats { + GeneratedMmDeviceStats { + activate_calls: MM_DEVICE_ACTIVATE_CALLS.load(Ordering::SeqCst), + validated_activate_calls: MM_DEVICE_VALIDATED_ACTIVATE_CALLS.load(Ordering::SeqCst), + returned_audio_objects: MM_DEVICE_RETURNED_AUDIO_OBJECTS.load(Ordering::SeqCst), + get_id_calls: MM_DEVICE_GET_ID_CALLS.load(Ordering::SeqCst), + add_ref_calls: MM_DEVICE_ADD_REF_CALLS.load(Ordering::SeqCst), + release_calls: MM_DEVICE_RELEASE_CALLS.load(Ordering::SeqCst), + current_ref_count: MM_DEVICE_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + #[repr(C)] struct GeneratedEvaluationContextVtbl { base__: IUnknown_Vtbl, diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 65f11eb8..ec439e61 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -341,12 +341,14 @@ Current code registries are migrated without changing behavior: - `IDataObject::GetCanonicalFormatEtc` output validity and ignored `tymed`; - `IAudioClient` shared/exclusive format negotiation and CoTaskMem format outputs; +- `IMMDevice::Activate` typed null-parameter activation and + `IMMDevice::GetId` CoTaskMem string ownership; - `IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` nullable audio-format inputs selecting the device default; and - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,696/7,929 safe census, generated unsafe manifests, and all live tests agree +5,697/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -383,13 +385,38 @@ method fingerprint, selector, exact flags, mutually exclusive outputs, ownership, citations, and validated metadata hash. The old Rust constants were removed. -`ownership-outputs.json` contains 147 parameter-specific CoTaskMem contracts +`ownership-outputs.json` contains 148 parameter-specific CoTaskMem contracts and one exact `HBITMAP`/`DeleteObject` contract. Attachment occurs only after the complete raw method is built and only when its namespace, interface IID, method, absolute slot, full parameter selector, and pre-contract fingerprint all match. These entries promote complete interfaces without applying allocator or handle ownership inference to any unrelated pointer output. +PR1 completes `IMMDevice` (IID +`d666063f-1587-4e43-81f1-b948e807363f`) with two exact `com.ownership.v1` +entries: + +- `Activate`, absolute slot 3, source fingerprint + `5025E3C25B95D89F92271233B0761D56DF1041F985D6C1D0BAFE0FC4DEDD26E3`: + the code-defined contract validates the full native signature and owned + dynamic-IID output. The safe projection fixes `CLSCTX_INPROC_SERVER` to `1` + and `pActivationParams` to native NULL. +- `GetId`, absolute slot 5, parameter `0: ppstrId`, source fingerprint + `38AF4F595BEEADA67D0D49EB1B04F2CC354C8A06813B286CCAE4B5EF44BFCD99`: + the JSON ownership entry copies the returned UTF-16 string and pairs the + allocation with `CoTaskMemFree`, yielding `getId(): string`. + +The activation target must be a registered generated safe class with the IID +of `IAudioClient`, `IAudioEndpointVolume`, `IAudioMeterInformation`, +`IAudioSessionManager`, or `IAudioSessionManager2`. Other/custom targets, +asynchronous activation, and loopback or other parameterized activation are +outside this subset. The selectors cite Microsoft's +[`IMMDevice::Activate`](https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate) +and +[`IMMDevice::GetId`](https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid) +contracts. Metadata drift fails closed; neither entry introduces a +per-interface native adapter or changes the WinRT root API. + Three exact parameter-direction entries, two reserved-null input entries, one flag-selected caller-buffer entry, one `IStorage::Stat` entry, and seven WMI conditional-output entries reuse closed semantic models. Together with the @@ -408,18 +435,18 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | | `standard_derived` | 5,333 | -| `exact_registry_dependent` | 363 | -| **Total** | **5,696** | +| `exact_registry_dependent` | 364 | +| **Total** | **5,697** | -The registry contains **504 declared entries**, all 504 match the pinned -metadata, and 413 distinct entries are consumed by safe plans. Safe plans have -669 entry/interface dependencies and 416 family/interface dependencies. -Per-interface dependency-set totals also include 5,982 metadata-attribute -dependencies and 26,129 COM-standard-rule dependencies. +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. +Per-interface dependency-set totals also include 5,983 metadata-attribute +dependencies and 26,134 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 180 | +| `ownership` | 182 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 10 | @@ -442,7 +469,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` | 167 | 116 | 122 | +| `com.ownership.v1` | 169 | 118 | 123 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | | `com.nullable-input.v1` | 2 | 2 | 2 | @@ -462,12 +489,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,578 | +| `com.hresult.failure.v1` | 5,579 | | `com.interface.input-borrow.v1` | 1,890 | -| `com.interface.typed-output-plus-one.v1` | 3,457 | -| `com.iunknown.identity-refcount.v1` | 5,696 | -| `com.query-interface.output-plus-one.v1` | 5,696 | -| `com.standard-cleanup.matching-allocator.v1` | 1,436 | +| `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 | 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 @@ -497,9 +524,19 @@ stable typed provenance ID/kind and participates in the dependency census only when consumed. Moving those declarations into grouped JSON files, and adding controlled contract-family ablation, remains later registry migration work. -The strict contract data schema and manifest are version 2. The capability -summary is version 3, and generated unsafe support manifests are version 11. -Seven WMI conditional-output entries and 148 output-ownership entries are -JSON-backed; the other 340 registered entries remain code-defined. All code and +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. +Seven WMI conditional-output entries and 149 output-ownership entries are +JSON-backed; the other 350 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 +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 +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. diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 5c8dc3cb..664b304a 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,696 complete safe -> interface projections out of 7,929 eligible interfaces (71.84%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,697 complete safe +> interface projections out of 7,929 eligible interfaces (71.85%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -491,11 +491,13 @@ not be described as solving every problem in the map above. | Authoritative count-param detection | Relationships come solely from `NativeArrayInfo(CountParamIndex)` or an exact cited override registry. Documented overrides cover `ISequentialStream::Read`/`Write`, `IDiscRecorder::GetRecorderGUID`, `IOpcSignatureCustomObject::GetXml`, and the fixed-capacity/actual-byte `IMFAttributes::GetBlob` contract. The previous substring/adjacency heuristic remains removed. | | Private-data ownership guard | Actual metadata contains seven declaring `GetPrivateData(REFGUID, UINT*, void*)` interfaces. Their documentation permits returning an AddRef'd interface set by `SetPrivateDataInterface`; Direct3D 10 also documents destructive NULL behavior, and DXGI does not mark the data pointer optional. They remain exact, cited fail-closed hazards rather than being projected as leaking `Buffer` methods. | | Atomic multi-interface writes | When a single `generate` invocation projects several COM interfaces, every interface is projected into memory first; files (and the `com/` index/package barrel) are only written once the whole batch has projected successfully. A later interface's projection failure no longer leaves an earlier interface's files partially written to disk. | -| Coclass projection | GUID-bearing Classic COM coclasses such as `TaskbarList`, `FileOperation`, and `FileOpenDialog` generate as independently constructible JS classes (`new TaskbarList()`). Interface wrappers remain non-publicly constructible and expose an IID descriptor plus `_fromNative` for runtime QueryInterface views. | +| Coclass projection | GUID-bearing Classic COM coclasses such as `TaskbarList`, `FileOperation`, and `FileOpenDialog` generate as independently constructible JS classes (`new TaskbarList()`). Interface wrappers remain non-publicly constructible and register private descriptors for safe `projectAs` QueryInterface views. | | Interface views | Generated coclasses expose `as(InterfaceClass)`, `tryAs(InterfaceClass)`, and `supports(InterfaceClass)`. These execute real QueryInterface calls; `tryAs` returns `null` only for `E_NOINTERFACE`, while other errors remain visible. | +| Safe projection entry | `projectAs(value, InterfaceClass)` on `/com` borrows a managed native value or generated wrapper and returns a separately owned QueryInterface wrapper. The target must be a registered generated safe COM interface class; arbitrary raw pointers and unsafe target classes are rejected. Generated modules register descriptors through private `/com/unsafe` helpers, not application-supplied ABI declarations. | +| Audio endpoint entry | Exact `IMMDevice::Activate` evidence projects `activate(InterfaceClass)` with an inferred target wrapper, fixed `CLSCTX_INPROC_SERVER = 1`, and native NULL activation parameters. Exact `GetId` ownership projects `getId(): string` and frees the CoTaskMem allocation. These are semantic plans over shared runtime primitives, not per-interface native adapters. | | Conservative primary interface | Windows.Win32 coclass TypeDefs do not carry `InterfaceImpl`/`DefaultAttribute` rows. The generator associates only exact metadata naming candidates, constructs the real interface inheritance graph, and selects a primary only when there is one unique most-derived leaf. Multiple unrelated leaves fail closed rather than choosing by numeric suffix. | | CommonJS and ESM | COM implementation files use the same CommonJS format as generated WinRT files. `com/index.js` is the CommonJS barrel, while `com/index.mjs` is the ESM facade. Package exports provide explicit `require` and `import` conditions for the COM barrel and deep imports. | -| Explicit raw opt-in | Manual ABI declarations and caller-supplied COM pointers are isolated under `@microsoft/dynwinrt/com/unsafe`. The default COM facade exports only initialization and managed value/layout wrappers—not `DynCom`, signatures, interfaces, native types, or `DynComUnsafe`; generated safe bindings continue to fail closed. | +| Explicit raw opt-in | Manual ABI declarations and caller-supplied COM pointers are isolated under `@microsoft/dynwinrt/com/unsafe`. The default COM facade exports initialization, `projectAs`, and managed value/layout wrappers—not `DynCom`, signatures, interfaces, native types, or `DynComUnsafe`; generated safe bindings continue to fail closed. | ### Generated package layout @@ -545,9 +547,22 @@ taskbar.release(); 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. Generated layout/schema version -changes require deleting and regenerating the complete bindings directory; -in-place cross-version migration is intentionally unsupported. +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 +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 +`IMMDevice.activate(InterfaceClass)` uses that private descriptor registry. +Unregistered/unsafe targets and numeric, Buffer, or native `RawPtr` sources are +rejected. Other generated `.as(...)` paths remain unchanged. + +Existing bindings must be deleted and completely regenerated with the +matching updated runtime and codegen. Regenerate the complete bindings +directory, including all selected roots; in-place cross-version migration, +editing the manifest version, and mixing old/new generated classes are not +supported. This does not change WinRT semantics or the runtime root API. winappCli project aliases use `#winapp/bindings/com` for the COM barrel and canonical deep imports such as @@ -680,8 +695,23 @@ and `@microsoft/dynwinrt/com`. | HSTRING inputs and scalar outputs | Supported | JavaScript strings are converted to owning HSTRING values; returned HSTRING values are decoded and released automatically. | | Referenced interface types | Supported when IID metadata is loaded | Missing external definitions fail closed and direct callers to pass the defining winmd with `--ref`. | | Dynamic-IID `void**` outputs | Supported for explicit required REFIID shapes | The method must return ordinary HRESULT and contain exactly one required const `GUID*` named `iid`/`riid` plus one required mutable `void**`/Object** output with +1 COM ownership. Their explicit parameter indices may be non-adjacent/non-terminal. Optional, duplicate, array, FreeWith, InOut, by-value/mutable/deeper GUID, and wrong-depth output shapes fail closed. | +| Typed endpoint activation | Exact-contract support | `IMMDevice.activate(InterfaceClass)` accepts only registered generated safe classes for the documented null-parameter IID subset below. The caller cannot supply CLSCTX flags or an activation-parameter pointer. | | Explicit apartment initialization | Supported | `initializeCom()` never silently chooses an apartment for the caller. | +`IMMDevice` is safe-complete with exact IID +`d666063f-1587-4e43-81f1-b948e807363f`, slot-3 `Activate`, and full-method +fingerprint evidence. Its activation targets are limited to `IAudioClient`, +`IAudioEndpointVolume`, `IAudioMeterInformation`, `IAudioSessionManager`, and +`IAudioSessionManager2`; other/custom targets, asynchronous activation, and +loopback or other parameterized activation remain outside this safe subset. +The separate slot-5 `GetId` JSON ownership entry supplies its CoTaskMem string +contract. Both entries belong to `com.ownership.v1`; see the +[contract evidence registry](classic-com-contract-evidence-registry.md). +The [audio endpoint example](../guides/windows/classic-com-usage.md#55-audio-endpoint-activation) +uses `projectAs` and `activate(IAudioClient)` without exposing raw pointers. +Existing safe `IAudioClient`, `IAudioClient2`, and `IAudioClient3` format +contracts remain unchanged. + `IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` have exact nullable audio-input contracts. Their declarations accept `DynComAudioFormat | null`, the COM signature retains input nullability, and @@ -1255,13 +1285,15 @@ that census to 5,681. The dedicated target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM model promotes 10 more interfaces after 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 the current -literal census to **5,696 / 7,929 = 71.837558%**. The result remains above the +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 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,696, or coverage +if the denominator changes, complete generation drops below 5,697, or coverage falls below 70%. ## Public-code frequency snapshot @@ -1392,7 +1424,7 @@ hardware, and whether it adds a distinct ABI shape. | `IClassFactory` | Low-level COM activation | Complete generation and public `CoGetClassObject` acquisition are live-tested with paired server locking and owned `CreateInstance` output. | | `IBindCtx` / `IRunningObjectTable` | Monikers and object binding | Both generate. `BIND_OPTS` carries an exact size initializer, and explicit bytes with a zero or incorrect `cbStruct` fail before native dispatch. | | `ICreateErrorInfo` / `IErrorInfo` | COM rich error information | Complete generation and acquisition are live-tested for GUID, wide strings, owned BSTR output, thread-local storage, and one-shot consumption. | -| `IMMDeviceEnumerator` | Audio endpoint discovery | Generates today, but live behavior depends on available audio endpoints. | +| `IMMDeviceEnumerator` / `IMMDevice` | Audio endpoint discovery and activation | Complete safe generation includes typed null-parameter activation for the documented IID subset and CoTaskMem-owned device IDs projected as strings. `projectAs` wraps borrowed managed device values with an independent QI owner; live behavior depends on audio services and endpoints. | | `IWbemServices` | WMI queries and method invocation | Complete generation uses exact sync/semisync output selection; selected outputs are owned COM references and `pCtx` is native null in the closed safe overloads. | | `IAudioClient` / `IAudioClient2` / `IAudioClient3` | Low-level audio streaming | Complete safe generation uses `DynComAudioFormat`; exact fingerprinted contracts model shared/exclusive closest-format selection and CoTaskMem-owned format outputs. Generated fake-vtable coverage is hardware-independent. | | `IDispatch` | Automation and scripting | Complete inherited real-metadata generation passes. `GetIDsOfNames` projects as `string[] -> number[]`; `Invoke` accepts `DynComDispatchParams` and explicit result/excepInfo/argErr request options, returning dedicated owning wrappers. Derived Automation interfaces remain independently validated. | @@ -1519,7 +1551,8 @@ COM interface references and Win32 handles must not be treated the same. | Value source | Ownership in dynwinrt | Cleanup | |---|---|---| | `CoCreateInstance` result | Owned `+1` COM reference | Automatic `Release` on `DynWinRtValue` drop/GC, or explicit `release()`. | -| `QueryInterface` / `cast()` result | Owned `+1` COM reference | Automatic `Release`, independently of the source wrapper. | +| `QueryInterface` / `cast()` / `projectAs()` result | Owned `+1` COM reference | Automatic `Release`, independently of the borrowed source value or wrapper. | +| Generated `IMMDevice.activate()` result | Owned `+1` COM reference for the registered allowed target | Automatic `Release`; the intermediate activation owner is released after projection, including on projection failure. | | Typed interface out parameter | Owned `+1` COM reference from the callee | Automatic `Release`. | | Interface passed as `[in]` | Borrowed for the duration of the call | No ownership transfer unless the callee explicitly retains it with `AddRef`. | | Numeric raw pointer | Borrowed | Never automatically released or freed. | diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 6f7895d9..540aaefd 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -24,7 +24,7 @@ the roadmap. The raw unsafe architecture is documented in | Entry point | Purpose | | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | | `@microsoft/dynwinrt` | Public WinRT API; does not include Classic COM | -| `@microsoft/dynwinrt/com` | COM initialization, GUIDs, and managed Automation/POD values | +| `@microsoft/dynwinrt/com` | COM initialization, GUIDs, safe `projectAs` interface views, and managed Automation/POD values | | `@microsoft/dynwinrt/com/unsafe` | Manual interface registration, explicit ABI declarations, vtable invocation, and native pointer handling | | `@microsoft/dynwinrt/com/unsafe/raw` | Owned/bounded external memory, raw aggregate layouts, pointer slots, and raw outbound ABI calls | @@ -135,9 +135,16 @@ 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`. Regenerating the same root removes -files it no longer owns, while files shared with or generated by other roots -remain intact. +`generated/com/.dynwinrt-com-manifest.json`, currently version 3. 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 +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. ### 4.3 Automatic generated unsafe companions @@ -219,17 +226,11 @@ try { } ``` -Audio format negotiation is now on the safe surface: - -```js -import { DynComAudioFormat } from "@microsoft/dynwinrt/com"; -import { IAudioClient } from "./generated/com/windows/win32/media/audio/IAudioClient.js"; - -const audio = IAudioClient._fromNative(existingAudioClientValue); -const pcm = DynComAudioFormat.pcm(2, 48_000, 16); -const [status, closest] = audio.isFormatSupported(0, pcm); -const mixFormat = audio.getMixFormat(); -``` +Audio format negotiation is now on the safe surface. The +[audio endpoint example](#55-audio-endpoint-activation) uses `projectAs`, +`IMMDevice.activate(IAudioClient)`, and `DynComAudioFormat.pcm()` without an +unsafe pointer strategy. An already acquired managed audio value can also be +wrapped with `projectAs(existingAudioClientValue, IAudioClient)`. For `IMDSPDeviceControl` and `IWMDMDeviceControl`, `record(null)` selects the device's default recording format after the required capability and seek @@ -314,9 +315,10 @@ surface. The mode selects exactly one optional native output, `pCtx` is native null, and the selected result is an owned managed COM value: ```js +import { projectAs } from "@microsoft/dynwinrt/com"; import { IWbemServices } from "./generated/com/index.js"; -const services = IWbemServices._fromNative(existingServiceValue); +const services = projectAs(existingServiceValue, IWbemServices); const workingNamespace = services.openNamespace("child", { mode: "sync" }); try { // The semisynchronous form uses { mode: "semisync" }. @@ -441,11 +443,12 @@ metadata. Interface classes cannot be instantiated directly with `new`. ### 5.2 QueryInterface views ```js +import { projectAs } from "@microsoft/dynwinrt/com"; import { TaskbarList, ITaskbarList3 } from "./generated/com/index.js"; const taskbar = new TaskbarList(); try { - const v3 = taskbar.as(ITaskbarList3); + const v3 = projectAs(taskbar, ITaskbarList3); try { // v3 owns an independent +1 reference returned by the actual QueryInterface call. } finally { @@ -461,10 +464,27 @@ try { } ``` +`projectAs(value, InterfaceClass)` is exported by the runtime +`@microsoft/dynwinrt/com` entrypoint. It accepts a managed native COM value or a +generated wrapper, borrows the source, and performs a real QueryInterface, +returning an independently owned wrapper with its TypeScript type inferred +from `InterfaceClass`. Release the result independently; the source is not +consumed, even when projecting to the same interface. + +The private registry rejects unregistered or generated `*Unsafe` target +classes. Numeric addresses, Buffers, native `RawPtr` values, and raw unsafe +pointer owners are not accepted as sources. Generated safe modules register +their descriptors through private `/com/unsafe` helpers; generated +`IMMDevice.activate(InterfaceClass)` obtains its target descriptor from that +same registry. Applications use `projectAs`, not descriptor registration or +arbitrary IID/signature pairs. Existing generated `.as(...)` paths are +unchanged. + Differences: | Method | Behavior | | -------------------------- | -------------------------------------------------------------------------------- | +| `projectAs(value, InterfaceClass)` | Queries a borrowed managed value or wrapper into a separately owned safe wrapper; throws if unsupported | | `as(InterfaceClass)` | Throws if the IID is not supported | | `tryAs(InterfaceClass)` | Returns `null` for `E_NOINTERFACE` | | `supports(InterfaceClass)` | Queries and immediately releases the temporary reference, then returns a Boolean | @@ -582,6 +602,57 @@ contract, codegen omits `implement()` for the entire interface. Cross-apartment dispatch, connection-point helpers, COM aggregation, custom marshaling, and COM server registration remain unsupported. +### 5.5 Audio endpoint activation + +Generate the endpoint coclass, device interface, and requested target: + +```powershell +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --namespace Windows.Win32.Media.Audio ` + --class-name "MMDeviceEnumerator,IMMDevice,IAudioClient" ` + --output .\generated +``` + +```js +import { DynComAudioFormat, initializeCom, projectAs } from "@microsoft/dynwinrt/com"; +import { IAudioClient, IMMDevice, MMDeviceEnumerator } from "./generated/com/index.js"; + +initializeCom(1); +const enumerator = new MMDeviceEnumerator(); +let endpointValue, device, audio; +try { + endpointValue = enumerator.getDefaultAudioEndpoint(0, 0); // eRender, eConsole + device = projectAs(endpointValue, IMMDevice); + audio = device.activate(IAudioClient); // inferred IAudioClient, owned independently + const pcm = DynComAudioFormat.pcm(2, 48_000, 16); + const [status, closest] = audio.isFormatSupported(0, pcm); // shared mode + console.log(device.getId(), status, closest); +} finally { + audio?.release(); + device?.release(); + endpointValue?.release(); + enumerator.release(); +} +``` + +This requires running Windows audio services and a default render endpoint. +`IMMDevice` is safe-complete, but its generated `activate(InterfaceClass)` +deliberately fixes `CLSCTX_INPROC_SERVER = 1` and passes native NULL for +activation parameters. The target must be a registered generated safe class +for exactly one of `IAudioClient`, `IAudioEndpointVolume`, +`IAudioMeterInformation`, `IAudioSessionManager`, or `IAudioSessionManager2`. +Generate and import whichever target the application needs. Other/custom +targets, async activation, and loopback or other parameterized activation +remain outside this safe subset. + +`getId()` returns a natural string and frees the native CoTaskMem allocation. +The existing safe `IAudioClient`/`IAudioClient2`/`IAudioClient3` format methods, +including `getMixFormat()`, and the exact nullable device-control `record()` +contracts remain unchanged. This path uses validated generated contracts and +shared runtime primitives, not per-interface native adapters; the WinRT root +entrypoint is unchanged. + ## 6. JavaScript projections of common native types | Native semantics | JavaScript/TypeScript | @@ -625,6 +696,7 @@ The following sources return a managed `+1` reference: - `CoGetMalloc`; - `CreateErrorInfo` and a successful `GetErrorInfo`; - `QueryInterface`; +- `projectAs(value, InterfaceClass)` and generated `IMMDevice.activate(InterfaceClass)`; - a validated interface out parameter; - the QI result returned by `DynComUnsafe.borrowComPointer()`. diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index d91b109e..03abd89e 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -32,15 +32,15 @@ B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D | Result | Interfaces | Percentage | | ---------------------------------------------------- | ---------: | ---------: | | Externally addressable Classic COM interfaces | 7,929 | 100% | -| Complete safe generation | 5,696 | 71.84% | -| Rejected because at least one contract is incomplete | 2,233 | 28.16% | +| Complete safe generation | 5,697 | 71.85% | +| Rejected because at least one contract is incomplete | 2,232 | 28.15% | 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,696 figure is semantic codegen coverage, not a claim that every interface +The 5,697 figure is semantic codegen coverage, not a claim that every interface has a dedicated live Windows test or can be activated on every machine. Reproduce the census with: @@ -105,7 +105,22 @@ modeled contracts. | Counted buffers | Typed input buffers, caller-owned output buffers, capacity/actual-length patterns, exact bounded sizing, and known CoTaskMem outputs. | | Automation values | Defined subsets of VARIANT, SAFEARRAY, PROPVARIANT, DISPPARAMS, and EXCEPINFO. | | Return conventions | Ordinary and semantic HRESULT, direct scalar, direct void, and exact registered direct-pointer contracts such as `IMalloc`. | -| COM object semantics | Coclass activation, inherited interfaces, QI views, automatic release, and idempotent explicit release. | +| COM object semantics | Coclass activation, inherited interfaces, `projectAs` QI views of managed values or wrappers, automatic release, and idempotent explicit release. | + +The safe `/com` entrypoint exports `projectAs(value, InterfaceClass)`. It +borrows a managed native value or generated wrapper and returns an independent +QueryInterface owner of a registered generated safe COM interface. Raw +pointers and unsafe target classes are rejected. + +`IMMDevice` is now safe-complete: `activate(InterfaceClass)` infers the returned +wrapper, fixes `CLSCTX_INPROC_SERVER = 1`, and passes native NULL activation +parameters. The supported targets are `IAudioClient`, `IAudioEndpointVolume`, +`IAudioMeterInformation`, `IAudioSessionManager`, and `IAudioSessionManager2`. +Other/custom targets, async activation, and loopback or other parameterized +activation remain outside this subset. `getId()` returns a string with exact +CoTaskMem cleanup. This uses generated semantic plans and shared runtime +primitives, not per-interface native adapters; the WinRT root is unchanged. +See the [audio endpoint example](../guides/windows/classic-com-usage.md#55-audio-endpoint-activation). ## JavaScript interface implementation @@ -343,11 +358,11 @@ versus 16 (`WBEM_FLAG_RETURN_IMMEDIATELY`), adopt the requested non-null `+1`, a release dirty failure output. Generic interface InOut parameters remain manual replacement contracts. -**1,428 of 1,432** x64 manual-contract interfaces now have at least one portable -executable generated high-level method. **1,427** have an executable manual +**1,427 of 1,431** x64 manual-contract interfaces now 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. Across the portable generated surface there are **6,048 executable +target. Across the portable generated surface there are **6,046 executable manual methods**, **0 remaining portable manual-classified methods omitted**, and **1,161 runtime-blocked methods** still omitted. @@ -355,19 +370,19 @@ 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,696 safe-complete interfaces exactly once: +classifies all 5,697 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | | `standard_derived` | 5,333 | -| `exact_registry_dependent` | 363 | +| `exact_registry_dependent` | 364 | -The registry declares 504 selector-specific entries; all 504 match pinned -metadata, 413 distinct entries are safe-consumed, and safe plans contain 669 -entry/interface plus 416 family/interface dependencies. They also consume -5,982 metadata-attribute and 26,129 universal COM-rule dependency sets. +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 +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 180, parameter-direction 45, bounded-two-call 16, +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, per-family rollups, and per-interface entry IDs are retained in the summary @@ -386,6 +401,11 @@ variable-format outputs. The two device-control `Record` methods have separate exact nullable-input contracts: `null` selects the device default format without allocating a placeholder WAVEFORMATEX. Other audio-format inputs remain required. +`IMMDevice::Activate` adds an exact IID/slot-3/full-fingerprint activation +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. The storage-medium contracts also pin `IOleCache::SetData` (including inherited `IOleCache2` calls) to caller-retained ownership and describe the distinct @@ -397,7 +417,7 @@ semantics are modeled. The strict embedded registry lives in `tools/dynwinrt-codegen/contracts/classic-com/`. JSON is the sole source for -seven selector-derived IWbemServices conditional-output contracts and 148 +seven selector-derived IWbemServices conditional-output contracts and 149 documented output-ownership contracts. Each entry includes its selector, pre-contract fingerprint, evidence, and validated metadata hash. @@ -410,18 +430,18 @@ 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,696 of 7,929 interfaces. The separate outbound raw census -classifies the 2,233 safe-incomplete interfaces as: +the safe census is 5,697 of 7,929 interfaces. The separate outbound raw census +classifies the 2,232 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,432 | 389 | -| i686 | 411 | 1,409 | 413 | -| ARM64 | 412 | 1,432 | 389 | +| x64 | 412 | 1,431 | 389 | +| i686 | 411 | 1,408 | 413 | +| ARM64 | 412 | 1,431 | 389 | -Including safe-complete interfaces, x64 and ARM64 have 6,108 -metadata-complete, 1,432 manual, and 389 blocked interfaces. i686 has 6,107 -metadata-complete, 1,409 manual, and 413 blocked interfaces. +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. Pointer-shaped types are analyzed recursively. A missing pointee layout for an external input pointer is manual-contract; the same missing layout for a @@ -431,14 +451,14 @@ writable/readable `T*` caller-storage contract is runtime-blocked. Thus layout is complete. Cleanup availability is no longer represented by ambiguous booleans. Per -target, 2,237 interfaces require no cleanup, 4,533 use a Phase 1 standard -cleanup, none use a known external cleanup, and 1,159 have unknown cleanup. +target, 2,237 interfaces require no cleanup, 4,534 use a Phase 1 standard +cleanup, none use a known external cleanup, and 1,158 have unknown cleanup. Every missing output ownership/allocator contract has `cleanup_unknown`. 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,696 safe-complete interfaces, cleanup is derived from the validated +For all 5,697 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, @@ -525,7 +545,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,696 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,697 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 622aa102..ddc73724 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": 5696, - "safe_incomplete": 2233, + "safe_complete": 5697, + "safe_incomplete": 2232, "safeEvidence": { - "safeComplete": 5696, + "safeComplete": 5697, "standardDerived": 5333, - "exactRegistryDependent": 363, - "metadataFactOccurrences": 5982, - "comStandardFactOccurrences": 26129, - "registeredExactEntries": 504, - "metadataMatchedExactEntries": 504, - "safeConsumedExactEntries": 413, - "exactEntryInterfaceDependencies": 669, - "exactFamilyInterfaceDependencies": 416, + "exactRegistryDependent": 364, + "metadataFactOccurrences": 5983, + "comStandardFactOccurrences": 26134, + "registeredExactEntries": 506, + "metadataMatchedExactEntries": 506, + "safeConsumedExactEntries": 415, + "exactEntryInterfaceDependencies": 671, + "exactFamilyInterfaceDependencies": 417, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, @@ -102,7 +102,7 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 4, - "ownership": 180, + "ownership": 182, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 @@ -380,6 +380,8 @@ "com.ownership.entry.windows-win32-media-audio.iaudioeffectsmanager.4460b3ae4b44452786767548a8acd260.getaudioeffects.slot-5.param-0-effects.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.getdisplayname.slot-4.param-0-pretval.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.geticonpath.slot-6.param-0-pretval.v1": 1, + "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.activate.slot-3.v1": 1, + "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.getid.slot-5.param-0-ppstrid.v1": 1, "com.ownership.entry.windows-win32-media-directshow-tv.iatsc-ett.5a142cc9b8cf4a86a040e9cadf3ef3e7.getextendedmessagetext.slot-7.param-1-pptext.v1": 1, "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, @@ -530,7 +532,7 @@ "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, "com.nullable-input.v1": 2, - "com.ownership.v1": 122, + "com.ownership.v1": 123, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 3, @@ -541,7 +543,7 @@ }, "byMetadataAttribute": { "CanReturnMultipleSuccessValuesAttribute": 46, - "ConstAttribute": 3331, + "ConstAttribute": 3332, "FreeWithAttribute": 3, "NativeArrayInfoAttribute": 2602 }, @@ -551,12 +553,12 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5578, + "com.hresult.failure.v1": 5579, "com.interface.input-borrow.v1": 1890, - "com.interface.typed-output-plus-one.v1": 3457, - "com.iunknown.identity-refcount.v1": 5696, - "com.query-interface.output-plus-one.v1": 5696, - "com.standard-cleanup.matching-allocator.v1": 1436 + "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 }, "exactEntryStatus": { "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": { @@ -6745,6 +6747,45 @@ "safeConsumed": false, "interfaceDependencies": 0 }, + "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.activate.slot-3.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IMMDevice", + "iid": "d666063f-1587-4e43-81f1-b948e807363f", + "method": "Activate", + "slot": 3, + "parameter": null + }, + "sourceFingerprint": "5025E3C25B95D89F92271233B0761D56DF1041F985D6C1D0BAFE0FC4DEDD26E3", + "citation": "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.getid.slot-5.param-0-ppstrid.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IMMDevice", + "iid": "d666063f-1587-4e43-81f1-b948e807363f", + "method": "GetId", + "slot": 5, + "parameter": [ + 0, + "ppstrId" + ] + }, + "sourceFingerprint": "38AF4F595BEEADA67D0D49EB1B04F2CC354C8A06813B286CCAE4B5EF44BFCD99", + "citation": "microsoft-learn:https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-media-audio.ipart.ae2de0e45bca4f2daa465d13f8fdb3a9.getglobalid.slot-5.param-0-ppwstrglobalid.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -10824,27 +10865,27 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6108, - "raw_manual_contract": 1432, + "raw_metadata_complete": 6109, + "raw_manual_contract": 1431, "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1432, + "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 }, "i686": { - "raw_metadata_complete": 6107, - "raw_manual_contract": 1409, + "raw_metadata_complete": 6108, + "raw_manual_contract": 1408, "raw_runtime_blocked": 413, "safe_incomplete_raw_metadata_complete": 411, - "safe_incomplete_raw_manual_contract": 1409, + "safe_incomplete_raw_manual_contract": 1408, "safe_incomplete_raw_runtime_blocked": 413 }, "x64": { - "raw_metadata_complete": 6108, - "raw_manual_contract": 1432, + "raw_metadata_complete": 6109, + "raw_manual_contract": 1431, "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1432, + "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 } }, @@ -10892,11 +10933,11 @@ "manual_reason_counts": { "arm64": { "external_pointee_storage": 971, - "missing_allocator": 1041, + "missing_allocator": 1040, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1041, + "missing_output_ownership": 1040, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10909,11 +10950,11 @@ }, "i686": { "external_pointee_storage": 972, - "missing_allocator": 1041, + "missing_allocator": 1040, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1041, + "missing_output_ownership": 1040, "nested_pointer_lifetime": 534, "opaque_pointee_contract": 289, "pointee_missing_layout": 391, @@ -10926,11 +10967,11 @@ }, "x64": { "external_pointee_storage": 971, - "missing_allocator": 1041, + "missing_allocator": 1040, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1041, + "missing_output_ownership": 1040, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10946,8 +10987,8 @@ "arm64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4533, - "cleanup_unknown": 1159, + "cleanup_standard_supported": 4534, + "cleanup_unknown": 1158, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 @@ -10955,8 +10996,8 @@ "i686": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4533, - "cleanup_unknown": 1159, + "cleanup_standard_supported": 4534, + "cleanup_unknown": 1158, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1090 @@ -10964,8 +11005,8 @@ "x64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4533, - "cleanup_unknown": 1159, + "cleanup_standard_supported": 4534, + "cleanup_unknown": 1158, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 5cf2de56..556a9d5c 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -1452,7 +1452,7 @@ Windows.Win32.Media.Audio,IControlChangeNotify,a09513ed-c709-4d21-bd7b-5f34c47f3 Windows.Win32.Media.Audio,IControlInterface,45d37c3f-5140-444a-ae24-400789f3cbf3,false,,missing_allocator Windows.Win32.Media.Audio,IDeviceSpecificProperty,3b22bcbf-2586-4af0-8583-205d391b807c,false,,external_pointee_storage Windows.Win32.Media.Audio,IDeviceTopology,2a07407e-6497-4a18-9787-32f79bd0d98f,false,,missing_allocator -Windows.Win32.Media.Audio,IMMDevice,d666063f-1587-4e43-81f1-b948e807363f,false,,missing_allocator +Windows.Win32.Media.Audio,IMMDevice,d666063f-1587-4e43-81f1-b948e807363f,true,exact_registry_dependent, Windows.Win32.Media.Audio,IMMDeviceActivator,3b0d0ea4-d0a9-4b0e-935b-09516746fac0,false,,missing_allocator Windows.Win32.Media.Audio,IMMDeviceCollection,0bd7a1be-7a1a-44db-8397-cc5392387b5e,true,standard_derived, Windows.Win32.Media.Audio,IMMDeviceEnumerator,a95664d2-9614-4f35-a746-de8db63617e6,true,standard_derived, diff --git a/tests/e2e/runners/com/persist-file.mjs b/tests/e2e/runners/com/persist-file.mjs index df67451d..47e0a74c 100644 --- a/tests/e2e/runners/com/persist-file.mjs +++ b/tests/e2e/runners/com/persist-file.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { DynCom } from '../../../../bindings/js/dist/com-unsafe.js'; +import { projectAs } from '../../../../bindings/js/dist/com.js'; import { IID_IPersistFile, IPersistFile, @@ -11,10 +12,23 @@ import { const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; DynCom.initialize(1); -const persist = IPersistFile._fromNative( - DynCom.coCreateInstance(CLSID_SHELL_LINK, IID_IPersistFile), -); -assert.equal(persist.getClassID().toLowerCase(), CLSID_SHELL_LINK); -persist.release(); +const native = DynCom.coCreateInstance(CLSID_SHELL_LINK, IID_IPersistFile); +let persist; +let second; +try { + persist = projectAs(native, IPersistFile); + second = projectAs(persist, IPersistFile); + native.release(); + assert.equal(persist.getClassID().toLowerCase(), CLSID_SHELL_LINK); + persist.release(); + assert.equal(second.getClassID().toLowerCase(), CLSID_SHELL_LINK); + assert.throws(() => projectAs(0n, IPersistFile), /managed COM/); + assert.throws(() => projectAs(Buffer.alloc(8), IPersistFile), /managed COM/); + assert.throws(() => projectAs(second, { IID: IPersistFile.IID }), /registered generated safe COM/); +} finally { + persist?.release(); + second?.release(); + native.release(); +} console.log('persist-file ok'); diff --git a/tools/dynwinrt-codegen/contracts/classic-com/manifest.json b/tools/dynwinrt-codegen/contracts/classic-com/manifest.json index d5117ff3..3bbfafd3 100644 --- a/tools/dynwinrt-codegen/contracts/classic-com/manifest.json +++ b/tools/dynwinrt-codegen/contracts/classic-com/manifest.json @@ -11,7 +11,7 @@ "path": "ownership-outputs.json", "kind": "ownership", "familyIds": ["com.ownership.v1"], - "sha256": "96C76D7A2762FC077D73AF74050B7F585DB71B4E5A2E583FD50F212F82164C0C" + "sha256": "0D3A9B890BD89710B47487DAF12A1860C02DEE25279D2A82C1D228FB3AE727E6" } ] } diff --git a/tools/dynwinrt-codegen/contracts/classic-com/ownership-outputs.json b/tools/dynwinrt-codegen/contracts/classic-com/ownership-outputs.json index ca94b09b..f4bcbdc9 100644 --- a/tools/dynwinrt-codegen/contracts/classic-com/ownership-outputs.json +++ b/tools/dynwinrt-codegen/contracts/classic-com/ownership-outputs.json @@ -1,6 +1,55 @@ { "schemaVersion": 2, "contracts": [ + { + "entryId": "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.getid.slot-5.param-0-ppstrid.v1", + "familyId": "com.ownership.v1", + "kind": "ownership", + "reason": "IMMDevice::GetId allocates the endpoint ID string with task memory; the caller frees it with CoTaskMemFree", + "selector": { + "interface": { + "namespace": "Windows.Win32.Media.Audio", + "name": "IMMDevice", + "iid": "d666063f-1587-4e43-81f1-b948e807363f" + }, + "declaringIid": "d666063f-1587-4e43-81f1-b948e807363f", + "method": "GetId", + "absoluteSlot": 5, + "parameterCount": 1, + "parameters": [ + { + "index": 0, + "name": "ppstrId", + "nativeType": "Windows.Win32.Foundation.PWSTR", + "pointerDepth": 1, + "direction": "out", + "optional": false, + "constness": "mutable", + "constAttribute": false + } + ], + "sourceFingerprint": "38AF4F595BEEADA67D0D49EB1B04F2CC354C8A06813B286CCAE4B5EF44BFCD99" + }, + "contract": { + "parameterIndex": 0, + "ownership": "cotaskmem-owned", + "cleanup": "CoTaskMemFree" + }, + "evidence": [ + { + "kind": "microsoft-learn", + "url": "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid", + "file": null + } + ], + "validatedMetadata": [ + { + "package": "Microsoft.Windows.SDK.Win32Metadata", + "version": "71.0.14-preview", + "sha256": "B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D" + } + ] + }, { "entryId": "com.ownership.entry.windows-win32-devices-portabledevices.iportabledevice.625e2df863924cf09ad13cfa5f17775c.getpnpdeviceid.slot-11.param-0-ppszpnpdeviceid.v1", "familyId": "com.ownership.v1", diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index c55a2a0d..502e13c2 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4559,10 +4559,11 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_696); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_696); + 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, 363); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 364); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4570,34 +4571,34 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.metadata_fact_occurrences, - 5_982 + 5_983 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_129 + 26_134 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 504); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 506); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 504 + 506 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 413 + 415 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 669 + 671 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 416 + 417 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4610,7 +4611,7 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 4), - ("ownership".into(), 180), + ("ownership".into(), 182), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 3), @@ -4618,7 +4619,7 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 122 + 123 ); assert_eq!( report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], @@ -4640,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(), 413); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 415); assert!( report .summary @@ -4685,9 +4686,23 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 413 + 415 ); let status = &report.summary.safe_evidence.exact_entry_status; + assert_eq!( + status + .values() + .filter(|entry| entry.family_id == "com.ownership.v1") + .count(), + 169 + ); + assert_eq!( + status + .values() + .filter(|entry| entry.family_id == "com.ownership.v1" && entry.safe_consumed) + .count(), + 118 + ); assert_eq!( status .values() @@ -4759,6 +4774,25 @@ mod tests { promoted_audio.evidence_class, Some(SafeEvidenceClass::ExactRegistryDependent) )); + let endpoint = report + .interfaces + .iter() + .find(|interface| { + interface.namespace == "Windows.Win32.Media.Audio" && interface.name == "IMMDevice" + }) + .unwrap(); + assert!(endpoint.safe_complete); + assert!(matches!( + endpoint.evidence_class, + Some(SafeEvidenceClass::ExactRegistryDependent) + )); + assert_eq!(endpoint.exact_entry_ids.len(), 2); + assert!(endpoint.exact_entry_ids.contains( + &"com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.activate.slot-3.v1".into() + )); + assert!(endpoint.exact_entry_ids.contains( + &"com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.getid.slot-5.param-0-ppstrid.v1".into() + )); let data_object = report .interfaces .iter() @@ -4855,7 +4889,7 @@ mod tests { ), ( 412 - usize::from(target == CensusTarget::I686), - 1_432 - 23 * usize::from(target == CensusTarget::I686), + 1_431 - 23 * usize::from(target == CensusTarget::I686), 389 + 24 * usize::from(target == CensusTarget::I686) ) ); @@ -4962,6 +4996,7 @@ mod tests { "IDispatch", "IPropertyStore", "IClassFactory", + "IMMDevice", ] { let interface = report .interfaces diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 1c131f95..30e5f8f1 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -2319,13 +2319,13 @@ mod tests { }; let coverage = measure_stage2_coverage(&winmd).unwrap(); println!("{}", serde_json::to_string(&coverage).unwrap()); - assert_eq!(coverage.x64_manual_interfaces, 1_432); - assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_428); + assert_eq!(coverage.x64_manual_interfaces, 1_431); + assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_427); assert_eq!( coverage.x64_manual_interfaces_with_executable_manual_method, - 1_427 + 1_426 ); - assert_eq!(coverage.executable_manual_methods, 6_048); + assert_eq!(coverage.executable_manual_methods, 6_046); assert_eq!(coverage.remaining_manual_methods, 0); assert_eq!(coverage.runtime_blocked_methods, 1_161); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 72e9efb6..46adbcbc 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -413,6 +413,14 @@ pub(super) struct ProjectedInterfaceRef { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ProjectedComMethodKind { Normal, + RestrictedActivation { + iid_param_index: usize, + context_param_index: usize, + null_param_index: usize, + output_param_index: usize, + context: u32, + allowed_iids: [&'static str; 5], + }, FixedCapacityBytes { guid_param_index: usize, }, diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index bf97a571..04c42fe8 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -148,7 +148,7 @@ fn render_coclass_files( let mut js = String::new(); js.push_str("// Generated by dynwinrt-codegen — do not edit\n"); js.push_str(&format!( - "import {{ DynCom }} from '{}';\n", + "import {{ DynCom, __registerComProjection }} from '{}';\n", com_runtime_import_name_for_module(namespace) )); js.push_str(&format!( @@ -174,6 +174,10 @@ fn render_coclass_files( js.push_str(" tryAs(InterfaceClass) {\n const obj = DynCom.tryCast(this._obj, InterfaceClass.IID);\n if (obj === null) return null;\n try {\n return InterfaceClass._fromNative(obj);\n } finally {\n obj.release();\n }\n }\n"); js.push_str(" supports(InterfaceClass) {\n const obj = DynCom.tryCast(this._obj, InterfaceClass.IID);\n if (obj === null) return false;\n obj.release();\n return true;\n }\n"); js.push_str("}\n"); + js.push_str(&format!( + "__registerComProjection({name}, {}.IID);\n", + primary_interface.name + )); let descriptor = "{ readonly IID: unknown; _fromNative(obj: unknown): T }"; let mut dts = String::new(); @@ -215,7 +219,7 @@ fn render_js(meta: &ProjectedComInterface) -> String { "DynCom, DynComMethodSig, WinGuid" }; out.push_str(&format!( - "import {{ {runtime_imports} }} from '{}';\n", + "import {{ {runtime_imports}, __registerComProjection, __comProjectionIid, projectAs }} from '{}';\n", com_runtime_import_name_for_module(&meta.namespace) )); for en in &meta.referenced_enums { @@ -406,6 +410,9 @@ fn render_js(meta: &ProjectedComInterface) -> String { continue; } match method.kind { + ProjectedComMethodKind::RestrictedActivation { .. } => { + emit_restricted_activation_js(&mut out, method, &iface_var) + } ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } @@ -464,6 +471,10 @@ fn render_js(meta: &ProjectedComInterface) -> String { } } out.push_str("}\n"); + out.push_str(&format!( + "__registerComProjection({}, IID_{});\n", + meta.name, meta.name + )); out.push_str(&format!( "function {wrap_owned}(obj) {{\n DynCom.bindComObject(obj);\n return Object.assign(Object.create({}.prototype), {{ _obj: obj }});\n}}\n", meta.name @@ -2034,6 +2045,43 @@ fn emit_conditional_interface_output_method_js( out.push_str(" }\n"); } +fn emit_restricted_activation_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str) { + let ProjectedComMethodKind::RestrictedActivation { + iid_param_index, + context_param_index, + null_param_index, + output_param_index, + context, + allowed_iids, + } = &method.kind + else { + unreachable!("validated restricted activation") + }; + let args = (0..method.params.len()) + .filter_map(|index| { + if index == *iid_param_index { + Some("DynCom.iidPointer(_iid)".to_string()) + } else if index == *context_param_index { + Some(format!("DynCom.u32({context})")) + } else if index == *null_param_index { + Some("DynCom.exactNullPointer(null)".into()) + } else { + assert_eq!(index, *output_param_index); + None + } + }) + .collect::>(); + let allowed = allowed_iids + .iter() + .map(|iid| format!("'{iid}'")) + .collect::>() + .join(", "); + out.push_str(&format!( + " {}(InterfaceClass) {{\n const _iid = __comProjectionIid(InterfaceClass);\n if (![{}].includes(_iid.toString().toLowerCase())) throw new TypeError('Interface is outside the supported null-parameter activation contract');\n const _raw = {iface_var}.method({}).invoke(this._obj, [{}]);\n let _owned;\n try {{\n _owned = DynCom.adoptComPointer(_raw, _iid);\n return projectAs(_owned, InterfaceClass);\n }} finally {{\n if (_owned !== undefined) _owned.release();\n _raw.release();\n }}\n }}\n", + method.camel_name, allowed, method.vtable_index, args.join(", ") + )); +} + fn emit_dynamic_iid_method_js( out: &mut String, method: &ProjectedComMethod, @@ -2434,6 +2482,16 @@ fn render_dts(meta: &ProjectedComInterface) -> String { } continue; } + if matches!( + method.kind, + ProjectedComMethodKind::RestrictedActivation { .. } + ) { + out.push_str(&format!( + " {}(InterfaceClass: {{ readonly IID: WinGuid; _fromNative(value: unknown): T }}): T;\n", + method.camel_name + )); + continue; + } if let ProjectedComMethodKind::FlagSelectedString { discriminator_param_index, capacity_param_index, @@ -2514,6 +2572,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { continue; } let (params, ret) = match method.kind { + ProjectedComMethodKind::RestrictedActivation { .. } => unreachable!("emitted above"), ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 0a9408bf..91e06599 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -404,6 +404,21 @@ fn map_method( }) } else { match raw.exact_contract.as_ref().map(|contract| contract.kind) { + Some(RawExactMethodContractKind::RestrictedEndpointActivation) => method + .with_special_contract(ComMethodSpecialContract::RestrictedActivation { + iid_param: ParamIndex::new(0), + context_param: ParamIndex::new(1), + null_param: ParamIndex::new(2), + output_param: ParamIndex::new(3), + context: 1, + allowed_iids: [ + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "5cdf2c82-841e-4546-9722-0cf74078229a", + "c02216f6-8c67-4b5b-9d00-d008e73e0064", + "bfa971f1-4d5e-40bb-935e-967039bfbee4", + "77aa99a0-1bd6-484f-8bc7-2c654c9a9b6f", + ], + }), Some(RawExactMethodContractKind::FixedCapacityBytes) => { method.with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { guid_param: ParamIndex::new(0), @@ -494,7 +509,11 @@ fn map_param( || raw_method .exact_interface_output_call .as_ref() - .is_some_and(|contract| contract.context_param_index == param_index); + .is_some_and(|contract| contract.context_param_index == param_index) + || raw_method.exact_contract.as_ref().is_some_and(|contract| { + contract.kind == RawExactMethodContractKind::RestrictedEndpointActivation + && param_index == 2 + }); let effective_direction = documented_bstr_direction_override( interface_namespace, interface_name, diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index 9bd7ec49..79573ba0 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -33,6 +33,14 @@ impl ComReturnKind { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(in crate::codegen::com) enum ComMethodSpecialContract { + RestrictedActivation { + iid_param: ParamIndex, + context_param: ParamIndex, + null_param: ParamIndex, + output_param: ParamIndex, + context: u32, + allowed_iids: [&'static str; 5], + }, FixedCapacityBytes { guid_param: ParamIndex, }, diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 1dd1c9d2..fc19175b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -647,6 +647,31 @@ fn project_method( let context = || method.name().to_string(); let dynamic_iid = method.dynamic_iid_contract(); let mut kind = match method.special_contract() { + Some(ComMethodSpecialContract::RestrictedActivation { + iid_param, + context_param, + null_param, + output_param, + context: cls_context, + allowed_iids, + }) => { + if dynamic_iid.map(|plan| (plan.iid_param_index(), plan.output_param_index())) + != Some((iid_param, output_param)) + { + return Err(format!( + "{}: restricted activation requires an exact dynamic IID result", + context() + )); + } + ProjectedComMethodKind::RestrictedActivation { + iid_param_index: iid_param.index(), + context_param_index: context_param.index(), + null_param_index: null_param.index(), + output_param_index: output_param.index(), + context: cls_context, + allowed_iids, + } + } Some(ComMethodSpecialContract::FixedCapacityBytes { guid_param }) => { if dynamic_iid.is_some() { return Err(format!( @@ -903,6 +928,13 @@ fn project_method( if matches!(typ, ComType::ExactNullPointer) { surface_input = false; } + if matches!( + kind, + ProjectedComMethodKind::RestrictedActivation { context_param_index, .. } + if context_param_index == index + ) { + surface_input = false; + } if matches!( kind, ProjectedComMethodKind::ConditionalInterfaceOutput { @@ -1322,6 +1354,45 @@ fn project_method( } } + if let ProjectedComMethodKind::RestrictedActivation { + iid_param_index, + context_param_index, + null_param_index, + output_param_index, + context, + .. + } = kind + { + if ( + iid_param_index, + context_param_index, + null_param_index, + output_param_index, + ) != (0, 1, 2, 3) + || context != 1 + || params.len() != 4 + || params[0].typ != ComType::GuidPointer + || params[0].direction != ComParamDirection::In + || !matches!( + params[1].typ, + ComType::Enum { + underlying: ComEnumUnderlying::U32, + .. + } + ) + || params[1].direction != ComParamDirection::In + || params[2].typ != ComType::ExactNullPointer + || params[2].direction != ComParamDirection::In + || params[3].direction != ComParamDirection::Out + || return_convention != ComReturnConvention::HResult + || results.len() != 1 + || results[0].source != ResultSource::Param(3) + || results[0].conversion != ResultConversion::DynamicIidAdoption + { + return Err("restricted activation lost its validated input/output plan".into()); + } + } + if let ProjectedComMethodKind::AudioFormatSupport { share_mode_param_index, closest_match_param_index, @@ -3204,6 +3275,25 @@ fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComPara mod tests { use super::*; + #[test] + fn endpoint_activation_preserves_the_semantic_call_plan() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Media.Audio", + "IMMDevice", + ) + .unwrap(); + let validated = model::validate_interface(&meta).unwrap(); + let projected = project_validated_interface(&validated, &winmd).unwrap(); + assert!(matches!( + projected.methods[0].kind, + ProjectedComMethodKind::RestrictedActivation { .. } + )); + } + #[test] fn guid_format_preserves_canonical_semantic_identity() { assert_eq!( diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 825b6904..d6e1de79 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -387,6 +387,7 @@ pub enum RawExactMethodContractKind { AudioFormatOwnedOutput, AudioFormatSupport, NullableAudioFormatInput, + RestrictedEndpointActivation, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -430,6 +431,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::NullableAudioFormatInput => { crate::contract_registry::ExactFamilyId::NullableInput } + RawExactMethodContractKind::RestrictedEndpointActivation => { + crate::contract_registry::ExactFamilyId::Ownership + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ExactFamilyId::SemanticHresult } @@ -471,6 +475,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::NullableAudioFormatInput => { crate::contract_registry::ContractKind::NullInput } + RawExactMethodContractKind::RestrictedEndpointActivation => { + crate::contract_registry::ContractKind::Ownership + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ContractKind::SemanticHresult } @@ -2210,6 +2217,7 @@ fn apply_exact_method_contract( RawExactMethodContractKind::AudioFormatOwnedOutput => {} RawExactMethodContractKind::AudioFormatSupport => {} RawExactMethodContractKind::NullableAudioFormatInput => {} + RawExactMethodContractKind::RestrictedEndpointActivation => {} RawExactMethodContractKind::BorrowedStgMediumInput | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc => {} @@ -2390,6 +2398,14 @@ fn registered_exact_method_contract( "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-iwmdmdevicecontrol-record" }, ), + ("Windows.Win32.Media.Audio", "IMMDevice", "Activate") => ( + RawExactMethodContractKind::RestrictedEndpointActivation, + 3, + 0, + None, + "IMMDevice::Activate returns a counted interface reference for the requested IID; the safe subset uses CLSCTX_INPROC_SERVER and null activation parameters for documented endpoint interfaces", + "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + ), ("Windows.Win32.Media.Audio", "IAudioClient", "IsFormatSupported") => ( RawExactMethodContractKind::AudioFormatSupport, 2, @@ -2498,7 +2514,7 @@ fn registered_exact_method_contract( "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", "IStream" | "IDataObject" => "Windows.Win32.System.Com", - "IAudioClient" | "IAudioClient3" => "Windows.Win32.Media.Audio", + "IAudioClient" | "IAudioClient3" | "IMMDevice" => "Windows.Win32.Media.Audio", "IMDSPDeviceControl" | "IWMDMDeviceControl" => "Windows.Win32.Media.DeviceManager", "IOleCache" => "Windows.Win32.System.Ole", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", @@ -2522,12 +2538,16 @@ fn registered_exact_method_contract( "IDataObject" => "IDataObject", "IAudioClient" => "IAudioClient", "IAudioClient3" => "IAudioClient3", + "IMMDevice" => "IMMDevice", "IMDSPDeviceControl" => "IMDSPDeviceControl", "IWMDMDeviceControl" => "IWMDMDeviceControl", "IOleCache" => "IOleCache", _ => unreachable!("matched exact method interface"), }, declaring_iid: match kind { + RawExactMethodContractKind::RestrictedEndpointActivation => { + "d666063f-1587-4e43-81f1-b948e807363f" + } RawExactMethodContractKind::FixedCapacityBytes => { "2cd2d921-c447-44a7-a13c-4adabfc247e3" } @@ -2578,6 +2598,7 @@ fn registered_exact_method_contract( } }, method_name: match kind { + RawExactMethodContractKind::RestrictedEndpointActivation => "Activate", RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", RawExactMethodContractKind::UnsafePrivateData => "GetPrivateData", RawExactMethodContractKind::StatStg => "Stat", @@ -2603,6 +2624,7 @@ fn registered_exact_method_contract( RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", }, vtable_index: match (interface, method) { + ("IMMDevice", "Activate") => 3, ("IMFAttributes", "GetBlob") => 15, ("IDXGIObject", "GetPrivateData") => 5, ("ID3D10DeviceChild", "GetPrivateData") => 4, @@ -2642,6 +2664,9 @@ fn registered_exact_method_contract( == RawExactMethodContractKind::BorrowedStgMediumInput) .then_some(2), source_fingerprint: match (interface, method) { + ("IMMDevice", "Activate") => { + Some("5025E3C25B95D89F92271233B0761D56DF1041F985D6C1D0BAFE0FC4DEDD26E3") + } ("IMDSPDeviceControl", "Record") => { Some("346C3A5C69100EF034C6B1773533C7B9AB74C66F05581FF8D1D02370C9506F52") } @@ -2801,6 +2826,7 @@ pub(crate) fn validate_required_exact_contract_presence(raw: &RawComMethod) -> R | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc | RawExactMethodContractKind::NullableAudioFormatInput + | RawExactMethodContractKind::RestrictedEndpointActivation ) }); if required && raw.exact_contract.is_none() { @@ -2874,6 +2900,10 @@ pub(crate) fn validate_exact_method_contract( )); } let valid_shape = match contract.kind { + RawExactMethodContractKind::RestrictedEndpointActivation => { + raw_method_shape(raw) + == "Activate@3(iid:in:required:constattr:System.Guid[Unknown]/ptr1/Mutable,dwClsCtx:in:required:noconstattr:Windows.Win32.System.Com.CLSCTX[Enum]/ptr0/Unspecified/underlying=u32/ptr0/Unspecified,pActivationParams:in:optional:noconstattr:Windows.Win32.System.Com.StructuredStorage.PROPVARIANT[Struct]/ptr1/Mutable,ppInterface:out:required:noconstattr:void/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } RawExactMethodContractKind::FixedCapacityBytes => { raw.params.len() == 4 && raw.params[0].name == "guidKey" @@ -3057,6 +3087,14 @@ pub(crate) fn validate_exact_method_contract( } }; let indices_valid = match contract.kind { + RawExactMethodContractKind::RestrictedEndpointActivation => { + contract.buffer_param_index == 3 + && contract.capacity_param_index == 0 + && contract.actual_length_param_index.is_none() + && contract.discriminator_param_index.is_none() + && contract.reserved_null_param_index.is_none() + && contract.ownership_transfer_param_index.is_none() + } RawExactMethodContractKind::FixedCapacityBytes | RawExactMethodContractKind::UnsafePrivateData | RawExactMethodContractKind::StatStg => { @@ -5254,6 +5292,50 @@ mod tests { .unwrap(); } + #[test] + fn endpoint_activation_contract_is_exact() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let interface = + parse_com_interface(&winmd, "Windows.Win32.Media.Audio", "IMMDevice").unwrap(); + let method = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Activate") + .unwrap(); + let contract = method.exact_contract.as_ref().unwrap_or_else(|| { + panic!( + "missing endpoint activation contract: {} ({})", + raw_method_shape(method), + raw_method_fingerprint(method) + ) + }); + validate_exact_method_contract( + "Windows.Win32.Media.Audio", + "IMMDevice", + &interface.interface.iid, + method, + contract, + ) + .unwrap(); + let get_id = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetId") + .unwrap(); + assert!( + !get_id.output_ownership_contracts.is_empty(), + "missing GetId ownership: {} ({})", + raw_method_shape(get_id), + raw_method_fingerprint(get_id) + ); + } + #[test] fn audio_record_nullability_contracts_are_exact() { let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index 72e55d97..3d7a7f57 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -481,6 +481,7 @@ pub(crate) fn statically_declared_exact_entry_ids() -> Result, } const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ + "com.ownership.entry.windows-win32-media-audio.immdevice.d666063f15874e4381f1b948e807363f.activate.slot-3.v1", "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1", "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1", "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1", @@ -1154,9 +1155,9 @@ 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(), 504); + assert_eq!(ids.len(), 506); assert_eq!(registry.conditional_outputs.len(), 7); - assert_eq!(registry.ownership_outputs.len(), 148); + assert_eq!(registry.ownership_outputs.len(), 149); assert_eq!( registry.conditional_outputs[0].entry_id, "wmi.conditional-output.entry.windows-win32-system-wmi.iwbemservices.9556dc99828c11cfa37e00aa003240c7.opennamespace.slot-3.v1" diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 07600635..1a7a1a3b 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 = 2; +const COM_MANIFEST_VERSION: u32 = 3; #[derive(Debug, Default, Deserialize, Serialize)] struct ComGenerationManifest { @@ -8994,8 +8994,9 @@ mod tests { let error = has_com_output(&output).unwrap_err(); assert!( - error.contains("have no version 2 generation manifest") - && error.contains("delete and regenerate"), + error.contains(&format!( + "have no version {COM_MANIFEST_VERSION} generation manifest" + )) && error.contains("delete and regenerate"), "{error}" ); diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js index 718d4c88..f4f6573c 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, DynWinRtValue, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, DynWinRtValue, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const IID_IDataTransferManagerInterop = WinGuid.parse('3a3dcd6c-3eab-43dc-bcde-45671ce800c8'); const IID_DataTransferManager_default = WinGuid.parse('a5caee9b-8708-49d1-8d36-67d25a8da00c'); @@ -45,6 +45,7 @@ class IDataTransferManagerInterop { _IDataTransferManagerInterop.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(appWindow))]); } } +__registerComProjection(IDataTransferManagerInterop, IID_IDataTransferManagerInterop); function _wrapIDataTransferManagerInteropOwned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(IDataTransferManagerInterop.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js index acea0c00..378fed47 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const { SHOW_WINDOW_CMD } = require('../windows-and-messaging/SHOW_WINDOW_CMD.js'); const _nativeLayout_WIN32_FIND_DATAW = '{"name":"Windows.Win32.Storage.FileSystem.WIN32_FIND_DATAW","x86":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"x64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"arm64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]}}'; @@ -153,6 +153,7 @@ class IShellLinkW { _IShellLinkW.method(20).invoke(this._obj, [DynCom.safeWideStringPointer(file)]); } } +__registerComProjection(IShellLinkW, IID_IShellLinkW); function _wrapIShellLinkWOwned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(IShellLinkW.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js index dbb7bf72..cca01f79 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const IID_ITaskbarList = WinGuid.parse('56fdf342-fd6d-11d0-958a-006097c9a090'); @@ -125,6 +125,7 @@ class ITaskbarList { _ITaskbarList.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } } +__registerComProjection(ITaskbarList, IID_ITaskbarList); function _wrapITaskbarListOwned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(ITaskbarList.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js index acaee1ff..4a9cd333 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const IID_ITaskbarList2 = WinGuid.parse('602d4995-b13a-429b-a66e-1935e44f4317'); @@ -137,6 +137,7 @@ class ITaskbarList2 { _ITaskbarList2.method(8).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(fFullscreen ? 1 : 0)]); } } +__registerComProjection(ITaskbarList2, IID_ITaskbarList2); function _wrapITaskbarList2Owned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(ITaskbarList2.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js index 861c8950..cc8a031d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const { TBPFLAG } = require('./TBPFLAG.js'); const _nativeLayout_RECT = '{"name":"Windows.Win32.Foundation.RECT","x86":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"x64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"arm64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]}}'; @@ -277,6 +277,7 @@ class ITaskbarList3 { _ITaskbarList3.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), prcClip === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_RECT, prcClip)]); } } +__registerComProjection(ITaskbarList3, IID_ITaskbarList3); function _wrapITaskbarList3Owned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(ITaskbarList3.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js index 97b671cc..cf1cc162 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, DynComMethodSig, WinGuid, __registerComProjection, __comProjectionIid, projectAs } = require('@microsoft/dynwinrt/com/unsafe'); const { TBPFLAG } = require('./TBPFLAG.js'); const { STPFLAG } = require('./STPFLAG.js'); @@ -290,6 +290,7 @@ class ITaskbarList4 { _ITaskbarList4.method(21).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.i32(stpFlags)]); } } +__registerComProjection(ITaskbarList4, IID_ITaskbarList4); function _wrapITaskbarList4Owned(obj) { DynCom.bindComObject(obj); return Object.assign(Object.create(ITaskbarList4.prototype), { _obj: obj }); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js index 3ec3dcf7..03b3c90d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom } = require('@microsoft/dynwinrt/com/unsafe'); +const { DynCom, __registerComProjection } = require('@microsoft/dynwinrt/com/unsafe'); const { ITaskbarList4, IID_ITaskbarList4 } = require('./ITaskbarList4.js'); const CLSID_TaskbarList = '56fdf344-fd6d-11d0-958a-006097c9a090'; @@ -37,5 +37,6 @@ class TaskbarList extends ITaskbarList4 { return true; } } +__registerComProjection(TaskbarList, ITaskbarList4.IID); exports.CLSID_TaskbarList = CLSID_TaskbarList; exports.TaskbarList = TaskbarList; diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 788b40af..bd206d28 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2201,6 +2201,46 @@ fn data_object_projects_hglobal_format_and_medium_values() { assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); } +#[test] +fn endpoint_activation_projects_a_typed_null_parameter_factory() { + if !win32_available() { + return; + } + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.Media.Audio", "IMMDevice") + .unwrap(); + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + assert!(output.dts.contains("activate(InterfaceClass:")); + assert!(!output.dts.contains("pActivationParams:")); + assert!(!output.dts.contains("dwClsCtx:")); + assert!( + output + .js + .contains("DynCom.u32(1), DynCom.exactNullPointer(null)") + ); + assert!(output.js.contains("DynCom.ownedComPointerType()")); + assert!(output.js.contains("projectAs(_owned, InterfaceClass)")); + assert!( + output + .js + .contains("__registerComProjection(IMMDevice, IID_IMMDevice)") + ); + for mutation in 0..6 { + let mut drift = interface.clone(); + let raw = &mut drift.raw_methods.as_mut().unwrap()[0]; + match mutation { + 0 => raw.exact_contract = None, + 1 => raw.params[0].const_attribute = false, + 2 => raw.params[2].typ.pointer_depth = 2, + 3 => raw.params[3].optional = true, + 4 => raw.vtable_index += 1, + 5 => raw.params[2].direction = com_metadata::RawParamDirection::InOut, + _ => unreachable!(), + } + assert!(com::generate_com_interface_files(&drift, &win32_winmd()).is_err()); + } +} + #[test] fn device_control_record_projects_exact_nullable_audio_formats() { if !win32_available() { From ce0d339701ef1aa40b7e40c1be968856e7f84b9e Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 8 Sep 2026 11:52:50 +0800 Subject: [PATCH 2/4] Move endpoint activation targets into a cited contract registry Preserve the five existing target IIDs, in-process context, native NULL parameters and owned result contract. Validate named evidence records and lower dynamic-length IID lists without changing generated bindings or coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .../classic-com-contract-evidence-registry.md | 14 ++ docs/guides/windows/classic-com-usage.md | 8 + tools/dynwinrt-codegen/src/codegen/com/ir.rs | 2 +- .../src/codegen/com/model/metadata.rs | 105 +++++++++++-- .../src/codegen/com/model/method.rs | 10 +- .../src/com_activation_registry.rs | 140 ++++++++++++++++++ tools/dynwinrt-codegen/src/lib.rs | 1 + 7 files changed, 262 insertions(+), 18 deletions(-) create mode 100644 tools/dynwinrt-codegen/src/com_activation_registry.rs diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index ec439e61..94c07839 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -406,6 +406,20 @@ entries: the JSON ownership entry copies the returned UTF-16 string and pairs the allocation with `CoTaskMemFree`, yielding `getId(): string`. +The activation targets are named records in +`tools/dynwinrt-codegen/src/com_activation_registry.rs`, not an anonymous +fixed-length IID array in the language model. Each record carries its interface +identity, authoritative citation, reason, and the in-process/native-NULL/owned +result conditions. Semantic lowering rejects missing or ambiguous evidence and +passes only the validated context and target IIDs to the projected IR; the +renderer does not interpret evidence. + +These records are part of the existing exact `IMMDevice::Activate` contract, +not additional safe-interface or per-entry census contributions. The migration +keeps the same five targets and does not add `IDeviceTopology` or general +activation. Activation-policy eligibility, wrapper completeness, and actual +device support remain separate requirements. + The activation target must be a registered generated safe class with the IID of `IAudioClient`, `IAudioEndpointVolume`, `IAudioMeterInformation`, `IAudioSessionManager`, or `IAudioSessionManager2`. Other/custom targets, diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 540aaefd..31ceb7f0 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -646,6 +646,14 @@ Generate and import whichever target the application needs. Other/custom targets, async activation, and loopback or other parameterized activation remain outside this safe subset. +The five targets are named, cited records in +`tools/dynwinrt-codegen/src/com_activation_registry.rs`, each carrying the +in-process/native-NULL/owned-interface conditions of this method contract. +This is the current projection policy, not an exhaustive Windows activation +list. Registering activation evidence does not establish a target wrapper's +complete safe support or guarantee that a device implements the requested IID. +This registry migration preserves the existing five targets and generated API. + `getId()` returns a natural string and frees the native CoTaskMem allocation. The existing safe `IAudioClient`/`IAudioClient2`/`IAudioClient3` format methods, including `getMixFormat()`, and the exact nullable device-control `record()` diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 46adbcbc..2eb8bdab 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -419,7 +419,7 @@ pub(super) enum ProjectedComMethodKind { null_param_index: usize, output_param_index: usize, context: u32, - allowed_iids: [&'static str; 5], + allowed_iids: Vec, }, FixedCapacityBytes { guid_param_index: usize, diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 91e06599..f09e3aa6 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -404,21 +404,19 @@ fn map_method( }) } else { match raw.exact_contract.as_ref().map(|contract| contract.kind) { - Some(RawExactMethodContractKind::RestrictedEndpointActivation) => method - .with_special_contract(ComMethodSpecialContract::RestrictedActivation { + Some(RawExactMethodContractKind::RestrictedEndpointActivation) => { + let (context, allowed_iids) = map_activation_targets( + crate::com_activation_registry::imm_device_activate_targets(), + )?; + method.with_special_contract(ComMethodSpecialContract::RestrictedActivation { iid_param: ParamIndex::new(0), context_param: ParamIndex::new(1), null_param: ParamIndex::new(2), output_param: ParamIndex::new(3), - context: 1, - allowed_iids: [ - "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", - "5cdf2c82-841e-4546-9722-0cf74078229a", - "c02216f6-8c67-4b5b-9d00-d008e73e0064", - "bfa971f1-4d5e-40bb-935e-967039bfbee4", - "77aa99a0-1bd6-484f-8bc7-2c654c9a9b6f", - ], - }), + context, + allowed_iids, + }) + } Some(RawExactMethodContractKind::FixedCapacityBytes) => { method.with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { guid_param: ParamIndex::new(0), @@ -489,6 +487,46 @@ fn map_method( Ok(method) } +fn map_activation_targets( + entries: &[crate::com_activation_registry::ActivationTargetEvidence], +) -> Result<(u32, Vec), ModelError> { + use crate::com_activation_registry::{ + ActivationConditions, ActivationContext, ActivationOutput, ActivationParameters, + }; + + let required = ActivationConditions { + context: ActivationContext::InProcess, + parameters: ActivationParameters::NativeNull, + output: ActivationOutput::OwnedRequestedInterface, + }; + if entries.is_empty() { + return Err(ModelError::InvalidContract( + "restricted activation requires target contract evidence".into(), + )); + } + let mut identities = std::collections::HashSet::new(); + let mut names = std::collections::HashSet::new(); + let mut iids = Vec::with_capacity(entries.len()); + for entry in entries { + let iid = ComGuid::parse(entry.iid)?; + if iid.is_zero() + || !identities.insert(iid) + || !names.insert((entry.namespace, entry.interface)) + || entry.conditions != required + || entry.reason.trim().is_empty() + || !entry.citation.starts_with("https://learn.microsoft.com/") + { + return Err(ModelError::InvalidContract(format!( + "{}.{} has invalid, duplicate, or incompatible activation target evidence", + entry.namespace, entry.interface + ))); + } + QualifiedName::new(entry.namespace, entry.interface)?; + iids.push(entry.iid.to_ascii_lowercase()); + } + Ok((required.context.native_value(), iids)) +} + fn map_param( model: &mut ComModel, interface_namespace: &str, @@ -2554,6 +2592,51 @@ fn is_explicit_pointer_alias(namespace: &str, name: &str) -> bool { mod tests { use super::*; + #[test] + fn activation_target_registry_lowers_without_a_fixed_target_count() { + let entries = crate::com_activation_registry::imm_device_activate_targets(); + let (context, iids) = map_activation_targets(entries).unwrap(); + assert_eq!(context, 1); + assert_eq!( + iids, + entries.iter().map(|entry| entry.iid).collect::>() + ); + let (context, subset) = map_activation_targets(&entries[..2]).unwrap(); + assert_eq!(context, 1); + assert_eq!(subset.len(), 2); + let mut mixed_case = entries.to_vec(); + mixed_case[0].iid = "1CB9AD4C-DBFA-4C32-B178-C2F568A703B2"; + assert_eq!(map_activation_targets(&mixed_case).unwrap().1, iids); + } + + #[test] + fn activation_target_registry_rejects_missing_or_ambiguous_evidence() { + let entries = crate::com_activation_registry::imm_device_activate_targets(); + assert!(map_activation_targets(&[]).is_err()); + for mutation in 0..9 { + let mut invalid = entries.to_vec(); + match mutation { + 0 => invalid[1].iid = invalid[0].iid, + 1 => { + invalid[1].namespace = invalid[0].namespace; + invalid[1].interface = invalid[0].interface; + } + 2 => invalid[0].iid = "not-an-iid", + 3 => invalid[0].iid = "00000000-0000-0000-0000-000000000000", + 4 => invalid[0].citation = "", + 5 => invalid[0].reason = " ", + 6 => invalid[0].namespace = "", + 7 => invalid[0].interface = "", + 8 => invalid[1].iid = "1CB9AD4C-DBFA-4C32-B178-C2F568A703B2", + _ => unreachable!(), + } + assert!( + map_activation_targets(&invalid).is_err(), + "accepted mutation {mutation}" + ); + } + } + #[test] fn const_attribute_does_not_erase_mixed_pointer_qualifiers() { assert_eq!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index 79573ba0..c35935ff 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -31,7 +31,7 @@ impl ComReturnKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub(in crate::codegen::com) enum ComMethodSpecialContract { RestrictedActivation { iid_param: ParamIndex, @@ -39,7 +39,7 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { null_param: ParamIndex, output_param: ParamIndex, context: u32, - allowed_iids: [&'static str; 5], + allowed_iids: Vec, }, FixedCapacityBytes { guid_param: ParamIndex, @@ -453,10 +453,8 @@ impl ComMethodContract { self.return_kind } - pub(in crate::codegen::com) const fn special_contract( - &self, - ) -> Option { - self.special_contract + pub(in crate::codegen::com) fn special_contract(&self) -> Option { + self.special_contract.clone() } pub(in crate::codegen::com) const fn dynamic_iid_contract(&self) -> Option { diff --git a/tools/dynwinrt-codegen/src/com_activation_registry.rs b/tools/dynwinrt-codegen/src/com_activation_registry.rs new file mode 100644 index 00000000..0e1680ed --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_activation_registry.rs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ActivationContext { + InProcess, +} + +impl ActivationContext { + pub(crate) const fn native_value(self) -> u32 { + match self { + Self::InProcess => 1, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ActivationParameters { + NativeNull, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ActivationOutput { + OwnedRequestedInterface, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ActivationConditions { + pub context: ActivationContext, + pub parameters: ActivationParameters, + pub output: ActivationOutput, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ActivationTargetEvidence { + pub namespace: &'static str, + pub interface: &'static str, + pub iid: &'static str, + pub conditions: ActivationConditions, + pub reason: &'static str, + pub citation: &'static str, +} + +const ORDINARY_ENDPOINT_ACTIVATION: ActivationConditions = ActivationConditions { + context: ActivationContext::InProcess, + parameters: ActivationParameters::NativeNull, + output: ActivationOutput::OwnedRequestedInterface, +}; + +const IMM_DEVICE_ACTIVATE_TARGETS: &[ActivationTargetEvidence] = &[ + ActivationTargetEvidence { + namespace: "Windows.Win32.Media.Audio", + interface: "IAudioClient", + iid: "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + conditions: ORDINARY_ENDPOINT_ACTIVATION, + reason: "Ordinary endpoint audio-client activation uses null parameters; parameterized loopback activation is outside this contract", + citation: "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + }, + ActivationTargetEvidence { + namespace: "Windows.Win32.Media.Audio.Endpoints", + interface: "IAudioEndpointVolume", + iid: "5cdf2c82-841e-4546-9722-0cf74078229a", + conditions: ORDINARY_ENDPOINT_ACTIVATION, + reason: "Endpoint-volume activation requires null activation parameters", + citation: "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + }, + ActivationTargetEvidence { + namespace: "Windows.Win32.Media.Audio.Endpoints", + interface: "IAudioMeterInformation", + iid: "c02216f6-8c67-4b5b-9d00-d008e73e0064", + conditions: ORDINARY_ENDPOINT_ACTIVATION, + reason: "Endpoint-meter activation requires null activation parameters", + citation: "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + }, + ActivationTargetEvidence { + namespace: "Windows.Win32.Media.Audio", + interface: "IAudioSessionManager", + iid: "bfa971f1-4d5e-40bb-935e-967039bfbee4", + conditions: ORDINARY_ENDPOINT_ACTIVATION, + reason: "Audio-session-manager activation requires null activation parameters", + citation: "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + }, + ActivationTargetEvidence { + namespace: "Windows.Win32.Media.Audio", + interface: "IAudioSessionManager2", + iid: "77aa99a0-1bd6-484f-8bc7-2c654c9a9b6f", + conditions: ORDINARY_ENDPOINT_ACTIVATION, + reason: "IMMDevice documents the extended audio-session manager as an activation target using the ordinary session-manager parameter policy", + citation: "https://learn.microsoft.com/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-activate", + }, +]; + +/// Targets for the independently fingerprinted IMMDevice::Activate method contract. +/// Registration does not establish wrapper completeness or device availability. +pub(crate) const fn imm_device_activate_targets() -> &'static [ActivationTargetEvidence] { + IMM_DEVICE_ACTIVATE_TARGETS +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoint_activation_target_set_is_unchanged() { + let targets = imm_device_activate_targets(); + assert_eq!( + targets.iter().map(|entry| entry.iid).collect::>(), + [ + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "5cdf2c82-841e-4546-9722-0cf74078229a", + "c02216f6-8c67-4b5b-9d00-d008e73e0064", + "bfa971f1-4d5e-40bb-935e-967039bfbee4", + "77aa99a0-1bd6-484f-8bc7-2c654c9a9b6f", + ] + ); + assert!( + targets + .iter() + .all(|entry| entry.conditions == ORDINARY_ENDPOINT_ACTIVATION) + ); + assert!( + !targets + .iter() + .any(|entry| entry.interface == "IDeviceTopology") + ); + } + + #[test] + fn endpoint_activation_target_names_match_pinned_metadata() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + for entry in imm_device_activate_targets() { + let interface = + crate::com_metadata::parse_com_interface(&winmd, entry.namespace, entry.interface) + .expect("registered activation target must exist in the configured metadata"); + assert_eq!(interface.interface.iid, entry.iid); + } + } +} diff --git a/tools/dynwinrt-codegen/src/lib.rs b/tools/dynwinrt-codegen/src/lib.rs index 0fc3b645..175603ba 100644 --- a/tools/dynwinrt-codegen/src/lib.rs +++ b/tools/dynwinrt-codegen/src/lib.rs @@ -2,6 +2,7 @@ // Licensed under the MIT License. pub mod codegen; +mod com_activation_registry; mod com_borrowed_handle_registry; mod com_enumerator_registry; pub mod com_metadata; From 1032d490319c2b515a0fa88a383c27c8b2c8bbbc Mon Sep 17 00:00:00 2001 From: leileizhang Date: Wed, 9 Sep 2026 09:46:03 +0800 Subject: [PATCH 3/4] Add metadata-driven native COM one-shot completion (PR2/4) (#145) * Add metadata-driven native COM one-shot completion Generate bounded audio activation promises with validated WinMD contracts, libffi export/result plans, a native-only FTM signal sink, and owner-local result collection. Preserve synchronous JS callback thread restrictions. Cover publication, HRESULTs, ownership, teardown, bounds, and WinRT regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb * Add guarded COM borrowed-copy transactions for Audio, WIC and MF (#146) * 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 * 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 * 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 * 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 --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 56 +- .github/workflows/coverage.yml | 1 + .github/workflows/python-release.yml | 1 + Cargo.lock | 11 + Cargo.toml | 1 + README.md | 18 +- bindings/js/Cargo.toml | 3 +- bindings/js/__test__/borrowed-copy-child.cjs | 363 ++++++ bindings/js/__test__/borrowed-copy.e2e.ts | 104 ++ bindings/js/__test__/borrowed-plan.spec.ts | 100 ++ .../generated-unsafe-companion.e2e.ts | 3 +- bindings/js/__test__/index.spec.ts | 8 +- .../js/__test__/native-completion-child.mjs | 275 +++++ .../native-completion-unload-child.mjs | 43 + .../js/__test__/native-completion-worker.mjs | 30 + bindings/js/__test__/native-completion.e2e.ts | 137 +++ bindings/js/package.json | 2 + bindings/js/runtime/com-projection.cjs | 15 +- bindings/js/scripts/generate-entrypoints.mjs | 3 + bindings/js/src/com.rs | 369 ++++-- bindings/js/src/com_borrowed.rs | 305 +++++ bindings/js/src/com_completion.rs | 440 +++++++ bindings/js/src/com_completion_test_hooks.rs | 737 +++++++++++ bindings/js/src/com_input.rs | 397 ++++++ bindings/js/src/com_input_tests.rs | 653 ++++++++++ bindings/js/src/lib.rs | 630 +++++++--- bindings/js/src/managed_tsfn.rs | 62 +- 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 | 9 + crates/dynwinrt/src/call.rs | 32 +- crates/dynwinrt/src/com.rs | 285 ++++- crates/dynwinrt/src/com_automation.rs | 15 + crates/dynwinrt/src/com_borrowed.rs | 851 +++++++++++++ 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 | 1087 +++++++++++++++++ crates/dynwinrt/src/com_borrowed_tests.rs | 762 ++++++++++++ crates/dynwinrt/src/com_completion.rs | 619 ++++++++++ crates/dynwinrt/src/native_call.rs | 132 +- .../classic-com-contract-evidence-registry.md | 81 +- .../classic-com-generated-unsafe.md | 35 +- docs/architecture/classic-com-support.md | 369 +++++- docs/guides/windows/classic-com-usage.md | 207 +++- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 75 +- .../classic-com-capability-summary.json | 546 ++++++++- .../classic-com-interface-support.csv | 50 +- eng/coverage/coverage.ps1 | 1 + tools/dynwinrt-codegen/Cargo.toml | 1 + .../src/codegen/com/capability.rs | 44 +- .../src/codegen/com/completion.rs | 331 +++++ .../src/codegen/com/generated_unsafe.rs | 4 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 101 +- .../src/codegen/com/javascript/render.rs | 128 +- .../codegen/com/javascript/render_tests.rs | 17 + tools/dynwinrt-codegen/src/codegen/com/mod.rs | 17 + .../src/codegen/com/model/borrowed.rs | 59 + .../src/codegen/com/model/mod.rs | 1 + .../src/codegen/com/project/borrowed.rs | 186 +++ .../codegen/com/project/legacy_diagnostics.rs | 1 + .../src/codegen/com/project/mod.rs | 334 ++++- .../src/com_borrowed_metadata.rs | 220 ++++ .../src/com_completion_metadata.rs | 162 +++ tools/dynwinrt-codegen/src/com_metadata.rs | 10 +- .../dynwinrt-codegen/src/contract_registry.rs | 17 +- tools/dynwinrt-codegen/src/main.rs | 75 +- .../tests/com_explicit_overload_test.rs | 186 +++ 71 files changed, 15464 insertions(+), 558 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/__test__/borrowed-plan.spec.ts create mode 100644 bindings/js/__test__/native-completion-child.mjs create mode 100644 bindings/js/__test__/native-completion-unload-child.mjs create mode 100644 bindings/js/__test__/native-completion-worker.mjs create mode 100644 bindings/js/__test__/native-completion.e2e.ts create mode 100644 bindings/js/src/com_borrowed.rs create mode 100644 bindings/js/src/com_completion.rs create mode 100644 bindings/js/src/com_completion_test_hooks.rs create mode 100644 bindings/js/src/com_input.rs create mode 100644 bindings/js/src/com_input_tests.rs 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.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 create mode 100644 crates/dynwinrt/src/com_borrowed_test_support.rs create mode 100644 crates/dynwinrt/src/com_borrowed_tests.rs create mode 100644 crates/dynwinrt/src/com_completion.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/completion.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 create mode 100644 tools/dynwinrt-codegen/src/com_completion_metadata.rs 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 c22e5ef0..81700d63 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -72,7 +72,11 @@ 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 run: cargo test -p dynwinrt-codegen - name: Test raw union MSVC C oracle (x64) @@ -90,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) { @@ -107,21 +111,27 @@ 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" } + 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) - 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 @@ -134,16 +144,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5697 -or - $result.safeEvidence.standardDerived -ne 5333 -or - $result.safeEvidence.exactRegistryDependent -ne 364 -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.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 694 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 425 ) { throw "Classic COM safe evidence dependency census changed" } @@ -154,7 +164,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" } @@ -287,6 +299,12 @@ jobs: - name: Test actual generated unsafe COM companion working-directory: bindings/js run: npm run test:generated-unsafe + - 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/.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 b0e42e9f..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" @@ -588,6 +598,7 @@ dependencies = [ "napi-build", "napi-derive", "pollster", + "serde", "serde_json", "windows", "windows-future", 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/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/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index bc5c0e16..f847fac1 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_UI_Shell_PropertiesSystem"] +test-hooks = ["dynwinrt/test-hooks", "windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_Media_Audio_Endpoints", "windows/Win32_UI_Shell_PropertiesSystem"] [dependencies] napi = { version = "3", features = ["napi7"] } @@ -22,6 +22,7 @@ windows-future = "0.3.2" windows-string = "0.0.0" pollster = "0.4.0" serde_json = "1" +serde = { version = "1", features = ["derive"] } [dependencies.windows] version = ">=0.59, <=0.62" diff --git a/bindings/js/__test__/borrowed-copy-child.cjs b/bindings/js/__test__/borrowed-copy-child.cjs new file mode 100644 index 00000000..adcb95b1 --- /dev/null +++ b/bindings/js/__test__/borrowed-copy-child.cjs @@ -0,0 +1,363 @@ +// 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, IMFSample } = + 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 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])) + 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') + 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) + 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.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.calls[0].slot = 42 + }, + (d) => { + d.audio_origin = { role: 'render' } + }, + (d) => { + d.operations[0].cleanup = 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 + }, + (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) + 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..9858dce8 --- /dev/null +++ b/bindings/js/__test__/borrowed-copy.e2e.ts @@ -0,0 +1,104 @@ +// 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,Windows.Win32.Media.MediaFoundation.IMFSample', + '--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, 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', + '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__/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/__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 4bac0315..ac820f87 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -58,6 +58,9 @@ const moduleKeys = (value: object) => test('Classic COM is isolated from the WinRT root entrypoint', (t) => { t.false(Object.prototype.hasOwnProperty.call(winrtRuntime, 'DynCom')) + t.false(Object.prototype.hasOwnProperty.call(winrtRuntime, 'DynComAsync')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComAsync')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, '__activateAudioInterfaceAsync')) t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynCom')) t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComUnsafe')) t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComMethodSig')) @@ -167,6 +170,7 @@ test('package facades exactly partition native exports', (t) => { ]) const unsafeComNames = new Set([ ...safeComNames, + 'DynComBorrowedCopyPlan', 'DynCom', 'DynComDispatchInvokeResult', 'DynComInterface', @@ -194,11 +198,11 @@ test('package facades exactly partition native exports', (t) => { ) t.deepEqual( moduleKeys(unsafeComRuntime), - [...nativeKeys.filter((name) => unsafeComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid'].sort(), + [...nativeKeys.filter((name) => unsafeComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid', '__activateAudioInterfaceAsync'].sort(), ) t.deepEqual( moduleKeys(rawComRuntime), - [...nativeKeys.filter((name) => rawComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid'].sort(), + [...nativeKeys.filter((name) => rawComNames.has(name)), 'projectAs', '__registerComProjection', '__comProjectionIid', '__activateAudioInterfaceAsync'].sort(), ) t.is(winrtCjsRuntime.WinGuid, comCjsRuntime.WinGuid) diff --git a/bindings/js/__test__/native-completion-child.mjs b/bindings/js/__test__/native-completion-child.mjs new file mode 100644 index 00000000..3bca35d1 --- /dev/null +++ b/bindings/js/__test__/native-completion-child.mjs @@ -0,0 +1,275 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { AsyncLocalStorage } from 'node:async_hooks' +import { Worker } from 'node:worker_threads' + +const require = createRequire(import.meta.url) +const runtimePath = process.env.DYNWINRT_COMPLETION_RUNTIME +const generatedRoot = process.env.DYNWINRT_COMPLETION_GENERATED +const native = require(runtimePath) +const com = require(join(dirname(runtimePath), 'com.js')) +const winrt = require(join(dirname(runtimePath), 'winrt.js')) +const { activateAudioInterfaceAsync, IAudioClient, IAudioEndpointVolume, IMMDevice } = require( + join(generatedRoot, 'com', 'index.js'), +) +const path = 'dynwinrt-test-render' +const scenario = process.argv[2] + +const stats = () => native.comCompletionTestStats() +const configure = (mode) => native.comCompletionTestConfigure(mode) +async function until(predicate) { + const deadline = Date.now() + 10_000 + while (!predicate()) { + assert.ok(Date.now() < deadline, JSON.stringify(stats())) + await new Promise((resolve) => setTimeout(resolve, 2)) + } +} +async function clean(expectedResults) { + await until(() => { + const s = stats() + return s.operationCreated === s.operationDropped && s.signalsLive === 0 + }) + const s = stats() + assert.equal(s.pending, 0) + assert.equal(s.resultCreated, expectedResults) + assert.equal(s.resultDropped, expectedResults) + assert.equal(s.wrongThread, 0) + assert.equal(s.marshalingErrors, 0) + assert.equal(s.callbackErrors, 0) + assert.equal(native.tsfnTestRegisteredHandleCount(), 0) +} + +if (scenario === 'render-smoke') { + native.roInitialize(0) + native.initializeCom(0) + const { MediaDevice, AudioDeviceRole } = require(join(generatedRoot, 'index.js')) + const renderPath = MediaDevice.getDefaultAudioRenderId(AudioDeviceRole.Default) + assert.ok(renderPath, 'The opt-in smoke requires a default speaker endpoint') + // Resolve only the render device. No capture ID, recording, or settings. + const volume = await activateAudioInterfaceAsync(renderPath, IAudioEndpointVolume) + try { + assert.ok(volume instanceof IAudioEndpointVolume) + const channels = volume.getChannelCount() + assert.ok(Number.isInteger(channels) && channels > 0) + } finally { + volume.release() + } +} else if (scenario === 'uninitialized') { + configure('mta') + await assert.rejects(activateAudioInterfaceAsync(path, IAudioClient), (error) => { + assert.equal(error.stage, 'apartment') + assert.equal(error.hresult, 0x800401f0 | 0) + return true + }) + await clean(0) + assert.equal(stats().startCalls, 0) +} else if (scenario === 'sta' || scenario === 'mta') { + native.initializeCom(scenario === 'sta' ? 0 : 1) + assert.equal(winrt.DynComAsync, undefined) + assert.equal(winrt.activateAudioInterfaceAsync, undefined) + assert.equal(com.DynComAsync, undefined) + assert.equal(com.__activateAudioInterfaceAsync, undefined) + const context = new AsyncLocalStorage() + for (const mode of ['mta', 'early', 'duplicate']) { + configure(mode) + await context.run({ mode }, async () => { + const promise = activateAudioInterfaceAsync(path, IAudioClient) + assert.equal(promise.cancel, undefined) + assert.equal(stats().resultCalls, 0, 'result access must wait for owner dispatch') + const result = await promise + assert.equal(context.getStore().mode, mode) + assert.ok(result instanceof IAudioClient) + assert.equal(result.getBufferSize(), 384) + const projected = com.projectAs(result, IAudioClient) + assert.equal(projected.getBufferSize(), 384) + projected.release() + assert.throws( + () => result._obj.cast(native.WinGuid.parse('94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90')), + /interface|80004002/i, + ) + assert.throws( + () => result._obj.cast(native.WinGuid.parse('00000003-0000-0000-c000-000000000046')), + /interface|80004002/i, + ) + result.release() + }) + await clean(1) + const s = stats() + assert.equal(s.startCalls, 1) + assert.equal(s.validatedArguments, 1) + assert.equal(s.signalQiChecks, 1) + assert.equal(s.resultCalls, 1) + assert.equal(s.callbacks, mode === 'mta' ? 1 : 2) + assert.equal(s.mtaCallbacks, mode === 'early' ? 0 : s.callbacks) + assert.equal(s.callbackHresult, 0) + } + configure('mta') + const endpoint = await activateAudioInterfaceAsync(path, IAudioEndpointVolume) + assert.ok(endpoint instanceof IAudioEndpointVolume) + assert.equal(endpoint.getChannelCount(), 2) + endpoint.release() + await clean(1) + + for (const [mode, stage, hresult, created] of [ + ['start-failure', 'start', 0x80070005 | 0, 0], + ['early-start-failure', 'start', 0x80070005 | 0, 0], + ['start-null', 'start', undefined, 0], + ['outer-failure', 'result', 0x80004005 | 0, 0], + ['outer-failure-written', 'result', 0x80004005 | 0, 1], + ['inner-failure', 'activation', 0x80070005 | 0, 0], + ['inner-failure-written', 'activation', 0x80070005 | 0, 1], + ['null-result', 'result', undefined, 0], + ['projection-failure', 'projection', 0x80004002 | 0, 1], + ]) { + configure(mode) + await assert.rejects(activateAudioInterfaceAsync(path, IAudioClient), (error) => { + assert.equal(error.stage, stage, mode) + assert.equal(error.hresult, hresult, mode) + if (hresult !== undefined) { + assert.match(error.message, new RegExp(`0x${(hresult >>> 0).toString(16)}`, 'i')) + } else { + assert.match(error.message, /NULL/) + } + return true + }) + await clean(created) + assert.equal(stats().resultCalls, mode.startsWith('start') || mode === 'early-start-failure' ? 0 : 1) + } + + configure('mta') + for (const input of [path + '\0truncated', null, {}, 1]) { + await assert.rejects(activateAudioInterfaceAsync(input, IAudioClient), /string|NUL/) + } + class Unregistered extends IAudioClient {} + await assert.rejects(activateAudioInterfaceAsync(path, IAudioClient, {}), /custom activation parameters/) + await assert.rejects(activateAudioInterfaceAsync(path, Unregistered), /registered/) + await assert.rejects(activateAudioInterfaceAsync(path, { IID: IAudioClient.IID }), /registered/) + await assert.rejects(activateAudioInterfaceAsync(path, IMMDevice), /Unsupported.*target/) + await clean(0) + assert.equal(stats().startCalls, 0) + + const source = readFileSync( + join(generatedRoot, 'com', 'windows', 'win32', 'media', 'audio', 'ActivateAudioInterfaceAsync.js'), + 'utf8', + ) + const descriptor = JSON.parse(JSON.parse(source.match(/const descriptor = (.+);/)[1])) + for (const mutate of [ + (d) => { + d.has_this = true + }, + (d) => { + d.library = 'other.dll' + }, + (d) => { + d.export = 'other' + }, + (d) => { + d.calling_convention = 'cdecl' + }, + (d) => { + d.start_parameters.pop() + }, + (d) => { + d.start_parameters[2] = 'arbitrary-pointer' + }, + (d) => { + d.handler.slot = 4 + }, + (d) => { + d.handler.iid = IAudioClient.IID.toString() + }, + (d) => { + d.result.slot = 4 + }, + (d) => { + d.result.outputs = ['hresult', 'required-owned-interface'] + }, + (d) => { + d.allowed_targets.push(IMMDevice.IID.toString()) + }, + (d) => { + d.allocator = 'some-release' + }, + ]) { + const changed = structuredClone(descriptor) + mutate(changed) + assert.throws( + () => native.DynComAsync.activateAudioInterface(JSON.stringify(changed), path, IAudioClient.IID), + /descriptor|contract/i, + ) + } + assert.equal(stats().startCalls, 0) +} else if (scenario === 'bounds') { + native.initializeCom(1) + configure('held') + const promises = Array.from({ length: 256 }, () => activateAudioInterfaceAsync(path, IAudioClient)) + await assert.rejects(activateAudioInterfaceAsync(path, IAudioClient), /limit.*256/) + assert.equal(stats().pending, 256) + native.comCompletionTestRelease() + const values = await Promise.all(promises) + for (const value of values) value.release() + await clean(256) + assert.equal(stats().resultCalls, 256) +} else if (scenario === 'liveness') { + native.initializeCom(0) + configure('mta') + // No timer/worker/explicit event-loop keeper and no retained Promise. + void activateAudioInterfaceAsync(path, IAudioClient).then((value) => { + value.release() + assert.equal(stats().resultCalls, 1) + console.log(`native-completion:${scenario}:ok`) + }) +} else if (scenario === 'stale-token') { + native.initializeCom(0) + configure('early') + void activateAudioInterfaceAsync(path, IAudioClient) + assert.equal(stats().pending, 1) + native.comCompletionTestCloseOwner() + assert.equal(stats().pending, 0) + assert.equal(stats().resultCalls, 0) + // A new owner record in the same env must not receive the abandoned token. + const value = await activateAudioInterfaceAsync(path, IAudioClient) + value.release() + await clean(1) + assert.equal(stats().startCalls, 2) + assert.equal(stats().resultCalls, 1) +} else if (scenario.startsWith('teardown-')) { + native.initializeCom(1) + const worker = new Worker(new URL('./native-completion-worker.mjs', import.meta.url), { + workerData: { runtimePath, generatedRoot, scenario }, + }) + await new Promise((resolve, reject) => { + worker.once('message', resolve) + worker.once('error', reject) + }) + if (scenario === 'teardown-inflight') { + await until(() => stats().callbackEntered) + } + await worker.terminate() + const collectedBeforeCleanup = stats().resultCalls + // Node may drain an already-queued callback on its still-valid owner + // apartment before running cleanup hooks. Late callbacks must not collect. + if (scenario === 'teardown-queued') assert.ok(collectedBeforeCleanup <= 1) + else assert.equal(collectedBeforeCleanup, 0) + native.comCompletionTestRelease() + await until(() => stats().operationCreated === stats().operationDropped && stats().signalsLive === 0) + const s = stats() + assert.equal(s.callbacks, 1) + assert.equal(s.mtaCallbacks, 1) + assert.equal(s.callbackErrors, 0) + assert.equal(s.callbackHresult, 0) + assert.equal(s.resultCreated, collectedBeforeCleanup) + assert.equal(s.resultDropped, collectedBeforeCleanup) + assert.equal(s.resultCalls, collectedBeforeCleanup) + assert.equal(s.wrongThread, 0) + assert.equal(s.marshalingErrors, 0) +} else { + throw new Error(`Unknown scenario ${scenario}`) +} + +if (scenario !== 'liveness') console.log(`native-completion:${scenario}:ok`) diff --git a/bindings/js/__test__/native-completion-unload-child.mjs b/bindings/js/__test__/native-completion-unload-child.mjs new file mode 100644 index 00000000..53fd9673 --- /dev/null +++ b/bindings/js/__test__/native-completion-unload-child.mjs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { Worker } from 'node:worker_threads' + +const runtimePath = process.env.DYNWINRT_COMPLETION_RUNTIME +const worker = new Worker(new URL('./native-completion-worker.mjs', import.meta.url), { + workerData: { + runtimePath, + generatedRoot: process.env.DYNWINRT_COMPLETION_GENERATED, + scenario: 'teardown-unload', + }, +}) +await new Promise((resolve, reject) => { + worker.once('message', resolve) + worker.once('error', reject) +}) +await worker.terminate() + +// No environment holds the addon between worker teardown and this require. +// The native callback code and its OS-owned reference must still be valid. +const native = createRequire(import.meta.url)(runtimePath) +native.initializeCom(1) +assert.equal(native.comCompletionTestStats().operationCreated, 1) +assert.equal(native.comCompletionTestStats().operationDropped, 0) +assert.equal(native.comCompletionTestStats().resultCalls, 0) +native.comCompletionTestRelease() +const deadline = Date.now() + 10_000 +while (native.comCompletionTestStats().signalsLive !== 0) { + assert.ok(Date.now() < deadline) + await new Promise((resolve) => setTimeout(resolve, 2)) +} +const stats = native.comCompletionTestStats() +assert.equal(stats.operationDropped, 1) +assert.equal(stats.callbacks, 1) +assert.equal(stats.mtaCallbacks, 1) +assert.equal(stats.resultCalls, 0) +assert.equal(stats.callbackErrors, 0) +assert.equal(stats.marshalingErrors, 0) +assert.equal(stats.wrongThread, 0) +console.log('native-completion:teardown-unload:ok') diff --git a/bindings/js/__test__/native-completion-worker.mjs b/bindings/js/__test__/native-completion-worker.mjs new file mode 100644 index 00000000..3edd3a7d --- /dev/null +++ b/bindings/js/__test__/native-completion-worker.mjs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { parentPort, workerData } from 'node:worker_threads' + +const require = createRequire(import.meta.url) +const { runtimePath, generatedRoot, scenario } = workerData +const native = require(runtimePath) +const { activateAudioInterfaceAsync, IAudioClient } = require(join(generatedRoot, 'com', 'index.js')) +native.initializeCom(0) +native.comCompletionTestConfigure( + scenario === 'teardown-held' || scenario === 'teardown-unload' + ? 'held' + : scenario === 'teardown-inflight' + ? 'pause-input' + : 'mta', +) +void activateAudioInterfaceAsync('dynwinrt-test-render', IAudioClient) +if (scenario === 'teardown-queued') { + const deadline = Date.now() + 10_000 + while (native.comCompletionTestStats().callbacks === 0) { + if (Date.now() > deadline) throw new Error('Native completion did not arrive') + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1) + } +} +parentPort.postMessage('ready') +// Keep the owner from processing the queued completion until termination. +Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0) diff --git a/bindings/js/__test__/native-completion.e2e.ts b/bindings/js/__test__/native-completion.e2e.ts new file mode 100644 index 00000000..3a8dddb6 --- /dev/null +++ b/bindings/js/__test__/native-completion.e2e.ts @@ -0,0 +1,137 @@ +// 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-native-completion') +const runtimePath = join(packageRoot, 'dist', 'index.js') +const runner = join(packageRoot, '__test__', 'native-completion-child.mjs') + +test.before((t) => { + const winmd = process.env.DYNWINRT_WIN32_WINMD + t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required for exact native-completion generation') + rmSync(output, { recursive: true, force: true }) + const args = [ + 'run', + '--quiet', + '-p', + 'dynwinrt-codegen', + '--', + 'generate', + '--winmd', + winmd!, + '--class-name', + 'Windows.Win32.Media.Audio.ActivateAudioInterfaceAsync,Windows.Win32.Media.Audio.IMMDevice', + '--output', + output, + ] + const dryRun = spawnSync('cargo', [...args, '--dry-run'], { + cwd: repositoryRoot, + encoding: 'utf8', + windowsHide: true, + }) + t.is(dryRun.status, 0, dryRun.stderr) + t.regex(dryRun.stdout, /Would generate ActivateAudioInterfaceAsync/) + const generation = spawnSync('cargo', args, { + cwd: repositoryRoot, + encoding: 'utf8', + windowsHide: true, + }) + t.is(generation.status, 0, generation.stderr) + if (process.env.DYNWINRT_TEST_AUDIO_RENDER === '1') { + const renderDevice = spawnSync( + 'cargo', + [ + 'run', + '--quiet', + '-p', + 'dynwinrt-codegen', + '--', + 'generate', + '--namespace', + 'Windows.Media.Devices', + '--class-name', + 'MediaDevice', + '--output', + output, + ], + { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true }, + ) + t.is(renderDevice.status, 0, renderDevice.stderr) + } + const scope = join(output, 'node_modules', '@microsoft') + mkdirSync(scope, { recursive: true }) + symlinkSync(packageRoot, join(scope, 'dynwinrt'), 'junction') + writeFileSync( + join(output, 'completion-types.mts'), + [ + "import { activateAudioInterfaceAsync, IAudioClient, IAudioEndpointVolume } from './com/index.js'", + "const client: Promise = activateAudioInterfaceAsync('render', IAudioClient)", + "const endpoint: Promise = activateAudioInterfaceAsync('render', IAudioEndpointVolume)", + 'void client; void endpoint', + '// @ts-expect-error No PROPVARIANT input in the safe subset.', + "activateAudioInterfaceAsync('render', IAudioClient, {})", + ].join('\n'), + ) + const types = spawnSync( + process.execPath, + [ + join(packageRoot, 'node_modules', 'typescript', 'bin', 'tsc'), + '--noEmit', + '--strict', + '--target', + 'ESNext', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + join(output, 'completion-types.mts'), + ], + { cwd: packageRoot, encoding: 'utf8', windowsHide: true }, + ) + t.is(types.status, 0, `${types.stdout}\n${types.stderr}`) +}) + +const scenarios = [ + 'uninitialized', + 'sta', + 'mta', + 'bounds', + 'liveness', + 'stale-token', + 'teardown-held', + 'teardown-inflight', + 'teardown-queued', + 'teardown-unload', +] +if (process.env.DYNWINRT_TEST_AUDIO_RENDER === '1') scenarios.push('render-smoke') + +for (const scenario of scenarios) { + test.serial(`native completion: ${scenario}`, (t) => { + const child = + scenario === 'teardown-unload' ? join(packageRoot, '__test__', 'native-completion-unload-child.mjs') : runner + const result = spawnSync(process.execPath, [child, scenario], { + cwd: packageRoot, + encoding: 'utf8', + timeout: 40_000, + windowsHide: true, + env: { + ...process.env, + DYNWINRT_COMPLETION_RUNTIME: runtimePath, + DYNWINRT_COMPLETION_GENERATED: output, + }, + }) + t.is(result.status, 0, `${result.error ?? ''}\n${result.stdout}\n${result.stderr}`) + t.regex(result.stdout, new RegExp(`native-completion:${scenario}:ok`)) + }) +} + +test.after.always(() => { + rmSync(output, { recursive: true, force: true }) + rmSync(join(packageRoot, '.target-generated-native-completion.dynwinrt-lock'), { force: true }) +}) diff --git a/bindings/js/package.json b/bindings/js/package.json index ec793dfd..b3d0aff1 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -92,6 +92,8 @@ "lint": "oxlint", "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/runtime/com-projection.cjs b/bindings/js/runtime/com-projection.cjs index 189f8942..f6ed88cd 100644 --- a/bindings/js/runtime/com-projection.cjs +++ b/bindings/js/runtime/com-projection.cjs @@ -47,4 +47,17 @@ function projectAs(value, type) { } } -module.exports = { projectAs, registerProjection, projectionIid } +async function activateAudioInterfaceAsync(descriptor, deviceInterfacePath, type) { + const iid = projectionIid(type) + if (typeof deviceInterfacePath !== 'string' || deviceInterfacePath.includes('\0')) { + throw new TypeError('A device interface path must be a string without embedded NUL') + } + const owned = await native.DynComAsync.activateAudioInterface(descriptor, deviceInterfacePath, iid) + try { + return projectAs(owned, type) + } finally { + owned.release() + } +} + +module.exports = { projectAs, registerProjection, projectionIid, activateAudioInterfaceAsync } diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index 816a6154..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', @@ -265,6 +266,7 @@ function writeFacade( ...(name === 'com' ? [] : [ 'module.exports.__registerComProjection = projection.registerProjection', 'module.exports.__comProjectionIid = projection.projectionIid', + 'module.exports.__activateAudioInterfaceAsync = projection.activateAudioInterfaceAsync', ]), ] : []), '', @@ -279,6 +281,7 @@ function writeFacade( ...(name === 'com' ? [] : [ "export declare function __registerComProjection(type: ComInterfaceType, iid: import('./index.js').WinGuid): void", "export declare function __comProjectionIid(type: ComInterfaceType): import('./index.js').WinGuid", + 'export declare function __activateAudioInterfaceAsync(descriptor: string, deviceInterfacePath: string, type: ComInterfaceType): Promise', ]), ] : []), '', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index debc22c3..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 { @@ -755,6 +759,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 +808,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 +1246,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 +1262,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) } } @@ -1435,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( @@ -1927,6 +2033,7 @@ fn optional_com_object( ) -> napi::Result> { value .map(|value| { + value.admit_com_input()?; value .0 .as_object() @@ -2019,6 +2126,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,15 +2455,73 @@ 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 receiver_guard = ComInputGuard::pin(&[obj])?; + let view = obj + .0 + .as_object() + .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()?; + let view = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM invocation requires a live object"))? + .clone(); + 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() + .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()?; - let raw = obj + obj.ensure_tracked_com_idle()?; + 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())) } @@ -2367,20 +2538,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 +2552,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,31 +2562,39 @@ impl DynComMethodHandle { args: Vec<&DynWinRTValue>, ) -> napi::Result { obj.ensure_com_apartment()?; - let raw = obj + obj.ensure_tracked_com_idle()?; + 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()), + }) }) } } @@ -2471,24 +2627,31 @@ impl DynComRaw { ) -> napi::Result> { dispatch.entered.set(false); obj.ensure_com_apartment()?; - let raw = obj + obj.ensure_tracked_com_idle()?; + 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() + }) }) } } @@ -2701,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() @@ -2718,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); } @@ -2926,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(()) } } @@ -2935,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, } } @@ -2951,6 +3129,7 @@ impl DynComDispatchParams { "Apartment-bound DISPPARAMS used from a different thread", )); } + self.inputs.ensure_idle()?; self .value .as_ref() @@ -3029,6 +3208,7 @@ impl DynComDispatchParams { )); } self.value = None; + self.inputs = super::com_input::InputBindings::deferred(); Ok(()) } } @@ -3714,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() @@ -3764,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); } @@ -3924,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| { @@ -3940,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| { @@ -3980,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| { @@ -4157,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(()) } } @@ -5362,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| { @@ -5598,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) } @@ -5626,6 +5828,7 @@ impl DynCom { #[napi] pub fn take_variant_array(value: &mut DynWinRTValue) -> napi::Result> { + value.admit_com_input()?; value .4 .take() @@ -5909,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_borrowed.rs b/bindings/js/src/com_borrowed.rs new file mode 100644 index 00000000..3fc58f0f --- /dev/null +++ b/bindings/js/src/com_borrowed.rs @@ -0,0 +1,305 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt::com::borrowed::{contracts, BorrowedCopyContract, BorrowedCopyPlan, ContextEffect}; +use napi::bindgen_prelude::{BigInt, Buffer, Unknown}; +use napi_derive::napi; +use serde::Deserialize; + +use super::{com, DynWinRTValue, TABLE}; + +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 = 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 != contracts::METADATA_SHA256 + || value.fingerprint != evidence.fingerprint + { + return Err(invalid("Audio context evidence drift; regenerate bindings")); + } + Ok(effect) +} + +fn parse_contract(value: &str) -> napi::Result { + BorrowedCopyContract::parse(value).map_err(invalid) +} + +#[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/com_completion.rs b/bindings/js/src/com_completion.rs new file mode 100644 index 00000000..fc715ce0 --- /dev/null +++ b/bindings/js/src/com_completion.rs @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ + cell::RefCell, + collections::HashMap, + ptr, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, +}; + +use dynwinrt::com::completion::{ + CompletionError, CompletionSignal, NativeSignalSink, OneShotContract, OneShotPlan, + OwnerOperation, ResultArgument, StartArgument, +}; +use napi::{ + bindgen_prelude::{FromNapiValue, PromiseRaw, ToNapiValue}, + sys, Env, JsError, Status, +}; +use napi_derive::napi; +use serde::Deserialize; +use windows::core::GUID; + +use super::{managed_tsfn::ManagedTsfn, DynWinRTValue, WinGUID}; + +const MAX_PENDING: usize = 256; +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +// These maps contain COM pointers and napi_deferred, and are NEVER shared with +// workers. Tokens are process-unique, so a recycled napi_env cannot revive one. +thread_local! { + static OWNERS: RefCell>> = + RefCell::new(HashMap::new()); +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Descriptor { + version: u32, + kind: String, + library: String, + export: String, + calling_convention: String, + has_this: bool, + start_parameters: Vec, + handler: HandlerDescriptor, + result: ResultDescriptor, + allowed_targets: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case")] +enum StartParameter { + Utf16Path, + RefIid, + NullPropVariant, + NativeSignal, + OwnedOperation, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct HandlerDescriptor { + iid: String, + root: String, + slot: usize, + input: String, + return_type: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResultDescriptor { + iid: String, + root: String, + slot: usize, + outputs: Vec, + return_type: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case")] +enum ResultParameter { + Hresult, + NullableOwnedInterface, +} + +fn parse_contract(descriptor: &str) -> napi::Result { + let descriptor: Descriptor = serde_json::from_str(descriptor).map_err(|error| { + napi::Error::from_reason(format!("Invalid native completion descriptor: {error}")) + })?; + if descriptor.version != 1 + || descriptor.kind != "audio-activation" + || descriptor.calling_convention != "system" + || descriptor.has_this + || descriptor.handler.root != "IUnknown" + || descriptor.handler.input != "borrowed-operation" + || descriptor.handler.return_type != "hresult" + || descriptor.result.root != "IUnknown" + || descriptor.result.return_type != "hresult" + { + return Err(napi::Error::from_reason( + "Unsupported native completion descriptor", + )); + } + fn guid(text: &str) -> napi::Result { + GUID::try_from(text).map_err(|_| napi::Error::from_reason("Invalid native completion IID")) + } + Ok(OneShotContract { + library: descriptor.library, + export: descriptor.export, + start_arguments: descriptor + .start_parameters + .into_iter() + .map(|parameter| match parameter { + StartParameter::Utf16Path => StartArgument::Utf16Path, + StartParameter::RefIid => StartArgument::RefIid, + StartParameter::NullPropVariant => StartArgument::NullPropVariant, + StartParameter::NativeSignal => StartArgument::NativeSignal, + StartParameter::OwnedOperation => StartArgument::OwnedOperation, + }) + .collect(), + handler_iid: guid(&descriptor.handler.iid)?, + handler_slot: descriptor.handler.slot, + operation_iid: guid(&descriptor.result.iid)?, + result_slot: descriptor.result.slot, + result_arguments: descriptor + .result + .outputs + .into_iter() + .map(|parameter| match parameter { + ResultParameter::Hresult => ResultArgument::HResult, + ResultParameter::NullableOwnedInterface => ResultArgument::NullableOwnedInterface, + }) + .collect(), + allowed_targets: descriptor + .allowed_targets + .iter() + .map(|iid| guid(iid)) + .collect::>()?, + }) +} + +struct PendingCompletion { + deferred: sys::napi_deferred, + signal: Arc, + operation: OwnerOperation, + _handler: NativeSignalSink, + plan: OneShotPlan, + target: GUID, +} + +enum OwnerRecord { + Starting, + Pending(Box), +} + +struct StartReservation { + env: usize, + token: u64, + armed: bool, +} + +impl StartReservation { + fn reserve(env: Env, token: u64) -> napi::Result { + let key = env.raw() as usize; + OWNERS.with(|owners| { + let mut owners = owners.borrow_mut(); + let pending = owners + .get_mut(&key) + .ok_or_else(|| napi::Error::from_reason("Native COM completion environment is closing"))?; + if pending.len() >= MAX_PENDING { + return Err(napi::Error::from_reason( + "Native COM completion limit (256) reached", + )); + } + pending.insert(token, OwnerRecord::Starting); + Ok(Self { + env: key, + token, + armed: true, + }) + }) + } + + fn publish(mut self, pending: PendingCompletion) -> napi::Result<()> { + let mut pending = Some(pending); + let published = OWNERS.with(|owners| { + let mut owners = owners.borrow_mut(); + if let Some(record @ OwnerRecord::Starting) = owners + .get_mut(&self.env) + .and_then(|records| records.get_mut(&self.token)) + { + *record = OwnerRecord::Pending(Box::new(pending.take().expect("unpublished completion"))); + true + } else { + false + } + }); + if !published { + return Err(napi::Error::from_reason( + "Native COM completion environment closed during start", + )); + } + self.armed = false; + Ok(()) + } +} + +impl Drop for StartReservation { + fn drop(&mut self) { + if self.armed { + OWNERS.with(|owners| { + if let Some(records) = owners.borrow_mut().get_mut(&self.env) { + records.remove(&self.token); + } + }); + } + } +} + +impl Drop for PendingCompletion { + fn drop(&mut self) { + self.signal.close(); + } +} + +fn ensure_owner_environment(env: Env) -> napi::Result<()> { + let key = env.raw() as usize; + if OWNERS.with(|owners| owners.borrow().contains_key(&key)) { + return Ok(()); + } + env.add_env_cleanup_hook(key, |key| { + close_owner_environment(key); + })?; + OWNERS.with(|owners| owners.borrow_mut().insert(key, HashMap::new())); + Ok(()) +} + +fn close_owner_environment(key: usize) { + let pending = OWNERS.with(|owners| owners.borrow_mut().remove(&key)); + // Close all signals before any owner references are released. Windows may + // still hold the handler; this does not cancel the native operation. + if let Some(pending) = pending { + for record in pending.values() { + if let OwnerRecord::Pending(record) = record { + record.signal.close(); + } + } + drop(pending); + } +} + +fn take_pending(env: sys::napi_env, token: u64) -> Option { + let record = OWNERS.with(|owners| { + owners + .borrow_mut() + .get_mut(&(env as usize)) + .and_then(|pending| pending.remove(&token)) + }); + match record { + Some(OwnerRecord::Pending(record)) => Some(*record), + Some(OwnerRecord::Starting) | None => None, + } +} + +fn status(context: &str, result: sys::napi_status) -> napi::Result<()> { + if result == sys::Status::napi_ok { + Ok(()) + } else { + Err(napi::Error::from_reason(format!( + "{context}: {}", + Status::from(result) + ))) + } +} + +fn reject( + env: sys::napi_env, + deferred: sys::napi_deferred, + error: CompletionError, +) -> napi::Result<()> { + let value = unsafe { JsError::from(napi::Error::from_reason(error.message)).into_value(env) }; + let stage = unsafe { String::to_napi_value(env, error.stage.to_owned()) }?; + status("Set native completion stage", unsafe { + sys::napi_set_named_property(env, value, c"stage".as_ptr(), stage) + })?; + if let Some(hr) = error.hresult { + let hr = unsafe { i32::to_napi_value(env, hr.0) }?; + status("Set native completion HRESULT", unsafe { + sys::napi_set_named_property(env, value, c"hresult".as_ptr(), hr) + })?; + } + status("Reject native completion", unsafe { + sys::napi_reject_deferred(env, deferred, value) + }) +} + +fn dispatch(token: u64, env: sys::napi_env) -> napi::Result<()> { + let Some(pending) = take_pending(env, token) else { + return Ok(()); + }; + pending.signal.close(); + let result = pending + .plan + .collect(&pending.operation, pending.target) + .and_then(|object| { + // napi-rs class construction can fail during worker termination before + // installing its native finalizer. Keep the owned COM result in Rust + // until an empty, finalizer-backed JS value has actually been created. + let value = unsafe { + DynWinRTValue::to_napi_value(env, DynWinRTValue::new(dynwinrt::WinRTValue::Null)) + } + .map_err(|error| CompletionError::contract("projection", error.to_string()))?; + let wrapped = unsafe { <&mut DynWinRTValue>::from_napi_value(env, value) } + .map_err(|error| CompletionError::contract("projection", error.to_string()))?; + wrapped.0 = dynwinrt::WinRTValue::Object(object); + wrapped + .bind_current_com_apartment() + .map_err(|error| CompletionError::contract("projection", error.to_string()))?; + Ok(value) + }); + match result { + Ok(value) => status("Resolve native completion", unsafe { + sys::napi_resolve_deferred(env, pending.deferred, value) + }), + Err(error) => reject(env, pending.deferred, error), + } +} + +fn finalized(token: u64, env: sys::napi_env) { + if env.is_null() { + return; + } + if let Some(pending) = take_pending(env, token) { + let error = CompletionError::contract( + "dispatch", + "Native completion dispatcher closed before delivery", + ); + if let Err(error) = reject(env, pending.deferred, error) { + eprintln!("[dynwinrt] native completion finalization failed: {error}"); + } + } +} + +pub(crate) fn start_with_plan<'env>( + env: Env, + plan: OneShotPlan, + path: &str, + target: GUID, +) -> napi::Result> { + ensure_owner_environment(env)?; + let token = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); + // Reserve before entering COM, which can reenter the caller's apartment. + let reservation = StartReservation::reserve(env, token)?; + let mut deferred = ptr::null_mut(); + let mut promise = ptr::null_mut(); + status("Create native completion promise", unsafe { + sys::napi_create_promise(env.raw(), &mut deferred, &mut promise) + })?; + let tsfn = ManagedTsfn::create_native_dispatch( + env.raw(), + dispatch, + Some(Box::new(move |env| finalized(token, env))), + )?; + let signal = CompletionSignal::new(move || { + let result = tsfn.call(token); + if result != Status::Ok && result != Status::Closing { + // Releasing this last handle schedules owner-side finalization, which + // rejects any still-pending deferred rather than leaking a live TSFN. + eprintln!("[dynwinrt] native completion enqueue failed: {result}"); + } + }); + #[cfg(feature = "test-hooks")] + super::com_completion_test_hooks::observe_signal(Arc::downgrade(&signal)); + let started = plan.create_signal_sink(signal.clone()).and_then(|handler| { + plan + .start(path, target, &handler) + .map(|operation| (handler, operation)) + }); + match started { + Ok((handler, operation)) => { + reservation.publish(PendingCompletion { + deferred, + signal: signal.clone(), + operation, + _handler: handler, + plan, + target, + })?; + signal.publish(); + } + Err(error) => { + signal.close(); + reject(env.raw(), deferred, error)?; + } + } + Ok(PromiseRaw::new(env.raw(), promise)) +} + +#[napi] +pub struct DynComAsync; + +#[napi] +impl DynComAsync { + #[napi] + pub fn activate_audio_interface<'env>( + env: Env, + descriptor: String, + path: String, + target: &WinGUID, + ) -> napi::Result> { + let contract = parse_contract(&descriptor)?; + #[cfg(feature = "test-hooks")] + let plan = super::com_completion_test_hooks::prepare_plan(contract) + .map_err(|error| napi::Error::from_reason(error.to_string()))?; + #[cfg(not(feature = "test-hooks"))] + let plan = OneShotPlan::prepare(contract) + .map_err(|error| napi::Error::from_reason(error.to_string()))?; + start_with_plan(env, plan, &path, target.0) + } +} + +#[cfg(feature = "test-hooks")] +pub(crate) fn pending_count(env: Env) -> usize { + OWNERS.with(|owners| { + owners + .borrow() + .get(&(env.raw() as usize)) + .map_or(0, HashMap::len) + }) +} + +#[cfg(feature = "test-hooks")] +#[napi] +pub fn com_completion_test_close_owner(env: Env) { + close_owner_environment(env.raw() as usize); +} diff --git a/bindings/js/src/com_completion_test_hooks.rs b/bindings/js/src/com_completion_test_hooks.rs new file mode 100644 index 00000000..a1285d2b --- /dev/null +++ b/bindings/js/src/com_completion_test_hooks.rs @@ -0,0 +1,737 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! ABI-correct fake export. Cross-apartment delivery uses RoGetAgileReference +//! through windows-core's marshaling wrapper, never Send COM pointers. + +use dynwinrt::com::completion::{CompletionError, CompletionSignal, OneShotContract, OneShotPlan}; +use napi::Env; +use napi_derive::napi; +use std::{ + cell::RefCell, + ffi::c_void, + ptr, + sync::{ + atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}, + Arc, LazyLock, Mutex, Weak, + }, + thread, + time::{Duration, Instant}, +}; +use windows::{ + core::{AgileReference, IUnknown, IUnknown_Vtbl, Interface as _, BOOL, GUID, HRESULT}, + Win32::{ + Foundation::HANDLE, + Media::Audio::{ + Endpoints::{IAudioEndpointVolume, IAudioEndpointVolume_Vtbl}, + IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceAsyncOperation_Vtbl, + IActivateAudioInterfaceCompletionHandler, IAudioClient, IAudioClient_Vtbl, AUDCLNT_SHAREMODE, + WAVEFORMATEX, + }, + System::{ + Com::StructuredStorage::PROPVARIANT, + Com::{CoCreateFreeThreadedMarshaler, CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED}, + Threading::GetCurrentThreadId, + }, + }, +}; + +const E_FAIL: HRESULT = HRESULT(0x80004005u32 as i32); +const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); +const E_NOINTERFACE: HRESULT = HRESULT(0x80004002u32 as i32); +const E_NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); +const E_ACCESSDENIED: HRESULT = HRESULT(0x80070005u32 as i32); +const E_WRONG_THREAD: HRESULT = HRESULT(0x8001010eu32 as i32); +const IID_AGILE: GUID = GUID::from_u128(0x94ea2b94_e9cc_49e0_c0ff_ee64ca8f5b90); +const IID_MARSHAL: GUID = GUID::from_u128(0x00000003_0000_0000_c000_000000000046); + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Mta, + Early, + Duplicate, + StartFailure, + EarlyStartFailure, + StartNull, + OuterFailure, + OuterFailureWritten, + InnerFailure, + InnerFailureWritten, + NullResult, + ProjectionFailure, + Held, + PauseInput, +} + +#[derive(Default)] +struct Stats { + start_calls: AtomicU32, + validated_arguments: AtomicU32, + signal_qi_checks: AtomicU32, + operation_created: AtomicU32, + operation_dropped: AtomicU32, + result_calls: AtomicU32, + result_created: AtomicU32, + result_dropped: AtomicU32, + wrong_thread: AtomicU32, + callbacks: AtomicU32, + mta_callbacks: AtomicU32, + callback_errors: AtomicU32, + callback_hresult: AtomicI32, + marshaling_errors: AtomicU32, + callback_entered: AtomicBool, + release_input: AtomicBool, + inside_callback: AtomicBool, + signals: Mutex>>, +} + +thread_local! { + static CONFIG: RefCell)>> = const { RefCell::new(None) }; +} +static LAST_STATS: LazyLock>> = + LazyLock::new(|| Mutex::new(Arc::new(Stats::default()))); +static HELD: LazyLock>> = LazyLock::new(|| Mutex::new(Vec::new())); + +pub(crate) fn prepare_plan(contract: OneShotContract) -> Result { + if CONFIG.with(|config| config.borrow().is_some()) { + unsafe { OneShotPlan::with_test_export(contract, fake_start as *const () as *mut c_void) } + } else { + OneShotPlan::prepare(contract) + } +} + +pub(crate) fn observe_signal(signal: Weak) { + CONFIG.with(|config| { + if let Some((_, stats)) = &*config.borrow() { + stats.signals.lock().unwrap().push(signal); + } + }); +} + +#[napi] +pub fn com_completion_test_configure(mode: Option) -> napi::Result<()> { + let Some(mode) = mode else { + CONFIG.with(|config| config.borrow_mut().take()); + return Ok(()); + }; + let mode = match mode.as_str() { + "mta" => Mode::Mta, + "early" => Mode::Early, + "duplicate" => Mode::Duplicate, + "start-failure" => Mode::StartFailure, + "early-start-failure" => Mode::EarlyStartFailure, + "start-null" => Mode::StartNull, + "outer-failure" => Mode::OuterFailure, + "outer-failure-written" => Mode::OuterFailureWritten, + "inner-failure" => Mode::InnerFailure, + "inner-failure-written" => Mode::InnerFailureWritten, + "null-result" => Mode::NullResult, + "projection-failure" => Mode::ProjectionFailure, + "held" => Mode::Held, + "pause-input" => Mode::PauseInput, + _ => { + return Err(napi::Error::from_reason( + "Unknown native completion fake mode", + )) + } + }; + let stats = Arc::new(Stats::default()); + *LAST_STATS.lock().unwrap() = stats.clone(); + CONFIG.with(|config| *config.borrow_mut() = Some((mode, stats))); + Ok(()) +} + +#[napi(object)] +pub struct ComCompletionTestStats { + pub start_calls: u32, + pub validated_arguments: u32, + pub signal_qi_checks: u32, + pub operation_created: u32, + pub operation_dropped: u32, + pub result_calls: u32, + pub result_created: u32, + pub result_dropped: u32, + pub wrong_thread: u32, + pub callbacks: u32, + pub mta_callbacks: u32, + pub callback_errors: u32, + pub callback_hresult: i32, + pub marshaling_errors: u32, + pub callback_entered: bool, + pub signals_live: u32, + pub pending: u32, +} + +#[napi] +pub fn com_completion_test_stats(env: Env) -> ComCompletionTestStats { + let stats = LAST_STATS.lock().unwrap().clone(); + let signals_live = stats + .signals + .lock() + .unwrap() + .iter() + .filter(|signal| signal.strong_count() != 0) + .count() as u32; + ComCompletionTestStats { + start_calls: stats.start_calls.load(Ordering::SeqCst), + validated_arguments: stats.validated_arguments.load(Ordering::SeqCst), + signal_qi_checks: stats.signal_qi_checks.load(Ordering::SeqCst), + operation_created: stats.operation_created.load(Ordering::SeqCst), + operation_dropped: stats.operation_dropped.load(Ordering::SeqCst), + result_calls: stats.result_calls.load(Ordering::SeqCst), + result_created: stats.result_created.load(Ordering::SeqCst), + result_dropped: stats.result_dropped.load(Ordering::SeqCst), + wrong_thread: stats.wrong_thread.load(Ordering::SeqCst), + callbacks: stats.callbacks.load(Ordering::SeqCst), + mta_callbacks: stats.mta_callbacks.load(Ordering::SeqCst), + callback_errors: stats.callback_errors.load(Ordering::SeqCst), + callback_hresult: stats.callback_hresult.load(Ordering::SeqCst), + marshaling_errors: stats.marshaling_errors.load(Ordering::SeqCst), + callback_entered: stats.callback_entered.load(Ordering::SeqCst), + signals_live, + pending: super::com_completion::pending_count(env) as u32, + } +} + +#[napi] +pub fn com_completion_test_release() { + LAST_STATS + .lock() + .unwrap() + .release_input + .store(true, Ordering::SeqCst); + let jobs = std::mem::take(&mut *HELD.lock().unwrap()); + if !jobs.is_empty() { + spawn_jobs(jobs); + } +} + +fn query(object: &IUnknown, iid: &GUID) -> windows::core::Result { + let mut value = ptr::null_mut(); + let hr = unsafe { object.query(iid, &mut value) }; + if hr.is_err() { + if !value.is_null() { + drop(unsafe { IUnknown::from_raw(value) }); + } + return Err(windows::core::Error::from_hresult(hr)); + } + if value.is_null() { + return Err(windows::core::Error::from_hresult(E_POINTER)); + } + Ok(unsafe { IUnknown::from_raw(value) }) +} + +fn probe_signal(handler: &IUnknown, stats: &Stats) -> windows::core::Result<()> { + let identity = query(handler, &IUnknown::IID)?; + for iid in [ + IActivateAudioInterfaceCompletionHandler::IID, + IID_AGILE, + IID_MARSHAL, + ] { + let view = query(handler, &iid)?; + let canonical = query(&view, &IUnknown::IID)?; + if canonical.as_raw() != identity.as_raw() { + return Err(windows::core::Error::from_hresult(E_FAIL)); + } + } + let mut unsupported = ptr::null_mut(); + let hr = unsafe { handler.query(&IAudioClient::IID, &mut unsupported) }; + if hr != E_NOINTERFACE || !unsupported.is_null() { + return Err(windows::core::Error::from_hresult(E_FAIL)); + } + let handler: IActivateAudioInterfaceCompletionHandler = handler.cast()?; + let null_hr = unsafe { (handler.vtable().ActivateCompleted)(handler.as_raw(), ptr::null_mut()) }; + if null_hr != E_POINTER { + return Err(windows::core::Error::from_hresult(E_FAIL)); + } + let wrong_interface = + unsafe { (handler.vtable().ActivateCompleted)(handler.as_raw(), handler.as_raw()) }; + if wrong_interface != E_NOINTERFACE { + return Err(windows::core::Error::from_hresult(E_FAIL)); + } + stats.signal_qi_checks.fetch_add(1, Ordering::SeqCst); + Ok(()) +} + +#[repr(C)] +struct FakeOperation { + vtable: *const IActivateAudioInterfaceAsyncOperation_Vtbl, + references: AtomicU32, + marshaler: Option, + _handler: AgileReference, + owner: u32, + target: GUID, + mode: Mode, + stats: Arc, +} + +impl Drop for FakeOperation { + fn drop(&mut self) { + self.stats.operation_dropped.fetch_add(1, Ordering::SeqCst); + } +} + +unsafe extern "system" fn operation_query( + this: *mut c_void, + iid: *const GUID, + output: *mut *mut c_void, +) -> HRESULT { + if output.is_null() { + return E_POINTER; + } + unsafe { + *output = ptr::null_mut(); + } + if iid.is_null() { + return E_POINTER; + } + let operation = unsafe { &*this.cast::() }; + let iid = unsafe { *iid }; + if iid == IID_MARSHAL { + return operation + .marshaler + .as_ref() + .map_or(E_NOINTERFACE, |marshaler| unsafe { + marshaler.query(&iid, output) + }); + } + if iid != IUnknown::IID && iid != IActivateAudioInterfaceAsyncOperation::IID && iid != IID_AGILE { + return E_NOINTERFACE; + } + if iid == IActivateAudioInterfaceAsyncOperation::IID + && operation.mode == Mode::PauseInput + && unsafe { GetCurrentThreadId() } != operation.owner + && operation.stats.inside_callback.load(Ordering::SeqCst) + { + operation + .stats + .callback_entered + .store(true, Ordering::SeqCst); + let deadline = Instant::now() + Duration::from_secs(30); + while !operation.stats.release_input.load(Ordering::SeqCst) && Instant::now() < deadline { + thread::sleep(Duration::from_millis(1)); + } + } + unsafe { + *output = this; + operation_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn operation_add_ref(this: *mut c_void) -> u32 { + unsafe { &*this.cast::() } + .references + .fetch_add(1, Ordering::SeqCst) + + 1 +} + +unsafe extern "system" fn operation_release(this: *mut c_void) -> u32 { + let count = unsafe { &*this.cast::() } + .references + .fetch_sub(1, Ordering::SeqCst) + - 1; + if count == 0 { + drop(unsafe { Box::from_raw(this.cast::()) }); + } + count +} + +unsafe extern "system" fn operation_result( + this: *mut c_void, + activation: *mut HRESULT, + output: *mut *mut c_void, +) -> HRESULT { + let operation = unsafe { &*this.cast::() }; + operation.stats.result_calls.fetch_add(1, Ordering::SeqCst); + if unsafe { GetCurrentThreadId() } != operation.owner { + operation.stats.wrong_thread.fetch_add(1, Ordering::SeqCst); + return E_WRONG_THREAD; + } + if activation.is_null() || output.is_null() || unsafe { !(*output).is_null() } { + return E_POINTER; + } + let inner_failure = matches!( + operation.mode, + Mode::InnerFailure | Mode::InnerFailureWritten + ); + unsafe { + *activation = if inner_failure { + E_ACCESSDENIED + } else { + HRESULT(0) + }; + } + if !matches!( + operation.mode, + Mode::InnerFailure | Mode::OuterFailure | Mode::NullResult + ) { + // Results are deliberately non-agile and are CREATED HERE on the owner + // apartment, not retained in the agile operation or MTA worker. + let value = new_result( + operation.target, + operation.owner, + operation.mode, + operation.stats.clone(), + ); + unsafe { + *output = value.into_raw(); + } + } + if matches!( + operation.mode, + Mode::OuterFailure | Mode::OuterFailureWritten + ) { + E_FAIL + } else { + HRESULT(0) + } +} + +static OPERATION_VTABLE: IActivateAudioInterfaceAsyncOperation_Vtbl = + IActivateAudioInterfaceAsyncOperation_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: operation_query, + AddRef: operation_add_ref, + Release: operation_release, + }, + GetActivateResult: operation_result, + }; + +fn new_operation( + handler: &IUnknown, + target: GUID, + mode: Mode, + stats: Arc, +) -> windows::core::Result { + let handler: IActivateAudioInterfaceCompletionHandler = handler.cast()?; + let handler = AgileReference::new(&handler)?; + let object = Box::new(FakeOperation { + vtable: &OPERATION_VTABLE, + references: AtomicU32::new(1), + marshaler: None, + _handler: handler, + owner: unsafe { GetCurrentThreadId() }, + target, + mode, + stats: stats.clone(), + }); + stats.operation_created.fetch_add(1, Ordering::SeqCst); + let raw = Box::into_raw(object); + let identity = unsafe { IUnknown::from_raw(raw.cast()) }; + let marshaler = unsafe { CoCreateFreeThreadedMarshaler(&identity)? }; + unsafe { + (*raw).marshaler = Some(marshaler); + } + Ok(identity) +} + +struct CallbackJob { + operation: AgileReference, + handler: AgileReference, + duplicate: bool, + stats: Arc, +} + +fn deliver( + handler: &IActivateAudioInterfaceCompletionHandler, + operation: &IActivateAudioInterfaceAsyncOperation, + stats: &Stats, + mta: bool, +) { + stats.callbacks.fetch_add(1, Ordering::SeqCst); + if mta { + stats.mta_callbacks.fetch_add(1, Ordering::SeqCst); + } + stats.inside_callback.store(true, Ordering::SeqCst); + let hr = unsafe { (handler.vtable().ActivateCompleted)(handler.as_raw(), operation.as_raw()) }; + stats.inside_callback.store(false, Ordering::SeqCst); + stats.callback_hresult.store(hr.0, Ordering::SeqCst); + if hr.is_err() { + stats.callback_errors.fetch_add(1, Ordering::SeqCst); + } +} + +fn spawn_jobs(jobs: Vec) { + thread::spawn(move || { + let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + if initialized.is_err() { + for job in &jobs { + job.stats.marshaling_errors.fetch_add(1, Ordering::SeqCst); + } + return; + } + for job in jobs { + let result = (|| -> windows::core::Result<()> { + let operation = job.operation.resolve()?; + let handler = job.handler.resolve()?; + deliver(&handler, &operation, &job.stats, true); + if job.duplicate { + deliver(&handler, &operation, &job.stats, true); + } + drop(handler); + drop(operation); + Ok(()) + })(); + if result.is_err() { + job.stats.marshaling_errors.fetch_add(1, Ordering::SeqCst); + } + } + unsafe { + CoUninitialize(); + } + }); +} + +unsafe extern "system" fn fake_start( + path: *const u16, + iid: *const GUID, + activation_params: *const PROPVARIANT, + handler: *mut c_void, + operation: *mut *mut c_void, +) -> HRESULT { + std::panic::catch_unwind(|| unsafe { + fake_start_inner(path, iid, activation_params, handler, operation) + }) + .unwrap_or(E_FAIL) +} + +unsafe fn fake_start_inner( + path: *const u16, + iid: *const GUID, + activation_params: *const PROPVARIANT, + handler: *mut c_void, + output: *mut *mut c_void, +) -> HRESULT { + let Some((mode, stats)) = CONFIG.with(|config| config.borrow().clone()) else { + return E_FAIL; + }; + stats.start_calls.fetch_add(1, Ordering::SeqCst); + if path.is_null() + || iid.is_null() + || !activation_params.is_null() + || handler.is_null() + || output.is_null() + || unsafe { !(*output).is_null() } + { + return E_POINTER; + } + let expected = "dynwinrt-test-render\0".encode_utf16().collect::>(); + for (index, expected) in expected.iter().enumerate() { + if unsafe { *path.add(index) } != *expected { + return E_FAIL; + } + } + let target = unsafe { *iid }; + if target != IAudioClient::IID && target != IAudioEndpointVolume::IID { + return E_NOINTERFACE; + } + stats.validated_arguments.fetch_add(1, Ordering::SeqCst); + let handler = unsafe { IUnknown::from_raw_borrowed(&handler) }.unwrap(); + let started = (|| -> windows::core::Result<()> { + probe_signal(handler, &stats)?; + if mode == Mode::StartNull { + return Ok(()); + } + let operation = new_operation(handler, target, mode, stats.clone())?; + unsafe { + *output = operation.clone().into_raw(); + } + let callback: IActivateAudioInterfaceCompletionHandler = handler.cast()?; + let operation_view: IActivateAudioInterfaceAsyncOperation = operation.cast()?; + if matches!(mode, Mode::Early | Mode::EarlyStartFailure) { + deliver(&callback, &operation_view, &stats, false); + deliver(&callback, &operation_view, &stats, false); + } else if mode != Mode::StartFailure { + let job = CallbackJob { + operation: AgileReference::new(&operation_view)?, + handler: AgileReference::new(&callback)?, + duplicate: mode == Mode::Duplicate, + stats: stats.clone(), + }; + if mode == Mode::Held { + HELD.lock().unwrap().push(job); + } else { + spawn_jobs(vec![job]); + } + } + Ok(()) + })(); + if let Err(error) = started { + stats.marshaling_errors.fetch_add(1, Ordering::SeqCst); + return error.code(); + } + if matches!(mode, Mode::StartFailure | Mode::EarlyStartFailure) { + E_ACCESSDENIED + } else { + HRESULT(0) + } +} + +#[repr(C)] +struct FakeResult { + vtable: *const c_void, + references: AtomicU32, + target: GUID, + owner: u32, + supports_target: bool, + stats: Arc, +} + +fn result_owner(value: &FakeResult) -> bool { + if unsafe { GetCurrentThreadId() } == value.owner { + true + } else { + value.stats.wrong_thread.fetch_add(1, Ordering::SeqCst); + false + } +} + +unsafe extern "system" fn result_query( + this: *mut c_void, + iid: *const GUID, + output: *mut *mut c_void, +) -> HRESULT { + if output.is_null() { + return E_POINTER; + } + unsafe { + *output = ptr::null_mut(); + } + if iid.is_null() { + return E_POINTER; + } + let value = unsafe { &*this.cast::() }; + if !result_owner(value) { + return E_WRONG_THREAD; + } + if unsafe { *iid } != IUnknown::IID && !(value.supports_target && unsafe { *iid } == value.target) + { + return E_NOINTERFACE; + } + unsafe { + *output = this; + result_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn result_add_ref(this: *mut c_void) -> u32 { + let value = unsafe { &*this.cast::() }; + result_owner(value); + value.references.fetch_add(1, Ordering::SeqCst) + 1 +} + +unsafe extern "system" fn result_release(this: *mut c_void) -> u32 { + let value = unsafe { &*this.cast::() }; + result_owner(value); + let count = value.references.fetch_sub(1, Ordering::SeqCst) - 1; + if count == 0 { + value.stats.result_dropped.fetch_add(1, Ordering::SeqCst); + drop(unsafe { Box::from_raw(this.cast::()) }); + } + count +} + +unsafe extern "system" fn result_u32(this: *mut c_void, output: *mut u32) -> HRESULT { + let value = unsafe { &*this.cast::() }; + if !result_owner(value) { + return E_WRONG_THREAD; + } + if output.is_null() { + return E_POINTER; + } + unsafe { + *output = if value.target == IAudioClient::IID { + 384 + } else { + 2 + }; + } + HRESULT(0) +} + +macro_rules! stub { + ($name:ident($($arg:ident: $typ:ty),*)) => { + unsafe extern "system" fn $name(_this: *mut c_void, $($arg: $typ),*) -> HRESULT { + E_NOTIMPL + } + }; +} +stub!(audio_initialize(_mode: AUDCLNT_SHAREMODE, _flags: u32, _duration: i64, _period: i64, _format: *const WAVEFORMATEX, _session: *const GUID)); +stub!(audio_i64(_value: *mut i64)); +stub!(audio_format_supported(_mode: AUDCLNT_SHAREMODE, _format: *const WAVEFORMATEX, _closest: *mut *mut WAVEFORMATEX)); +stub!(audio_mix_format(_format: *mut *mut WAVEFORMATEX)); +stub!(audio_period(_default: *mut i64, _minimum: *mut i64)); +stub!(audio_noargs()); +stub!(audio_handle(_handle: HANDLE)); +stub!(audio_service(_iid: *const GUID, _result: *mut *mut c_void)); +stub!(endpoint_notify(_notify: *mut c_void)); +stub!(endpoint_set_f32(_value: f32, _context: *const GUID)); +stub!(endpoint_get_f32(_value: *mut f32)); +stub!(endpoint_set_channel(_channel: u32, _value: f32, _context: *const GUID)); +stub!(endpoint_get_channel(_channel: u32, _value: *mut f32)); +stub!(endpoint_set_mute(_value: BOOL, _context: *const GUID)); +stub!(endpoint_get_mute(_value: *mut BOOL)); +stub!(endpoint_step_info(_step: *mut u32, _count: *mut u32)); +stub!(endpoint_step(_context: *const GUID)); +stub!(endpoint_range(_min: *mut f32, _max: *mut f32, _step: *mut f32)); + +const RESULT_IDENTITY: IUnknown_Vtbl = IUnknown_Vtbl { + QueryInterface: result_query, + AddRef: result_add_ref, + Release: result_release, +}; +static AUDIO_VTABLE: IAudioClient_Vtbl = IAudioClient_Vtbl { + base__: RESULT_IDENTITY, + Initialize: audio_initialize, + GetBufferSize: result_u32, + GetStreamLatency: audio_i64, + GetCurrentPadding: result_u32, + IsFormatSupported: audio_format_supported, + GetMixFormat: audio_mix_format, + GetDevicePeriod: audio_period, + Start: audio_noargs, + Stop: audio_noargs, + Reset: audio_noargs, + SetEventHandle: audio_handle, + GetService: audio_service, +}; +static ENDPOINT_VTABLE: IAudioEndpointVolume_Vtbl = IAudioEndpointVolume_Vtbl { + base__: RESULT_IDENTITY, + RegisterControlChangeNotify: endpoint_notify, + UnregisterControlChangeNotify: endpoint_notify, + GetChannelCount: result_u32, + SetMasterVolumeLevel: endpoint_set_f32, + SetMasterVolumeLevelScalar: endpoint_set_f32, + GetMasterVolumeLevel: endpoint_get_f32, + GetMasterVolumeLevelScalar: endpoint_get_f32, + SetChannelVolumeLevel: endpoint_set_channel, + SetChannelVolumeLevelScalar: endpoint_set_channel, + GetChannelVolumeLevel: endpoint_get_channel, + GetChannelVolumeLevelScalar: endpoint_get_channel, + SetMute: endpoint_set_mute, + GetMute: endpoint_get_mute, + GetVolumeStepInfo: endpoint_step_info, + VolumeStepUp: endpoint_step, + VolumeStepDown: endpoint_step, + QueryHardwareSupport: result_u32, + GetVolumeRange: endpoint_range, +}; + +fn new_result(target: GUID, owner: u32, mode: Mode, stats: Arc) -> IUnknown { + stats.result_created.fetch_add(1, Ordering::SeqCst); + let value = Box::new(FakeResult { + vtable: if target == IAudioClient::IID { + (&AUDIO_VTABLE as *const IAudioClient_Vtbl).cast() + } else { + (&ENDPOINT_VTABLE as *const IAudioEndpointVolume_Vtbl).cast() + }, + references: AtomicU32::new(1), + target, + owner, + supports_target: mode != Mode::ProjectionFailure, + stats, + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } +} 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 e502de76..b75e9274 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -29,6 +29,11 @@ pub use com_raw::{ DynComRawStructLayout, DynComRawUnionLayout, }; mod async_promise; +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; @@ -962,17 +967,108 @@ pub struct DynWinRTValue( Option, Option, Option, + Option, ); +// 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 {} #[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(()) + } + + 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, @@ -981,28 +1077,47 @@ impl DynWinRTValue { None, None, None, + inputs, ) } pub(crate) fn bind_current_com_apartment(&mut self) -> napi::Result<()> { - if self.0.as_object().is_none() { + 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(); - match &self.6 { - Some(binding) if binding.owner_thread != current => Err(napi::Error::from_reason( + 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", - )), - Some(_) => Ok(()), - None => { - self.6 = Some(ComApartmentBinding { - owner_thread: current, - }); - Ok(()) - } + )); + } + if self.0.as_object().is_none() { + return Err(napi::Error::from_reason( + "Classic COM apartment binding requires a managed COM object", + )); } + if self.6.is_none() { + self.6 = Some(ComApartmentBinding::for_object( + &self.0.as_object().expect("checked COM object"), + )); + } + self.existing_com_context()?; + if let Some(inputs) = &self.7 { + inputs.attach(self.6.as_ref().expect("bound COM object"))?; + } + Ok(()) } pub(crate) fn ensure_com_apartment(&self) -> napi::Result<()> { @@ -1019,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 { @@ -1026,6 +1146,69 @@ 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()?; + 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()))?; + Ok(binding.context.borrow().clone()) + } + + 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); + if let Some(inputs) = &self.7 { + inputs.attach(self.6.as_ref().unwrap())?; + } + self.6.as_ref().unwrap().ensure_identity() + } + fn with_pointer_owner(value: dynwinrt::WinRTValue, owner: com::NativePointerOwner) -> Self { Self( value, @@ -1035,6 +1218,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1047,6 +1231,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1062,6 +1247,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -1077,6 +1263,7 @@ impl DynWinRTValue { Some(buffer), None, None, + None, ) } @@ -1099,159 +1286,86 @@ impl DynWinRTValue { } else { com::PointerProvenance::None }; - let apartment = matches!(value, dynwinrt::WinRTValue::Object(_)).then(|| ComApartmentBinding { - owner_thread: std::thread::current().id(), - }); - Self(value, None, provenance, None, None, None, apartment) + let apartment = if let dynwinrt::WinRTValue::Object(object) = &value { + Some(ComApartmentBinding::for_object(object)) + } else { + None + }; + 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 { @@ -1305,12 +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 @@ -1327,6 +1451,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(); } @@ -1337,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()?; } @@ -1348,6 +1480,7 @@ impl DynWinRTValue { self.4 = None; self.5 = None; self.6 = None; + self.7 = None; Ok(()) } @@ -1655,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) } @@ -1787,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")), } } @@ -1800,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")), } } @@ -1812,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] @@ -1826,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!( @@ -1833,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 -- @@ -2020,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 @@ -2040,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] @@ -2049,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] @@ -2058,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] @@ -2081,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] @@ -2100,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, ))) @@ -2115,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, ))) @@ -2127,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, )) @@ -2143,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) } } @@ -2164,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, @@ -2261,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, @@ -2273,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() { @@ -2291,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. @@ -2302,7 +2528,7 @@ impl DynWinRTStruct { typ.0.kind(), ))); } - Ok(DynWinRTStruct(typ.0.default_value())) + Ok(DynWinRTStruct::from_data(typ.0.default_value(), None)) } #[napi] @@ -2538,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(_)) })?; @@ -2553,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(()) } @@ -2567,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 @@ -2589,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) } } @@ -2913,6 +3160,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/bindings/js/src/managed_tsfn.rs b/bindings/js/src/managed_tsfn.rs index fc0a2cba..b6f2cbc1 100644 --- a/bindings/js/src/managed_tsfn.rs +++ b/bindings/js/src/managed_tsfn.rs @@ -122,10 +122,16 @@ impl TsfnLifecycle { } type Mapper = dyn Fn(T, sys::napi_env) -> napi::Result> + Send + Sync; +type NativeDispatch = dyn Fn(T, sys::napi_env) -> napi::Result<()> + Send + Sync; pub(crate) type TsfnFinalizer = dyn FnOnce(sys::napi_env); +enum Dispatch { + JavaScript(Box>), + Native(Box>), +} + struct TsfnContext { - mapper: Box>, + dispatch: Dispatch, finalizer: Option>, fallback_env: sys::napi_env, } @@ -214,6 +220,41 @@ impl ManagedTsfn { weak: bool, mapper: impl Fn(T, sys::napi_env) -> napi::Result> + Send + Sync + 'static, finalizer: Option>, + ) -> napi::Result { + Self::create_with_dispatch( + env, + callback, + max_queue_size, + weak, + Dispatch::JavaScript(Box::new(mapper)), + finalizer, + ) + } + + // No napi_value callback and no arbitrary JS execution on the producer. + // The payload is a token; apartment-bound state lives only in the consumer. + pub(crate) fn create_native_dispatch( + env: sys::napi_env, + dispatch: impl Fn(T, sys::napi_env) -> napi::Result<()> + Send + Sync + 'static, + finalizer: Option>, + ) -> napi::Result { + Self::create_with_dispatch( + env, + ptr::null_mut(), + 1, + false, + Dispatch::Native(Box::new(dispatch)), + finalizer, + ) + } + + fn create_with_dispatch( + env: sys::napi_env, + callback: sys::napi_value, + max_queue_size: usize, + weak: bool, + dispatch: Dispatch, + finalizer: Option>, ) -> napi::Result { let lifecycle = TsfnLifecycle::get_or_create(Env::from_raw(env))?; let open = lifecycle @@ -227,7 +268,7 @@ impl ManagedTsfn { } let context = Box::new(TsfnContext { - mapper: Box::new(mapper), + dispatch, finalizer, fallback_env: env, }); @@ -421,12 +462,25 @@ unsafe extern "C" fn call_js( return; } let value = unsafe { *Box::::from_raw(data.cast()) }; - if env.is_null() || callback.is_null() { + if env.is_null() { return; } let context = unsafe { &*context.cast::>() }; - let args = match (context.mapper)(value, env) { + let mapper = match &context.dispatch { + Dispatch::Native(dispatch) => { + if let Err(error) = dispatch(value, env) { + let error = unsafe { JsError::from(error).into_value(env) }; + unsafe { + sys::napi_fatal_exception(env, error); + } + } + return; + } + Dispatch::JavaScript(mapper) if !callback.is_null() => mapper, + Dispatch::JavaScript(_) => return, + }; + let args = match mapper(value, env) { Ok(args) => args, Err(error) => { let error = unsafe { JsError::from(error).into_value(env) }; 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 4dc84fe7..f74f05cc 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -7,7 +7,11 @@ description = "Dynamic WinRT API invocation — call any Windows Runtime method repository = "https://github.com/microsoft/dynwinrt" authors = ["Microsoft"] +[features] +test-hooks = ["windows/Win32_Media_MediaFoundation"] + [dependencies] +dynwinrt-com-contracts = { path = "../dynwinrt-com-contracts", version = "0.1.0" } libffi = "5.1.0" libffi-sys = "4.1.0" paste = "1" @@ -50,6 +54,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/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 f2149b54..96ad4ef0 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -29,6 +29,12 @@ 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; pub use automation::{ DispatchParamsValue, ExcepInfoValue, PropVariantData, PropVariantType, PropVariantValue, PropVariantVector, PropVariantVectorType, SafeArrayBound, SafeArrayElementType, @@ -1471,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(), @@ -4636,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( @@ -5088,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", @@ -5105,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() { @@ -5224,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 {}", @@ -5852,6 +6017,7 @@ pub struct MethodSignature { return_plan: ComReturnPlan, enumerator_next_vtable_index: Option, canonical_format_etc: Option, + context_effect: Option, } #[derive(Debug, Clone, Copy)] @@ -5868,6 +6034,7 @@ impl MethodSignature { return_plan: ComReturnPlan::HResult, enumerator_next_vtable_index: None, canonical_format_etc: None, + context_effect: None, } } @@ -6124,6 +6291,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() @@ -6205,6 +6381,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()?; } @@ -6302,6 +6485,8 @@ impl MethodSignature { Ok(RegisteredMethod { plan: ComCallPlan::new(native, self.parameters, self.return_plan), callback_plan, + context_effect: self.context_effect, + context_hresult_plan, }) } } @@ -6784,6 +6969,8 @@ fn require_direction( struct RegisteredMethod { plan: ComCallPlan, callback_plan: CallbackMethodPlan, + context_effect: Option, + context_hresult_plan: Option, } type RegisteredMethods = BTreeMap)>; @@ -6890,6 +7077,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}", @@ -6939,6 +7131,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() } @@ -6989,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 {}", @@ -7025,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 @@ -7181,11 +7417,14 @@ struct DynamicComSink { iids: Vec, iid_map: Vec<(GUID, usize)>, callback_plans: Vec>, + // Present only on the private, native-only one-shot signal sink. + free_threaded_marshaler: Option, } // The refcount is atomic, the vtable is immutable after publication, and the // callback is explicitly Send + Sync. Language bindings may impose a stricter -// apartment/thread policy before invoking their callback. +// apartment/thread policy before invoking their callback. The optional inner +// is the actual free-threaded marshaler, never an apartment-bound COM object. unsafe impl Send for DynamicComSink {} unsafe impl Sync for DynamicComSink {} @@ -7269,6 +7508,14 @@ impl DynamicComSink { fn create( interfaces: Vec, callback: SinkCallback, + ) -> result::Result { + Self::create_impl(interfaces, callback, false) + } + + fn create_impl( + interfaces: Vec, + callback: SinkCallback, + native_signal: bool, ) -> result::Result { if interfaces.is_empty() { return Err(invalid_argument( @@ -7346,11 +7593,21 @@ impl DynamicComSink { iids, iid_map, callback_plans: all_plans, + free_threaded_marshaler: None, }); let owner = (&mut *sink) as *mut Self; for view in &mut sink.interfaces { view.owner = owner; } + if native_signal { + let raw = owner.cast(); + let identity = unsafe { IUnknown::from_raw_borrowed(&raw) } + .expect("allocated native signal identity"); + sink.free_threaded_marshaler = Some( + unsafe { windows::Win32::System::Com::CoCreateFreeThreadedMarshaler(identity) } + .map_err(result::Error::WindowsError)?, + ); + } Ok(unsafe { IUnknown::from_raw(Box::into_raw(sink).cast()) }) } @@ -7394,7 +7651,15 @@ impl DynamicComSink { result: *mut *mut c_void, ) -> HRESULT { let sink = unsafe { &*owner }; - let pointer = if *iid == IUnknown::IID { + if let Some(marshaler) = &sink.free_threaded_marshaler + && *iid == windows_core::imp::IMarshal::IID + { + return unsafe { marshaler.query(iid, result) }; + } + let pointer = if *iid == IUnknown::IID + || (sink.free_threaded_marshaler.is_some() + && *iid == windows_core::imp::IAgileObject::IID) + { owner.cast() } else if let Some((_, index)) = sink.iid_map.iter().find(|(candidate, _)| candidate == iid) { @@ -7462,6 +7727,16 @@ impl DynamicComSink { catch_unwind(AssertUnwindSafe(|| { let view = unsafe { Self::view_from_ptr(this) }; let sink = unsafe { &*view.owner }; + let _in_flight = if sink.free_threaded_marshaler.is_some() { + let identity = view.owner.cast(); + Some( + unsafe { IUnknown::from_raw_borrowed(&identity) } + .expect("native signal identity") + .clone(), + ) + } else { + None + }; let callback = sink.callback.clone(); let values = [unsafe { Self::borrowed_interface(value) }]; let result = callback( 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 new file mode 100644 index 00000000..a8b640dc --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed.rs @@ -0,0 +1,851 @@ +// 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}; + +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; +#[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); +#[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; + +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: AudioRole) -> result::Result { + self.ensure_thread()?; + 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", + )); + } + 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) }); + } + } +} + +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 { + 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 + .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_guarded( + view.as_raw(), + args, + before_dispatch, + )? + }, + 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_guarded(view.as_raw(), args, before_dispatch)?; + 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_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 new file mode 100644 index 00000000..1d056d0a --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_test_support.rs @@ -0,0 +1,1087 @@ +// 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 _}; + +#[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); +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) + } +} +const 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 +} +const 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 +} +const 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()) +} +const 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 +} +const 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 +} +const 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 == "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); + } + 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(()) + } + 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..825e1b6a --- /dev/null +++ b/crates/dynwinrt/src/com_borrowed_tests.rs @@ -0,0 +1,762 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +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() +} + +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.calls[0].evidence.push_str(".slot-drift"); + assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); + let mut descriptor = BorrowedCopyContract::expected(kind); + descriptor.calls[0].bindings.clear(); + assert!(BorrowedCopyPlan::prepare(&MetadataTable::new(), descriptor).is_err()); + let mut descriptor = BorrowedCopyContract::expected(kind); + 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(); + 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/crates/dynwinrt/src/com_completion.rs b/crates/dynwinrt/src/com_completion.rs new file mode 100644 index 00000000..b3252db4 --- /dev/null +++ b/crates/dynwinrt/src/com_completion.rs @@ -0,0 +1,619 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Bounded native one-shot completion. No language callbacks or operation +//! references are stored in the free-threaded signal sink. + +use std::{ + ffi::{CString, c_void}, + marker::PhantomData, + ptr, + rc::Rc, + sync::{Arc, Mutex}, + thread::{self, ThreadId}, +}; + +use libffi::middle::{Arg, Cif, CodePtr, Type as FfiType}; +use windows::Win32::{ + Foundation::{FreeLibrary, HMODULE}, + System::{ + Com::CoGetApartmentType, + LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN, + GetModuleHandleExW, GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }, + }, +}; +use windows_core::{GUID, HRESULT, IUnknown, Interface as _, PCSTR, PCWSTR}; + +use super::{CallbackContract, DynamicComSink, InterfaceBase, SinkCallbackResult, Value}; +use crate::{MetadataTable, WinRTValue}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StartArgument { + Utf16Path, + RefIid, + NullPropVariant, + NativeSignal, + OwnedOperation, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResultArgument { + HResult, + NullableOwnedInterface, +} + +/// A completed COM-local contract, supplied only after metadata validation. +#[derive(Debug, Clone)] +pub struct OneShotContract { + pub library: String, + pub export: String, + pub start_arguments: Vec, + pub handler_iid: GUID, + pub handler_slot: usize, + pub operation_iid: GUID, + pub result_slot: usize, + pub result_arguments: Vec, + pub allowed_targets: Vec, +} + +impl OneShotContract { + fn validate(&self) -> Result<(), CompletionError> { + if self.library != "MMDevAPI.dll" + || self.export != "ActivateAudioInterfaceAsync" + || self.start_arguments + != [ + StartArgument::Utf16Path, + StartArgument::RefIid, + StartArgument::NullPropVariant, + StartArgument::NativeSignal, + StartArgument::OwnedOperation, + ] + || self.handler_iid != GUID::from_u128(0x41d949ab_9862_444a_80f6_c261334da5eb) + || self.operation_iid != GUID::from_u128(0x72a22d78_cde4_431d_b8cc_843a71199b6d) + || self.handler_slot != 3 + || self.result_slot != 3 + || self.result_arguments + != [ + ResultArgument::HResult, + ResultArgument::NullableOwnedInterface, + ] + || self.allowed_targets + != [ + GUID::from_u128(0x1cb9ad4c_dbfa_4c32_b178_c2f568a703b2), + GUID::from_u128(0x5cdf2c82_841e_4546_9722_0cf74078229a), + ] + { + return Err(CompletionError::contract( + "descriptor", + "Unsupported or changed native one-shot contract; regenerate the COM bindings", + )); + } + Ok(()) + } +} + +#[derive(Debug)] +pub struct CompletionError { + pub stage: &'static str, + pub hresult: Option, + pub message: String, +} + +impl CompletionError { + pub fn contract(stage: &'static str, message: impl Into) -> Self { + Self { + stage, + hresult: None, + message: message.into(), + } + } + + pub fn native(stage: &'static str, hresult: HRESULT) -> Self { + Self { + stage, + hresult: Some(hresult), + message: format!( + "Native COM completion {stage} failed (HRESULT 0x{:08X})", + hresult.0 as u32 + ), + } + } +} + +impl std::fmt::Display for CompletionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.stage, self.message) + } +} + +impl std::error::Error for CompletionError {} + +type Notify = Box; + +struct SignalState { + published: bool, + completed: bool, + closed: bool, + notify: Option, +} + +/// Pointer-free, one-shot rendezvous between start publication and completion. +/// The notification must only enqueue a token; it must not call a language +/// runtime or retain an operation/result interface. +pub struct CompletionSignal(Mutex); + +impl CompletionSignal { + pub fn new(notify: impl FnOnce() + Send + 'static) -> Arc { + Arc::new(Self(Mutex::new(SignalState { + published: false, + completed: false, + closed: false, + notify: Some(Box::new(notify)), + }))) + } + + pub fn publish(&self) { + self.advance(true); + } + + fn complete(&self) { + self.advance(false); + } + + fn advance(&self, publish: bool) { + let notify = { + let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner()); + if state.closed { + return; + } + if publish { + state.published = true; + } else { + state.completed = true; + } + if state.published && state.completed { + state.notify.take() + } else { + None + } + }; + if let Some(notify) = notify { + notify(); + } + } + + pub fn close(&self) { + let notify = { + let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner()); + state.closed = true; + state.notify.take() + }; + drop(notify); + } +} + +struct Module(HMODULE); + +impl Drop for Module { + fn drop(&mut self) { + let _ = unsafe { FreeLibrary(self.0) }; + } +} + +fn pin_code_module(address: *const c_void) -> Result<(), CompletionError> { + let mut pinned = HMODULE::default(); + unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + PCWSTR(address.cast()), + &mut pinned, + ) + } + .map_err(|error| CompletionError::native("load", error.code())) +} + +/// Owner-thread-only even when Windows happens to return an agile operation. +/// +/// ```compile_fail +/// fn require_send() {} +/// require_send::(); +/// ``` +pub struct OwnerOperation { + object: IUnknown, + owner: ThreadId, + _apartment: PhantomData>, +} + +pub struct NativeSignalSink { + object: IUnknown, + iid: GUID, +} + +impl NativeSignalSink { + #[cfg(any(test, feature = "test-hooks"))] + pub fn interface(&self) -> &IUnknown { + &self.object + } +} + +/// Immutable libffi plans and module lifetime, deliberately not Send or Sync. +pub struct OneShotPlan { + contract: OneShotContract, + start_cif: Cif, + result_cif: Cif, + entry: CodePtr, + _module: Option, + owner: ThreadId, + _apartment: PhantomData>, +} + +impl OneShotPlan { + pub fn prepare(contract: OneShotContract) -> Result { + contract.validate()?; + let library = contract + .library + .encode_utf16() + .chain(Some(0)) + .collect::>(); + let module = Module( + unsafe { LoadLibraryExW(PCWSTR(library.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32) } + .map_err(|error| CompletionError::native("load", error.code()))?, + ); + let export = CString::new(contract.export.as_bytes()) + .map_err(|_| CompletionError::contract("descriptor", "Embedded NUL in export"))?; + let entry = unsafe { GetProcAddress(module.0, PCSTR(export.as_ptr().cast())) } + .ok_or_else(|| CompletionError::native("load", HRESULT(0x8007007fu32 as i32)))?; + let entry = CodePtr(entry as *const () as *mut c_void); + // A late OS completion may outlive Node environment teardown. Pin only + // this allowlisted system module, never an application-supplied DLL. + pin_code_module(entry.0)?; + Ok(Self::lower(contract, entry, Some(module))) + } + + fn lower(contract: OneShotContract, entry: CodePtr, module: Option) -> Self { + let start_cif = crate::native_call::system_cif( + contract + .start_arguments + .iter() + .map(|_| FfiType::pointer()) + .collect(), + FfiType::i32(), + ); + let result_cif = crate::native_call::system_cif( + std::iter::once(FfiType::pointer()) + .chain(contract.result_arguments.iter().map(|_| FfiType::pointer())) + .collect(), + FfiType::i32(), + ); + Self { + contract, + start_cif, + result_cif, + entry, + _module: module, + owner: thread::current().id(), + _apartment: PhantomData, + } + } + + #[cfg(any(test, feature = "test-hooks"))] + pub unsafe fn with_test_export( + contract: OneShotContract, + entry: *mut c_void, + ) -> Result { + contract.validate()?; + if entry.is_null() { + return Err(CompletionError::contract("test-export", "Null fake export")); + } + Ok(Self::lower(contract, CodePtr(entry), None)) + } + + fn ensure_owner(&self) -> Result<(), CompletionError> { + if thread::current().id() != self.owner { + return Err(CompletionError::native( + "apartment", + HRESULT(0x8001010eu32 as i32), + )); + } + let mut apartment = Default::default(); + let mut qualifier = Default::default(); + unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) } + .map_err(|error| CompletionError::native("apartment", error.code())) + } + + pub fn create_signal_sink( + &self, + signal: Arc, + ) -> Result { + self.ensure_owner()?; + // An OS-held callback may outlive the last Node environment that + // loaded this addon. Its static vtable code must remain mapped too. + pin_code_module(DynamicComSink::query_interface as *const () as *const c_void)?; + let table = MetadataTable::new(); + let interface = super::register_interface( + &table, + "NativeOneShotSignal", + self.contract.handler_iid, + InterfaceBase::IUnknown, + ) + .add_method_at( + self.contract.handler_slot, + "Signal", + super::MethodSignature::new(&table).add_in(super::Type::winrt(table.object())), + ) + .map_err(|error| CompletionError::contract("signal", error.message()))?; + let iid = self.contract.handler_iid; + let operation_iid = self.contract.operation_iid; + let callback: super::SinkCallback = Arc::new(move |actual_iid, slot, args, contract| { + if actual_iid != iid || slot != 3 || contract != CallbackContract::hresult(0) { + return SinkCallbackResult::hresult(super::SINK_E_FAIL); + } + let [Value::WinRt(WinRTValue::Object(operation))] = args else { + return SinkCallbackResult::hresult(super::SINK_E_POINTER); + }; + // QI and its temporary +1 stay on the callback apartment. Only the + // signal is retained; GetActivateResult never runs here. + let mut borrowed = OwnedOutput::default(); + let hr = unsafe { operation.query(&operation_iid, &mut borrowed.0) }; + if hr.is_err() { + return SinkCallbackResult::hresult(hr); + } + if borrowed.0.is_null() { + return SinkCallbackResult::hresult(super::SINK_E_POINTER); + } + drop(borrowed); + signal.complete(); + SinkCallbackResult::hresult(HRESULT(0)) + }); + let definition = interface + .callback_backends() + .map_err(|error| CompletionError::contract("signal", error.message()))?; + let identity = DynamicComSink::create_impl(vec![definition], callback, true) + .map_err(|error| CompletionError::contract("signal", error.message()))?; + let mut view = OwnedOutput::default(); + let hr = unsafe { identity.query(&iid, &mut view.0) }; + if hr.is_err() { + return Err(CompletionError::native("signal", hr)); + } + let object = view.take().ok_or_else(|| { + CompletionError::contract("signal", "Native signal interface was not published") + })?; + Ok(NativeSignalSink { object, iid }) + } + + pub fn start( + &self, + path: &str, + target_iid: GUID, + sink: &NativeSignalSink, + ) -> Result { + self.ensure_owner()?; + if path.contains('\0') { + return Err(CompletionError::contract( + "input", + "Device interface path contains NUL", + )); + } + if !self.contract.allowed_targets.contains(&target_iid) + || sink.iid != self.contract.handler_iid + { + return Err(CompletionError::contract( + "input", + "Unsupported native completion target or signal", + )); + } + let path = path.encode_utf16().chain(Some(0)).collect::>(); + let mut output = OwnedOutput::default(); + let mut storage = Vec::<*mut c_void>::with_capacity(self.contract.start_arguments.len()); + for argument in &self.contract.start_arguments { + storage.push(match argument { + StartArgument::Utf16Path => path.as_ptr().cast_mut().cast(), + StartArgument::RefIid => (&target_iid as *const GUID).cast_mut().cast(), + StartArgument::NullPropVariant => ptr::null_mut(), + StartArgument::NativeSignal => sink.object.as_raw(), + StartArgument::OwnedOperation => (&mut output.0 as *mut *mut c_void).cast(), + }); + } + let args = storage.iter().map(Arg::new).collect::>(); + let hr = HRESULT(unsafe { self.start_cif.call::(self.entry, &args) }); + if hr.is_err() { + return Err(CompletionError::native("start", hr)); + } + let object = output.take().ok_or_else(|| { + CompletionError::contract("start", "Start succeeded with a NULL operation") + })?; + Ok(OwnerOperation { + object, + owner: self.owner, + _apartment: PhantomData, + }) + } + + pub fn collect( + &self, + operation: &OwnerOperation, + target_iid: GUID, + ) -> Result { + self.ensure_owner()?; + if operation.owner != self.owner || !self.contract.allowed_targets.contains(&target_iid) { + return Err(CompletionError::contract( + "result", + "Owner or target mismatch", + )); + } + let this = operation.object.as_raw(); + let vtable = unsafe { *this.cast::<*const *mut c_void>() }; + let entry = unsafe { *vtable.add(self.contract.result_slot) }; + let mut inner = super::SINK_E_FAIL.0; + let mut output = OwnedOutput::default(); + let mut storage = vec![this]; + for argument in &self.contract.result_arguments { + storage.push(match argument { + ResultArgument::HResult => (&mut inner as *mut i32).cast(), + ResultArgument::NullableOwnedInterface => { + (&mut output.0 as *mut *mut c_void).cast() + } + }); + } + let args = storage.iter().map(Arg::new).collect::>(); + let outer = HRESULT(unsafe { self.result_cif.call::(CodePtr(entry), &args) }); + if outer.is_err() { + return Err(CompletionError::native("result", outer)); + } + if HRESULT(inner).is_err() { + return Err(CompletionError::native("activation", HRESULT(inner))); + } + let result = output.take().ok_or_else(|| { + CompletionError::contract("result", "Both HRESULTs succeeded with a NULL interface") + })?; + let mut projected = OwnedOutput::default(); + let hr = unsafe { result.query(&target_iid, &mut projected.0) }; + if hr.is_err() { + return Err(CompletionError::native("projection", hr)); + } + projected.take().ok_or_else(|| { + CompletionError::contract("projection", "QueryInterface succeeded with NULL") + }) + } +} + +#[derive(Default)] +struct OwnedOutput(*mut c_void); + +impl OwnedOutput { + fn take(&mut self) -> Option { + let pointer = std::mem::replace(&mut self.0, ptr::null_mut()); + (!pointer.is_null()).then(|| unsafe { IUnknown::from_raw(pointer) }) + } +} + +impl Drop for OwnedOutput { + fn drop(&mut self) { + drop(self.take()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn contract() -> OneShotContract { + OneShotContract { + library: "MMDevAPI.dll".into(), + export: "ActivateAudioInterfaceAsync".into(), + start_arguments: vec![ + StartArgument::Utf16Path, + StartArgument::RefIid, + StartArgument::NullPropVariant, + StartArgument::NativeSignal, + StartArgument::OwnedOperation, + ], + handler_iid: GUID::from_u128(0x41d949ab_9862_444a_80f6_c261334da5eb), + handler_slot: 3, + operation_iid: GUID::from_u128(0x72a22d78_cde4_431d_b8cc_843a71199b6d), + result_slot: 3, + result_arguments: vec![ + ResultArgument::HResult, + ResultArgument::NullableOwnedInterface, + ], + allowed_targets: vec![ + GUID::from_u128(0x1cb9ad4c_dbfa_4c32_b178_c2f568a703b2), + GUID::from_u128(0x5cdf2c82_841e_4546_9722_0cf74078229a), + ], + } + } + + #[test] + fn native_completion_loads_only_the_system_export_and_has_real_ftm_identity() { + thread::spawn(|| { + super::super::initialize_apartment(super::super::ApartmentType::MultiThreaded).unwrap(); + let plan = OneShotPlan::prepare(contract()).unwrap(); + assert!(!plan.start_cif.as_raw_ptr().is_null()); + let signal = + CompletionSignal::new(|| panic!("no native activation is started by this test")); + let sink = plan.create_signal_sink(signal.clone()).unwrap(); + let query = |object: &IUnknown, iid: &GUID| { + let mut result = OwnedOutput::default(); + unsafe { + object.query(iid, &mut result.0).ok().unwrap(); + } + result.take().unwrap() + }; + let identity = query(sink.interface(), &IUnknown::IID); + for iid in [ + plan.contract.handler_iid, + windows_core::imp::IAgileObject::IID, + windows_core::imp::IMarshal::IID, + ] { + let view = query(sink.interface(), &iid); + let canonical = query(&view, &IUnknown::IID); + assert_eq!(canonical.as_raw(), identity.as_raw()); + } + drop(identity); + drop(sink); + assert_eq!(Arc::strong_count(&signal), 1); + signal.close(); + let mut invalid = contract(); + invalid.start_arguments.push(StartArgument::NativeSignal); + assert!(OneShotPlan::prepare(invalid).is_err()); + let mut invalid = contract(); + invalid.library = "C:\\untrusted\\MMDevAPI.dll".into(); + assert!(OneShotPlan::prepare(invalid).is_err()); + }) + .join() + .unwrap(); + } + + #[test] + fn native_completion_signal_races_publish_without_duplicates() { + let calls = Arc::new(AtomicUsize::new(0)); + let called = calls.clone(); + let signal = CompletionSignal::new(move || { + called.fetch_add(1, Ordering::SeqCst); + }); + let mut threads = Vec::new(); + for _ in 0..16 { + let signal = signal.clone(); + threads.push(thread::spawn(move || signal.complete())); + } + signal.publish(); + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn signal_publication_and_completion_are_once_and_close_is_not_cancellation() { + fn assert_send_sync() {} + assert_send_sync::(); + for early in [true, false] { + let calls = Arc::new(AtomicUsize::new(0)); + let called = calls.clone(); + let signal = CompletionSignal::new(move || { + called.fetch_add(1, Ordering::SeqCst); + }); + if early { + signal.complete(); + signal.complete(); + assert_eq!(calls.load(Ordering::SeqCst), 0); + signal.publish(); + } else { + signal.publish(); + signal.complete(); + } + signal.publish(); + signal.complete(); + signal.close(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + let signal = CompletionSignal::new(|| panic!("closed signal must not dispatch")); + signal.complete(); + signal.close(); + signal.publish(); + signal.complete(); + } +} 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-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 94c07839..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,333 | -| `exact_registry_dependent` | 364 | -| **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. -Per-interface dependency-set totals also include 5,983 metadata-attribute -dependencies and 26,134 COM-standard-rule dependencies. +| `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 +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 | @@ -472,6 +480,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: @@ -483,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 | @@ -493,6 +503,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: @@ -503,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 @@ -540,17 +563,27 @@ 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. -Seven WMI conditional-output entries and 149 output-ownership entries are -JSON-backed; the other 350 registered entries remain code-defined. All code and -data entries use the same selector-derived `entryId`, typed `familyId`, +manifests are version 12. +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 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 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 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 d67a3b38..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 @@ -445,10 +462,10 @@ Generation emits `generated/com/unsafe/support.json`: ```json { - "schemaVersion": 11, + "schemaVersion": 12, "interfaces": [ { - "schemaVersion": 11, + "schemaVersion": 12, "metadata": { "setSha256": "...", "files": ["..."], @@ -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 664b304a..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,350 @@ 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 +`Windows.Win32.Media.Audio.Apis.ActivateAudioInterfaceAsync` relationship. +It is separate from general interface projection and does not increase the +complete-interface census. No general native-export or COM server API is +introduced. + +The configured `Windows.Win32.winmd` must contain the following complete +contracts. The retained regression uses Win32Metadata **71.0.14-preview**, +SHA256 `B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`. + +| Entry | Verified native ABI and contract | +| --- | --- | +| `MMDevAPI.dll!ActivateAudioInterfaceAsync` | System ABI, ordinary HRESULT return, exactly five arguments and **no `this`**: const NUL-terminated UTF-16 path; REFIID; optional `PROPVARIANT*` restricted to NULL; borrowed completion-handler interface; required cell receiving an owned operation `+1`. | +| `IActivateAudioInterfaceCompletionHandler` | IID `41d949ab-9862-444a-80f6-c261334da5eb`, direct IUnknown inheritance, only slot 3 `ActivateCompleted`, ordinary HRESULT, one borrowed operation-interface input. | +| `IActivateAudioInterfaceAsyncOperation` | IID `72a22d78-cde4-431d-b8cc-843a71199b6d`, direct IUnknown inheritance, only slot 3 `GetActivateResult`, ordinary outer HRESULT, required `HRESULT*` and `IUnknown**` output cells. | + +The export parser preserves named types, pointer depth, direction, optional +and Const attributes, import library, entry point, and calling convention. +The COM projector validates the whole relationship before emitting a +versioned, closed runtime descriptor, plus the complete safe `IAudioClient` +and `IAudioEndpointVolume` projections. Unknown signatures and contract drift +fail during dry-run/generation and again at runtime descriptor validation. +No renderer infers ownership from method names. + +Metadata does not mark the *contained* `activatedInterface` pointer nullable. +The exact +[GetActivateResult contract](https://learn.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-iactivateaudiointerfaceasyncoperation-getactivateresult) +documents NULL on inner activation failure; its receiving cell is still +required. The native collector interprets start HRESULT, outer result HRESULT, +inner activation HRESULT, and NULL independently, with RAII cleanup of written +owned outputs even on failure. Successful result QI and the public `projectAs` +registry run on the owner thread. +The owned result is not placed in a JavaScript native-value carrier until +that carrier has a registered finalizer. A failing N-API class construction +during worker shutdown therefore still releases the result on its owner. + +`com_completion.rs` prepares bounded libffi export/result plans using the +existing system-ABI CIF helper. The allowlisted DLL is resolved from System32 +and pinned for late native completion after Node teardown. It does not call a +compiled per-interface SDK adapter, invent a COM receiver, or permit +production function-address injection. The signal's own code module is also +pinned before publication, so a callback cannot jump into an unloaded addon +after the last Node environment using it has closed. + +The private signal sink reuses `DynamicComSink`'s HRESULT/interface-input +static thunk. It has canonical IUnknown identity, the exact callback IID, +IAgileObject, and a real IMarshal delegated to an aggregated +[CoCreateFreeThreadedMarshaler](https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreatefreethreadedmarshaler). +This is an internal implementation detail, not general aggregation support. +The free-threaded state contains only a pointer-free publication/completion +rendezvous and a native token notifier, never an operation, result, or JS +callback. A temporary in-flight reference protects the sink; callback input +QI/borrowed references are released in that callback's apartment. + +Node keeps the original start-returned operation, handler, deferred, and plan +in an owner-thread-local record that is not Send/Sync. The native signal only +enqueues a process-unique token through `ManagedTsfn`'s native-dispatch mode. +Publication gates early callbacks, duplicate callbacks notify once, and no +operation→handler→operation cycle is formed. Owner dispatch collects results +only after the signal; it neither casts to WinRT IAsyncInfo nor assumes that +the operation or audio result is agile. Ordinary JS callback owner-thread +guards and WinRT async dispatch are unchanged. + +One-shot notifier disposal releases the TSFN even if Windows retains the +handler. There are at most 256 pending records per environment, including +reservations made before a potentially reentrant start call. Cleanup +closes every signal before releasing owner COM references; late/stale tokens +cannot address a new record in a recycled environment. Dropping the JS Promise +does not cancel native work. No timeout, AbortSignal, loopback parameters, or +arbitrary cross-apartment JS scheduling is exposed. + +Deterministic tests use an ABI-correct five-argument fake export, complete +operation and audio-result vtables, actual FTM QI, and initialized MTA delivery +through +[RoGetAgileReference/Resolve](https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-rogetagilereference). +Fake non-agile results are created only in owner-thread GetActivateResult. +Coverage includes early/duplicate completion, all HRESULT/NULL stages, +exactly-once lifetime, stale/recycled tokens, callback-in-flight teardown, +addon lifetime after the last environment closes, pending-work bounds, and +event-loop exit. This deterministic suite does not activate hardware or +record audio. The separate opt-in `DYNWINRT_TEST_AUDIO_RENDER=1` smoke only +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 three copy-only facades remain excluded from the current +**5,721 / 7,929** complete safe census. + +### Private context and lifecycle + +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 + \ 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. + +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 +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 + +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) +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. +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 before the version-2 execution-plan refactor: + +| 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 @@ -190,8 +534,9 @@ callable entries, the most useful count is: These numbers describe the metadata, not dynwinrt support: -- The current Classic COM work targets interface methods. It does **not** - project the 17,760 flat DLL exports. +- Classic COM primarily targets interface methods. Apart from the bounded + native-completion export above, it does **not** project the 17,760 flat DLL + exports. - An interface declaration may describe a caller-implemented callback rather than an OS object that can be activated and called. - The interface count includes graphics, media, WMI, Automation, Shell, and @@ -473,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`). | @@ -549,8 +894,10 @@ 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 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 @@ -1287,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 31ceb7f0..694351be 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,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 3. 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. -**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 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. @@ -599,8 +602,10 @@ The generated implementation boundary is: If any method contains an unmodeled Automation/union/ownership/allocator contract, codegen omits `implement()` for the entire interface. Cross-apartment -dispatch, connection-point helpers, COM aggregation, custom marshaling, and -COM server registration remain unsupported. +JavaScript dispatch, connection-point helpers, COM aggregation, custom +marshaling, and COM server registration remain unsupported. The native-only +one-shot completion in [section 5.6](#56-native-one-shot-audio-activation) +does not relax these JavaScript callback restrictions. ### 5.5 Audio endpoint activation @@ -643,8 +648,8 @@ activation parameters. The target must be a registered generated safe class for exactly one of `IAudioClient`, `IAudioEndpointVolume`, `IAudioMeterInformation`, `IAudioSessionManager`, or `IAudioSessionManager2`. Generate and import whichever target the application needs. Other/custom -targets, async activation, and loopback or other parameterized activation -remain outside this safe subset. +targets and loopback or other parameterized activation remain outside this +synchronous subset. The separate bounded async entry point is described below. The five targets are named, cited records in `tools/dynwinrt-codegen/src/com_activation_registry.rs`, each carrying the @@ -661,6 +666,188 @@ contracts remain unchanged. This path uses validated generated contracts and shared runtime primitives, not per-interface native adapters; the WinRT root entrypoint is unchanged. +### 5.6 Native one-shot audio activation + +Generate the DLL-export consumer, which also validates and emits both supported +result interface classes: + +```powershell +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --namespace Windows.Win32.Media.Audio ` + --class-name ActivateAudioInterfaceAsync ` + --output .\generated ` + --dry-run +# Remove --dry-run to write the bindings. +``` + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; +import { + activateAudioInterfaceAsync, + IAudioEndpointVolume, +} from "./generated/com/index.js"; + +initializeCom(0); // Choose the caller's apartment before starting activation. +const volume = await activateAudioInterfaceAsync( + renderDeviceInterfacePath, // e.g. an audio-render ID from MediaDevice + IAudioEndpointVolume, +); +try { + console.log(volume.getChannelCount()); // No recording or volume changes. +} finally { + volume.release(); +} +``` + +`activateAudioInterfaceAsync(path, GeneratedInterfaceClass): Promise` is +available only in the generated COM modules, not the WinRT npm root. The +target must be the registered safe `IAudioClient` or `IAudioEndpointVolume` +class. A successful result has independent owned lifetime and uses the same +`projectAs` registry as synchronous COM acquisition. + +The start runs immediately on the calling/owner apartment; it is **not** +moved to an MTA worker to evade Windows consent or UI-thread requirements. +[Microsoft documents UI-thread consent requirements and explicitly safe +render-device activations](https://learn.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-activateaudiointerfaceasync). +`initializeCom(0)` alone does not provide an application UI thread or a consent +window. Applications must select the correct thread and device path. + +This first subset always passes native NULL for `activationParams`. Extra +arguments, custom `PROPVARIANT`/loopback blobs, unregistered or unsupported +target classes, and embedded NUL in the device path are rejected. There is no +generic DLL-export, callback scheduling, aggregation, or cancellation API. +Dropping a Promise is **not** OS cancellation. At most 256 native completions +may be pending per Node environment; pending work keeps its dispatcher alive +until completion or environment teardown. + +Windows invokes a private native-only completion signal, not a JavaScript +handler. The original operation and result stay on the owner thread. +Ordinary generated `implement()`/`implementation()` callbacks still reject +foreign-thread calls with `RPC_E_WRONG_THREAD`. + +Errors distinguish `stage: "start"` (export HRESULT), `"result"` (outer +`GetActivateResult` HRESULT or a NULL-success contract violation), +`"activation"` (inner activation HRESULT), and `"projection"` (result QI). +Native HRESULT failures preserve the signed numeric `hresult` property and +hexadecimal value in the message. Written owned outputs are released on both +HRESULT failure paths. Two successful HRESULTs with a NULL interface reject +instead of resolving an empty wrapper. + +Run deterministic fake-export/FTM/apartment/lifecycle coverage with +`npm run test:native-completion` in `bindings\js`, with +`DYNWINRT_WIN32_WINMD` set. It does not access an audio device or microphone. +An optional live smoke is enabled by `DYNWINRT_TEST_AUDIO_RENDER=1`. It requires +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 **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 ` + --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. + +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 +[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 03abd89e..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,40 @@ 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,333 | -| `exact_registry_dependent` | 364 | +| `standard_derived` | 5,355 | +| `exact_registry_dependent` | 366 | -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 -5,983 metadata-attribute and 26,134 universal COM-rule dependency sets. +The registry declares 532 selector-specific entries; all 532 match pinned +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, 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. +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 +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. @@ -405,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 @@ -430,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 @@ -458,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, @@ -545,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 ddc73724..4df35312 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": { @@ -80,35 +80,40 @@ "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": 5333, - "exactRegistryDependent": 364, - "metadataFactOccurrences": 5983, - "comStandardFactOccurrences": 26134, - "registeredExactEntries": 506, - "metadataMatchedExactEntries": 506, - "safeConsumedExactEntries": 415, - "exactEntryInterfaceDependencies": 671, - "exactFamilyInterfaceDependencies": 417, + "safeComplete": 5721, + "standardDerived": 5355, + "exactRegistryDependent": 366, + "metadataFactOccurrences": 6012, + "comStandardFactOccurrences": 26247, + "registeredExactEntries": 532, + "metadataMatchedExactEntries": 532, + "safeConsumedExactEntries": 431, + "exactEntryInterfaceDependencies": 694, + "exactFamilyInterfaceDependencies": 425, "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, "null-input": 4, - "ownership": 182, + "ownership": 183, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 }, "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, @@ -386,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, @@ -526,13 +544,15 @@ }, "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, "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, @@ -543,9 +563,9 @@ }, "byMetadataAttribute": { "CanReturnMultipleSuccessValuesAttribute": 46, - "ConstAttribute": 3332, + "ConstAttribute": 3351, "FreeWithAttribute": 3, - "NativeArrayInfoAttribute": 2602 + "NativeArrayInfoAttribute": 2612 }, "byStandardRuleId": { "com.activation.output-plus-one.v1": 976, @@ -553,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": { @@ -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", @@ -6931,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", @@ -10861,14 +11349,14 @@ "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": { "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 }, @@ -10876,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 }, @@ -10884,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 556a9d5c..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 @@ -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 @@ -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/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/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 502e13c2..04375dbb 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(), @@ -4559,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_333); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 364); + 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, @@ -4571,47 +4569,49 @@ 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, 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 + 694 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 417 + 425 ); 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), ("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"], @@ -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!( @@ -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/completion.rs b/tools/dynwinrt-codegen/src/codegen/com/completion.rs new file mode 100644 index 00000000..8ede1af6 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/completion.rs @@ -0,0 +1,331 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Exact metadata relationship and projection for the first native one-shot +//! consumer. DLL exports are not represented as fake COM vtable methods. + +use crate::com_metadata::{ComInterfaceMeta, RawComMethod, completion::*, raw_method_shape}; + +use super::{ + ComGeneratedOutput, + ir::{ + NativeCompletionHandler, NativeCompletionResult, NativeCompletionResultParameter, + NativeCompletionStartParameter, ProjectedNativeCompletion, + }, +}; + +const HANDLER_IID: &str = "41d949ab-9862-444a-80f6-c261334da5eb"; +const OPERATION_IID: &str = "72a22d78-cde4-431d-b8cc-843a71199b6d"; +const TARGETS: [(&str, &str, &str); 2] = [ + ( + AUDIO_NAMESPACE, + "IAudioClient", + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + ), + ( + "Windows.Win32.Media.Audio.Endpoints", + "IAudioEndpointVolume", + "5cdf2c82-841e-4546-9722-0cf74078229a", + ), +]; +const START_SHAPE: &str = "Windows.Win32.Media.Audio.Apis!ActivateAudioInterfaceAsync:MMDevAPI.dll:system:true(deviceInterfacePath:In:false:true:Windows.Win32.Foundation.PWSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,riid:In:false:true:System.Guid[Unknown]/ptr1/Mutable,activationParams:In:true:false:Windows.Win32.System.Com.StructuredStorage.PROPVARIANT[Struct]/ptr1/Mutable,completionHandler:In:false:false:Windows.Win32.Media.Audio.IActivateAudioInterfaceCompletionHandler[Interface]{41d949ab-9862-444a-80f6-c261334da5eb}/ptr0/Unspecified,activationOperation:Out:false:false:Windows.Win32.Media.Audio.IActivateAudioInterfaceAsyncOperation[Interface]{72a22d78-cde4-431d-b8cc-843a71199b6d}/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:semantic=false"; +const HANDLER_SHAPE: &str = "ActivateCompleted@3(activateOperation:in:required:noconstattr:Windows.Win32.Media.Audio.IActivateAudioInterfaceAsyncOperation[Interface]{72a22d78-cde4-431d-b8cc-843a71199b6d}/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next"; +const RESULT_SHAPE: &str = "GetActivateResult@3(activateResult:out:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr1/Mutable/underlying=i32/ptr0/Unspecified,activatedInterface:out:required:noconstattr:Windows.Win32.System.Com.IUnknown[Interface]{00000000-0000-0000-c000-000000000046}/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next"; + +fn validate_interface<'a>( + interface: &'a ComInterfaceMeta, + name: &str, + iid: &str, + shape: &str, +) -> Result<&'a RawComMethod, String> { + let raw = interface.raw_methods.as_deref().unwrap_or_default(); + if interface.interface.namespace != AUDIO_NAMESPACE + || interface.interface.name != name + || interface.interface.iid != iid + || !interface.is_iunknown_rooted + || interface.base_offset != 3 + || interface.own_methods_start != 3 + || interface.base_chain != ["IUnknown"] + || !interface.base_iids.is_empty() + || interface.interface.generic_piid.is_some() + || !interface.interface.generic_args.is_empty() + || interface.interface.methods.len() != 1 + || raw.len() != 1 + { + return Err(format!( + "Native completion interface identity/inheritance drift: {name}" + )); + } + let raw = &raw[0]; + if raw.declaring_namespace != AUDIO_NAMESPACE + || raw.declaring_interface != name + || raw.declaring_iid != iid + || raw_method_shape(raw) != shape + || raw.exact_contract.is_some() + || raw.exact_interface_output_call.is_some() + || !raw.interface_replacement_contracts.is_empty() + || !raw.output_ownership_contracts.is_empty() + || !raw.exact_null_input_contracts.is_empty() + || !raw.exact_parameter_direction_contracts.is_empty() + || raw.safe_array_contract_error.is_some() + || raw.params.iter().any(|param| { + param.exact_interface_output.is_some() || param.safe_array_evidence.is_some() + }) + { + return Err(format!("Native completion method contract drift: {name}")); + } + Ok(raw) +} + +pub fn validate_audio_completion(facts: &AudioCompletionFacts) -> Result<(), String> { + if facts.start.name != AUDIO_EXPORT + || facts.start.shape() != START_SHAPE + || facts.start.params.iter().any(|param| { + param.native_array.is_some() + || param.string_pointer_array.is_some() + || param.free_with.is_some() + || param.safe_array_evidence.is_some() + || param.exact_interface_output.is_some() + }) + { + return Err( + "Native completion DLL export contract drift: ActivateAudioInterfaceAsync".into(), + ); + } + validate_interface(&facts.handler, HANDLER_NAME, HANDLER_IID, HANDLER_SHAPE)?; + validate_interface( + &facts.operation, + OPERATION_NAME, + OPERATION_IID, + RESULT_SHAPE, + )?; + if facts.targets.len() != TARGETS.len() { + return Err("Native audio completion target set drift".into()); + } + for (interface, (namespace, name, iid)) in facts.targets.iter().zip(TARGETS) { + if interface.interface.namespace != namespace + || interface.interface.name != name + || interface.interface.iid != iid + || !interface.is_iunknown_rooted + || interface.raw_methods.is_none() + { + return Err(format!( + "Native audio completion target identity drift: {name}" + )); + } + } + Ok(()) +} + +fn project(facts: &AudioCompletionFacts) -> Result { + validate_audio_completion(facts)?; + Ok(ProjectedNativeCompletion { + namespace: AUDIO_NAMESPACE, + function_name: "activateAudioInterfaceAsync", + version: 1, + kind: "audio-activation", + library: facts.start.dll.clone(), + export: facts.start.entry_point.clone(), + calling_convention: "system", + has_this: false, + start_parameters: vec![ + NativeCompletionStartParameter::Utf16Path, + NativeCompletionStartParameter::RefIid, + NativeCompletionStartParameter::NullPropVariant, + NativeCompletionStartParameter::NativeSignal, + NativeCompletionStartParameter::OwnedOperation, + ], + handler: NativeCompletionHandler { + iid: facts.handler.interface.iid.clone(), + root: "IUnknown", + slot: facts.handler.raw_methods.as_ref().unwrap()[0].vtable_index, + input: "borrowed-operation", + return_type: "hresult", + }, + result: NativeCompletionResult { + iid: facts.operation.interface.iid.clone(), + root: "IUnknown", + slot: facts.operation.raw_methods.as_ref().unwrap()[0].vtable_index, + // GetActivateResult docs supply pointee nullability on inner + // failure; winmd's required flag describes the receiving cell. + outputs: vec![ + NativeCompletionResultParameter::Hresult, + NativeCompletionResultParameter::NullableOwnedInterface, + ], + return_type: "hresult", + }, + allowed_targets: facts + .targets + .iter() + .map(|target| target.interface.iid.clone()) + .collect(), + }) +} + +pub fn generate_audio_completion_files(winmd_paths: &str) -> Result { + let facts = parse_audio_completion(winmd_paths)?; + let projected = project(&facts)?; + let mut output = super::javascript::render::render_native_completion(&projected)?; + // Validate and emit every method of each result projection. A partially + // supported result type must not become a safe entry point. + let mut extras = std::collections::BTreeMap::new(); + for target in &facts.targets { + let files = super::generate_com_interface_files(target, winmd_paths)?; + let module = + super::canonical_module_path(&target.interface.namespace, &target.interface.name)?; + extras.insert(format!("{module}.js"), files.js); + extras.insert(format!("{module}.d.ts"), files.dts); + for (path, content) in files.extra_files { + if let Some(existing) = extras.insert(path.clone(), content.clone()) + && existing != content + { + return Err(format!("Conflicting native completion dependency: {path}")); + } + } + } + output.extra_files = extras.into_iter().collect(); + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::com_metadata::{RawNativeType, RawParamDirection}; + + #[test] + fn native_completion_projection_and_rendering_have_explicit_roles() { + let plan = ProjectedNativeCompletion { + namespace: AUDIO_NAMESPACE, + function_name: "renamedActivation", + version: 1, + kind: "audio-activation", + library: "MMDevAPI.dll".into(), + export: AUDIO_EXPORT.into(), + calling_convention: "system", + has_this: false, + start_parameters: vec![ + NativeCompletionStartParameter::Utf16Path, + NativeCompletionStartParameter::RefIid, + NativeCompletionStartParameter::NullPropVariant, + NativeCompletionStartParameter::NativeSignal, + NativeCompletionStartParameter::OwnedOperation, + ], + handler: NativeCompletionHandler { + iid: HANDLER_IID.into(), + root: "IUnknown", + slot: 3, + input: "borrowed-operation", + return_type: "hresult", + }, + result: NativeCompletionResult { + iid: OPERATION_IID.into(), + root: "IUnknown", + slot: 3, + outputs: vec![ + NativeCompletionResultParameter::Hresult, + NativeCompletionResultParameter::NullableOwnedInterface, + ], + return_type: "hresult", + }, + allowed_targets: TARGETS.iter().map(|(_, _, iid)| iid.to_string()).collect(), + }; + let descriptor = serde_json::to_value(&plan).unwrap(); + assert_eq!( + descriptor["start_parameters"], + serde_json::json!([ + "utf16-path", + "ref-iid", + "null-prop-variant", + "native-signal", + "owned-operation", + ]) + ); + assert_eq!( + descriptor["result"]["outputs"], + serde_json::json!(["hresult", "nullable-owned-interface"]) + ); + assert!(descriptor.get("function_name").is_none()); + let rendered = super::super::javascript::render::render_native_completion(&plan).unwrap(); + assert!( + rendered + .js + .contains("exports.renamedActivation = renamedActivation") + ); + assert!(rendered.js.contains("arguments.length !== 2")); + assert!(rendered.dts.contains("renamedActivation")); + assert!(rendered.dts.contains("Promise")); + } + + #[test] + fn exact_winmd_completion_relationship_and_fail_closed_drift() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let facts = parse_audio_completion(&winmd).unwrap(); + validate_audio_completion(&facts).unwrap(); + let output = generate_audio_completion_files(&winmd).unwrap(); + assert!(output.js.contains("exports.activateAudioInterfaceAsync")); + assert!(output.js.contains("\\\"has_this\\\":false")); + assert!(output.js.contains("null-prop-variant")); + assert!(output.js.contains("nullable-owned-interface")); + assert!(output.dts.contains("Promise")); + assert!(!output.js.contains("IAsyncInfo")); + assert!(!output.js.contains("implement(")); + assert!( + output + .extra_files + .iter() + .any(|(name, _)| name.ends_with("/IAudioClient.js")) + ); + assert!( + output + .extra_files + .iter() + .any(|(name, _)| name.ends_with("/IAudioEndpointVolume.js")) + ); + let reject = |mutate: fn(&mut AudioCompletionFacts)| { + let mut changed = facts.clone(); + mutate(&mut changed); + assert!(validate_audio_completion(&changed).is_err()); + }; + let mutations: &[fn(&mut AudioCompletionFacts)] = &[ + |f: &mut AudioCompletionFacts| f.start.is_static = false, + |f| f.start.calling_convention = "cdecl".into(), + |f| f.start.dll = "untrusted.dll".into(), + |f| f.start.entry_point = "Other".into(), + |f| f.start.params.swap(0, 1), + |f| f.start.params[1].typ.pointer_depth = 0, + |f| f.start.params[2].optional = false, + |f| f.start.params[2].typ.pointer_depth = 2, + |f| f.start.params[3].direction = RawParamDirection::Out, + |f| f.start.params[4].typ.pointer_depth = 0, + |f| f.start.semantic_hresult = true, + |f| f.start.return_type.native_type = RawNativeType::Void, + |f| f.handler.base_chain.push("IForeign".into()), + |f| f.handler.interface.iid = OPERATION_IID.into(), + |f| f.handler.raw_methods.as_mut().unwrap()[0].vtable_index = 4, + |f| f.handler.raw_methods.as_mut().unwrap()[0].params[0].optional = true, + |f| { + f.operation.raw_methods.as_mut().unwrap()[0].params[0] + .typ + .pointer_depth = 0 + }, + |f| f.operation.raw_methods.as_mut().unwrap()[0].params[1].optional = true, + |f| { + f.operation.raw_methods.as_mut().unwrap()[0].params[1] + .typ + .pointer_depth = 2 + }, + |f| { + f.operation + .interface + .methods + .push(f.operation.interface.methods[0].clone()) + }, + |f| f.targets[0].interface.iid = HANDLER_IID.into(), + ]; + for mutate in mutations { + reject(*mutate); + } + } +} 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 handler: NativeCompletionHandler, + pub result: NativeCompletionResult, + pub allowed_targets: Vec, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "kebab-case")] +pub(super) enum NativeCompletionStartParameter { + Utf16Path, + RefIid, + NullPropVariant, + NativeSignal, + OwnedOperation, +} + +#[derive(Debug, serde::Serialize)] +pub(super) struct NativeCompletionHandler { + pub iid: String, + pub root: &'static str, + pub slot: usize, + pub input: &'static str, + pub return_type: &'static str, +} + +#[derive(Debug, serde::Serialize)] +pub(super) struct NativeCompletionResult { + pub iid: String, + pub root: &'static str, + pub slot: usize, + pub outputs: Vec, + pub return_type: &'static str, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "kebab-case")] +pub(super) enum NativeCompletionResultParameter { + Hresult, + NullableOwnedInterface, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum ComPrimitive { Bool, @@ -487,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, @@ -566,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), @@ -674,9 +728,48 @@ pub(super) struct ProjectedComInterface { pub(super) activation: ActivationPlan, pub(super) referenced_enums: Vec, 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 04c42fe8..82cad9c5 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -33,6 +33,45 @@ pub struct ComGeneratedOutput { pub extra_files: Vec<(String, String)>, } +pub(in crate::codegen::com) fn render_native_completion( + plan: &super::super::ir::ProjectedNativeCompletion, +) -> Result { + let descriptor = serde_json::to_string(plan).map_err(|error| error.to_string())?; + let descriptor_literal = + serde_json::to_string(&descriptor).map_err(|error| error.to_string())?; + let import = com_runtime_import_name_for_module(plan.namespace); + let import = serde_json::to_string(&import).map_err(|error| error.to_string())?; + let function_name = plan.function_name; + let js = format!( + "// Generated by dynwinrt-codegen — do not edit\n\ + 'use strict';\n\ + const {{ __activateAudioInterfaceAsync }} = require({import});\n\ + const descriptor = {descriptor_literal};\n\ + async function {function_name}(deviceInterfacePath, InterfaceClass) {{\n\ + if (arguments.length !== 2) throw new TypeError('Native audio activation requires exactly a device path and generated interface class; custom activation parameters are unsupported');\n\ + return __activateAudioInterfaceAsync(descriptor, deviceInterfacePath, InterfaceClass);\n\ + }}\n\ + exports.{function_name} = {function_name};\n" + ); + let public_import = super::super::rebase_runtime_import( + com_public_import_name(), + super::super::canonical_namespace_depth(plan.namespace), + ); + let dts = format!( + "// Generated by dynwinrt-codegen — do not edit\n\ + import type {{ ComInterfaceType }} from '{public_import}';\n\ + /** Native one-shot activation on the caller's COM apartment. NULL activation parameters only.\n\ + * Targets: IAudioClient and IAudioEndpointVolume. May require UI-thread consent.\n\ + * Dropping the Promise does not cancel the Windows operation. */\n\ + export declare function {function_name}(deviceInterfacePath: string, InterfaceClass: ComInterfaceType): Promise;\n" + ); + Ok(ComGeneratedOutput { + js, + dts, + extra_files: Vec::new(), + }) +} + pub(in crate::codegen::com) fn render_com_interface( meta: &ProjectedComInterface, ) -> Result { @@ -213,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 { @@ -222,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); @@ -323,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::(); @@ -375,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 { .. } => {} @@ -2269,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 { @@ -2453,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 fee38fd7..84045cbf 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -4,6 +4,7 @@ //! Classic-COM metadata projection and JavaScript generation. pub mod capability; +mod completion; mod generated_unsafe; mod ir; mod javascript; @@ -13,6 +14,7 @@ mod typedef_inventory; use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; +pub use completion::{generate_audio_completion_files, validate_audio_completion}; pub use generated_unsafe::{ Stage2Coverage, UNSAFE_SUPPORT_SCHEMA_VERSION, UnsafeGeneratedOutput, UnsafeInterfaceSupport, generate_unsafe_interface_files, generate_unsafe_interface_files_with_metadata, @@ -152,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") @@ -178,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..50f44379 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/borrowed.rs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::com_metadata::{ComInterfaceMeta, borrowed as evidence}; +use dynwinrt_com_contracts::{BorrowedCopyContract, registry}; + +pub(in crate::codegen::com) struct ValidatedStorage { + pub copy: Option, + 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); + 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); + } + } + } + Ok(Some(ValidatedStorage { + copy, + effects, + dependencies, + })) +} 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..c80c037a --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/project/borrowed.rs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::super::{ + ir::{ + CopyArguments, CopyResult, ProjectedBorrowedCopy, ProjectedBorrowedOperation, + ProjectedBorrowedStorage, + }, + 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(|copy| copy.copy_only); + let context_effects = storage + .effects + .into_iter() + .map(|(slot, evidence)| { + Ok(( + slot, + serde_json::to_string(&serde_json::json!({ + "version": 1, + "effect": evidence.effect.as_deref(), + "metadata_sha256": crate::com_metadata::borrowed::METADATA_SHA256, + "fingerprint": evidence.fingerprint, + })) + .map_err(|error| error.to_string())?, + )) + }) + .collect::>()?; + let copy = storage + .copy + .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, + }) + }) + .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}; + + 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 { + 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(); + compare_public_baseline(name, &output.dts); + 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(); + compare_public_baseline(name, &output.dts); + 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..bf202882 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)?; @@ -3155,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(); @@ -3171,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 { @@ -3188,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; } } @@ -3206,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| { @@ -3229,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); + } } } @@ -3275,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 { @@ -3755,6 +4034,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 +4180,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 +4216,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..f477a118 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_borrowed_metadata.rs @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! 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}; + +#[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 fn all_evidence() -> &'static [Evidence] { + ®istry().evidence +} + +pub(crate) fn catalog_entry(entry: &Evidence) -> ExactRegistryEntry { + let family = if entry.effect.is_some() { + ExactFamilyId::AudioContext + } else { + ExactFamilyId::BorrowedCopy + }; + 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 { + "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 = all_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) +} + +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 { + candidate(meta).is_some_and(|entry| entry.context) +} + +pub fn is_bounded_copy(meta: &ComInterfaceMeta) -> bool { + // 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 { + 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 !candidate(meta).is_some_and(|entry| entry.catalog) { + return vec![]; + } + meta.raw_methods + .as_deref() + .unwrap_or_default() + .iter() + .filter_map(|raw| evidence_for(raw).ok().flatten()) + .map(catalog_entry) + .collect() +} + +pub fn require_metadata_hash(paths: &str) -> Result<(), String> { + 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 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 != entry.iid + || !meta.is_iunknown_rooted + || meta.base_offset != 3 + || 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() != entry.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 evidence = evidence_for(raw)?; + if (!entry.context || entry.required_evidence.contains(&raw.vtable_index)) + && evidence.is_none() + { + return Err(format!( + "Absent borrowed-storage/context evidence at slot {}", + raw.vtable_index + )); + } + } + 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 = "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]) + .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_completion_metadata.rs b/tools/dynwinrt-codegen/src/com_completion_metadata.rs new file mode 100644 index 00000000..acec3ba0 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_completion_metadata.rs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Raw metadata for the bounded DLL-export / native-completion relationship. + +use super::*; + +pub const AUDIO_NAMESPACE: &str = "Windows.Win32.Media.Audio"; +pub const AUDIO_EXPORT: &str = "ActivateAudioInterfaceAsync"; +pub const HANDLER_NAME: &str = "IActivateAudioInterfaceCompletionHandler"; +pub const OPERATION_NAME: &str = "IActivateAudioInterfaceAsyncOperation"; + +#[derive(Debug, Clone)] +pub struct RawCompletionExport { + pub namespace: String, + pub container: String, + pub name: String, + pub dll: String, + pub entry_point: String, + pub calling_convention: String, + pub is_static: bool, + pub params: Vec, + pub return_type: RawComType, + pub semantic_hresult: bool, +} + +impl RawCompletionExport { + pub fn shape(&self) -> String { + let params = self + .params + .iter() + .map(|param| { + let mut typ = String::new(); + push_raw_type_shape(&mut typ, ¶m.typ); + format!( + "{}:{:?}:{}:{}:{typ}", + param.name, param.direction, param.optional, param.const_attribute, + ) + }) + .collect::>() + .join(","); + let mut result = String::new(); + push_raw_type_shape(&mut result, &self.return_type); + format!( + "{}.{}!{}:{}:{}:{}({params})->{result}:semantic={}", + self.namespace, + self.container, + self.entry_point, + self.dll, + self.calling_convention, + self.is_static, + self.semantic_hresult, + ) + } +} + +#[derive(Debug, Clone)] +pub struct AudioCompletionFacts { + pub start: RawCompletionExport, + pub handler: ComInterfaceMeta, + pub operation: ComInterfaceMeta, + pub targets: Vec, +} + +pub fn parse_audio_completion(winmd_paths: &str) -> Result { + let index = crate::meta::load_index(winmd_paths) + .ok_or("Cannot load metadata for native audio completion")?; + let definitions = index.get(AUDIO_NAMESPACE, "Apis").collect::>(); + let candidates = definitions + .iter() + .flat_map(|def| def.methods()) + .filter(|method| method.name() == AUDIO_EXPORT) + .collect::>(); + let [method] = candidates.as_slice() else { + return Err("Expected exactly one Audio.Apis.ActivateAudioInterfaceAsync export".into()); + }; + let import = method + .impl_map() + .ok_or("Audio activation is not a DLL export")?; + let signature = method.signature(&[]); + let parameters = method + .params() + .filter(|param| param.sequence() > 0) + .collect::>(); + if parameters.len() != signature.types.len() { + return Err("Incomplete audio activation parameter metadata".into()); + } + let params = parameters + .iter() + .zip(&signature.types) + .map(|(param, typ)| { + if param.has_attribute("NativeArrayInfoAttribute") + || param.has_attribute("FreeWithAttribute") + { + return Err("Unexpected array or allocator on audio activation input".into()); + } + Ok(RawComParam { + name: param.name().into(), + typ: map_raw_com_type(typ, &index), + direction: raw_param_direction(param.flags()), + optional: param + .flags() + .contains(windows_metadata::ParamAttributes::Optional), + const_attribute: param.has_attribute("ConstAttribute"), + native_array: None, + string_pointer_array: None, + free_with: None, + safe_array_evidence: None, + exact_interface_output: None, + }) + }) + .collect::, String>>()?; + let interface = |name: &str, namespace: &str| { + parse_com_interface_from_index(&index, namespace, name) + .ok_or_else(|| format!("Missing native completion interface {namespace}.{name}")) + }; + Ok(AudioCompletionFacts { + start: RawCompletionExport { + namespace: AUDIO_NAMESPACE.into(), + container: "Apis".into(), + name: method.name().into(), + dll: import.import_scope().name().into(), + entry_point: import.import_name().into(), + calling_convention: method.calling_convention().into(), + is_static: signature.flags == windows_metadata::MethodCallAttributes::default(), + params, + return_type: map_raw_com_type(&signature.return_type, &index), + semantic_hresult: method.has_attribute("CanReturnMultipleSuccessValuesAttribute"), + }, + handler: interface(HANDLER_NAME, AUDIO_NAMESPACE)?, + operation: interface(OPERATION_NAME, AUDIO_NAMESPACE)?, + targets: vec![ + interface("IAudioClient", AUDIO_NAMESPACE)?, + interface( + "IAudioEndpointVolume", + "Windows.Win32.Media.Audio.Endpoints", + )?, + ], + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn audio_completion_metadata_shape() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let facts = parse_audio_completion(&winmd).unwrap(); + assert!(facts.start.is_static); + assert_eq!(facts.start.params.len(), 5); + assert_eq!(facts.start.calling_convention, "system"); + assert_eq!(facts.start.dll, "MMDevAPI.dll"); + assert_eq!(facts.handler.base_chain, ["IUnknown"]); + assert_eq!(facts.operation.base_chain, ["IUnknown"]); + assert_eq!(facts.handler.raw_methods.as_ref().unwrap().len(), 1); + assert_eq!(facts.operation.raw_methods.as_ref().unwrap().len(), 1); + assert_eq!(facts.targets.len(), 2); + } +} diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index d6e1de79..5cfe34d7 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -11,6 +11,11 @@ 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; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RawConstness { Const, @@ -1186,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() { @@ -1294,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..801823cc 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::all_evidence() + .iter() + .map(|entry| crate::com_metadata::borrowed::catalog_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 1a7a1a3b..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 = 3; +const COM_MANIFEST_VERSION: u32 = 5; #[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(), @@ -525,7 +525,14 @@ fn run() -> Result<(), String> { let mut requested_winrt_interfaces = Vec::new(); let mut com_interfaces: Vec = Vec::new(); let mut com_coclasses: Vec = Vec::new(); + let mut native_audio_completion = false; for (ns, cls) in &class_requests { + if ns == com_metadata::completion::AUDIO_NAMESPACE + && cls == com_metadata::completion::AUDIO_EXPORT + { + native_audio_completion = true; + continue; + } if let Some(com_iface) = com_metadata::parse_com_interface(&winmd, ns, cls) { // Route through classic-COM path when: // 1) The interface is IUnknown-rooted (base +3), OR @@ -585,8 +592,15 @@ fn run() -> Result<(), String> { // JS files into a Python output directory would produce the // wrong artifact types with no diagnostic. Reject the // combination up front. - if lang != "js" && (!com_interfaces.is_empty() || !com_coclasses.is_empty()) { + if lang != "js" + && (!com_interfaces.is_empty() + || !com_coclasses.is_empty() + || native_audio_completion) + { let mut offenders: Vec = Vec::new(); + if native_audio_completion { + offenders.push("Windows.Win32.Media.Audio.ActivateAudioInterfaceAsync (native COM completion)".into()); + } for ci in &com_interfaces { offenders.push(format!( "{}.{} (classic-COM interface)", @@ -613,7 +627,10 @@ fn run() -> Result<(), String> { // Classic COM occupies its own ESM subpackage so its symbols // cannot collide with or leak into the WinRT root barrel. - if !com_interfaces.is_empty() || !com_coclasses.is_empty() { + if !com_interfaces.is_empty() + || !com_coclasses.is_empty() + || native_audio_completion + { let com_output_dir = output_dir.join("com"); let mut unsafe_metadata = None; @@ -627,6 +644,26 @@ fn run() -> Result<(), String> { // delete anything here. let mut generated = Vec::with_capacity(com_interfaces.len() + com_coclasses.len()); + if native_audio_completion { + let out = com::generate_audio_completion_files(&winmd)?; + let module = com::canonical_module_path( + com_metadata::completion::AUDIO_NAMESPACE, + com_metadata::completion::AUDIO_EXPORT, + )?; + let mut files = vec![ + (format!("{module}.js"), out.js), + (format!("{module}.d.ts"), out.dts), + ]; + files.extend(out.extra_files); + generated.push(PlannedComRoot { + root: "Windows.Win32.Media.Audio.ActivateAudioInterfaceAsync".into(), + name: com_metadata::completion::AUDIO_EXPORT.into(), + files, + unsafe_support: None, + summary: None, + no_callable_error: None, + }); + } for com_iface in &com_interfaces { let root = format!( "{}.{}", @@ -8961,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, 4] { + 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"); @@ -8968,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}" ); 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) + ); +} From 4a9d0db2708ce4aaac2b69b1df1f0f34ef0aa04b Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Wed, 9 Sep 2026 10:11:00 +0800 Subject: [PATCH 4/4] Make COM declaration tests independent of built JS artifacts Share the isolated COM runtime declaration fixture between overload and sink tests. Keep strict TypeScript and negative assertions while removing the coverage-time dependency on bindings/js/dist. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .../tests/com_explicit_overload_test.rs | 12 +++--- .../tests/com_sink_tsc_check_test.rs | 36 ++-------------- tools/dynwinrt-codegen/tests/support/mod.rs | 43 +++++++++++++++++++ 3 files changed, 51 insertions(+), 40 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/support/mod.rs diff --git a/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs index a0a4c40b..4a0da177 100644 --- a/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs +++ b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs @@ -4,6 +4,8 @@ use dynwinrt_codegen::{codegen::com, com_metadata}; use std::{fs, path::Path, process::Command}; +mod support; + #[test] fn ambiguous_native_overloads_expose_exact_callable_slots() { let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { @@ -152,18 +154,14 @@ fn generated_explicit_overload_declarations_typecheck() { ), ) .unwrap(); + support::write_com_runtime_stub(&output); 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")] - } + "types": [] }, - "include": ["usage.ts", "com/**/*.d.ts"] + "include": ["globals.d.ts", "usage.ts", "com/**/*.d.ts"] }); fs::write( output.join("tsconfig.json"), diff --git a/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs b/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs index 3f6a469b..4c0adf05 100644 --- a/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs @@ -5,6 +5,8 @@ use std::fs; use std::path::Path; use std::process::Command; +mod support; + #[test] fn generated_com_sink_dts_passes_tsc_no_emit() { let winmd = std::env::var("DYNWINRT_WIN32_WINMD") @@ -144,11 +146,7 @@ composed.release(); "#, ) .expect("write COM sink usage"); - fs::write( - tmp.join("globals.d.ts"), - "declare class Buffer extends Uint8Array {}\n", - ) - .expect("write Buffer stub"); + support::write_com_runtime_stub(&tmp); fs::write( tmp.join("tsconfig.json"), r#"{ @@ -166,34 +164,6 @@ composed.release(); ) .expect("write COM sink tsconfig"); - let package = tmp.join("node_modules").join("@microsoft").join("dynwinrt"); - fs::create_dir_all(&package).expect("create COM runtime stub"); - fs::write( - package.join("package.json"), - r#"{ - "name": "@microsoft/dynwinrt", - "version": "0.0.0", - "exports": { - "./com": { - "types": "./com.d.ts" - } - } -}"#, - ) - .expect("write COM runtime package stub"); - fs::write( - package.join("com.d.ts"), - r#"export declare class WinGuid {} -export interface DynComImplementation {} -export declare class DynWinRtValue { - isNull(): boolean; -} -export declare class DynComNativeStruct {} -export declare class DynComNativeStructArray {} -"#, - ) - .expect("write COM runtime declarations"); - let output = Command::new("cmd") .arg("/c") .arg(&tsc) diff --git a/tools/dynwinrt-codegen/tests/support/mod.rs b/tools/dynwinrt-codegen/tests/support/mod.rs new file mode 100644 index 00000000..53992823 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/support/mod.rs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{fs, path::Path}; + +// Declaration tests run before the native addon is built in coverage CI. +pub fn write_com_runtime_stub(output: &Path) { + fs::write( + output.join("globals.d.ts"), + "declare class Buffer extends Uint8Array {}\n", + ) + .expect("write Buffer stub"); + let package = output + .join("node_modules") + .join("@microsoft") + .join("dynwinrt"); + fs::create_dir_all(&package).expect("create COM runtime stub"); + fs::write( + package.join("package.json"), + r#"{ + "name": "@microsoft/dynwinrt", + "version": "0.0.0", + "exports": { + "./com": { + "types": "./com.d.ts" + } + } +}"#, + ) + .expect("write COM runtime package stub"); + fs::write( + package.join("com.d.ts"), + r#"export declare class WinGuid {} +export interface DynComImplementation {} +export declare class DynWinRtValue { + isNull(): boolean; +} +export declare class DynComNativeStruct {} +export declare class DynComNativeStructArray {} +"#, + ) + .expect("write COM runtime declarations"); +}