diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 44e6b1c7..aba06be1 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 5681) { + if ($result.complete_interfaces -lt 5691) { 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 5681) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5691) { 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 5681 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2248 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5691 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2238 ) { throw "Classic COM compact interface support index changed" } $expected = @{ - x64 = @(412, 1446, 390) - i686 = @(411, 1423, 414) - arm64 = @(412, 1446, 390) + x64 = @(412, 1437, 389) + i686 = @(411, 1414, 413) + arm64 = @(412, 1437, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -134,16 +134,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5681 -or - $result.safeEvidence.standardDerived -ne 5326 -or - $result.safeEvidence.exactRegistryDependent -ne 355 -or - $result.safeEvidence.metadataFactOccurrences -ne 5974 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26076 -or - $result.safeEvidence.registeredExactEntries -ne 495 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 495 -or - $result.safeEvidence.safeConsumedExactEntries -ne 404 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 655 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 404 + $result.safeEvidence.safeComplete -ne 5691 -or + $result.safeEvidence.standardDerived -ne 5333 -or + $result.safeEvidence.exactRegistryDependent -ne 358 -or + $result.safeEvidence.metadataFactOccurrences -ne 5976 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26114 -or + $result.safeEvidence.registeredExactEntries -ne 499 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 499 -or + $result.safeEvidence.safeConsumedExactEntries -ne 408 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 660 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 408 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/README.md b/README.md index 3d258f4a..a5ad2321 100644 --- a/README.md +++ b/README.md @@ -142,11 +142,12 @@ 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,681 of 7,929 -eligible interfaces (71.65%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,691 of 7,929 +eligible interfaces (71.77%)** 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, and +BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, the +target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, and synchronous JavaScript implementations of fully supported callback interfaces. Seventeen stock-Windows Node E2E runners exercise representative Shell, Automation, stream, callback, HWND, and WinRT interop scenarios. @@ -154,8 +155,9 @@ Automation, stream, callback, HWND, and WinRT interop scenarios. Safety takes priority over coverage. If metadata does not fully describe an interface's ABI, layout, ownership, allocator, or cleanup contract, generation fails before emitting a partial wrapper. Material gaps still include several -common graphics, audio, WMI, clipboard/drag-and-drop, derived Automation, union, -BYREF/InOut, and output-ownership shapes. +common graphics, audio, WMI, non-HGLOBAL/device-specific clipboard and +drag-and-drop, derived Automation, union, BYREF/InOut, and output-ownership +shapes. Classic COM generation currently emits JavaScript and TypeScript only. It uses the separate `@microsoft/dynwinrt/com` public surface; generated wrappers call diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index e9a36d74..c6ab1f1a 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 WMI and unsafe Audio 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.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', '--output', output, ] @@ -88,6 +88,9 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr t.is(readFileSync(sentinel, 'utf8'), 'outside-target-must-survive') const wbemBase = join(output, 'com', 'windows', 'win32', 'system', 'wmi', 'IWbemServices') + const dataObjectBase = join(output, 'com', 'windows', 'win32', 'system', 'com', 'IDataObject') + const oleCacheBase = join(output, 'com', 'windows', 'win32', 'system', 'ole', 'IOleCache') + const oleCache2Base = join(output, 'com', 'windows', 'win32', 'system', 'ole', 'IOleCache2') const wbemCallResultBase = join(output, 'com', 'windows', 'win32', 'system', 'wmi', 'IWbemCallResult') const wbemClassObjectBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'system', 'wmi', 'IWbemClassObjectUnsafe') const thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') @@ -100,10 +103,14 @@ test.serial('generated safe WMI and unsafe Audio 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 { DynComFormatEtc, DynComStgMedium } = 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', `const wbem = require(${JSON.stringify(`${wbemBase}.js`)})`, + `const dataObject = require(${JSON.stringify(`${dataObjectBase}.js`)})`, + `const oleCache = require(${JSON.stringify(`${oleCacheBase}.js`)})`, + `const oleCache2 = require(${JSON.stringify(`${oleCache2Base}.js`)})`, `const wbemCallResult = require(${JSON.stringify(`${wbemCallResultBase}.js`)})`, `const wbemClassObject = require(${JSON.stringify(`${wbemClassObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, @@ -124,6 +131,9 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '}', 'async function main() {', ` const esmWbem = await import(pathToFileURL(${JSON.stringify(`${wbemBase}.js`)}).href)`, + ` const esmDataObject = await import(pathToFileURL(${JSON.stringify(`${dataObjectBase}.js`)}).href)`, + ` const esmOleCache = await import(pathToFileURL(${JSON.stringify(`${oleCacheBase}.js`)}).href)`, + ` const esmOleCache2 = await import(pathToFileURL(${JSON.stringify(`${oleCache2Base}.js`)}).href)`, ` const esmWbemCallResult = await import(pathToFileURL(${JSON.stringify(`${wbemCallResultBase}.js`)}).href)`, ` const esmWbemClassObject = await import(pathToFileURL(${JSON.stringify(`${wbemClassObjectBase}.js`)}).href)`, ` const esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, @@ -131,21 +141,32 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ` const esmSafeBarrel = await import(pathToFileURL(${JSON.stringify(join(output, 'com', 'index.mjs'))}).href)`, ` const esmBarrel = await import(pathToFileURL(${JSON.stringify(join(output, 'com', 'unsafe', 'index.mjs'))}).href)`, " assert.equal(typeof wbem.IWbemServices, 'function')", + " assert.equal(typeof dataObject.IDataObject, 'function')", + " assert.equal(typeof oleCache.IOleCache, 'function')", + " assert.equal(typeof oleCache2.IOleCache2, 'function')", " assert.equal(typeof wbemCallResult.IWbemCallResult, 'function')", " assert.equal(typeof wbemClassObject.IWbemClassObjectUnsafe, 'function')", " assert.equal(typeof thumbnail.IThumbnailProvider, 'function')", " assert.equal(typeof audio.IAudioClientUnsafe, 'function')", ' assert.equal(esmAudio.IAudioClientUnsafe, audio.IAudioClientUnsafe)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(safeBarrel.IDataObject, dataObject.IDataObject)', + ' assert.equal(safeBarrel.IOleCache, oleCache.IOleCache)', + ' assert.equal(safeBarrel.IOleCache2, oleCache2.IOleCache2)', ' assert.equal(safeBarrel.IWbemCallResult, wbemCallResult.IWbemCallResult)', ' assert.equal(safeBarrel.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(cjsBarrel.UnsafePointerOutput, UnsafePointerOutput)', ' assert.equal(cjsBarrel.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmWbem.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmDataObject.IDataObject, dataObject.IDataObject)', + ' assert.equal(esmOleCache.IOleCache, oleCache.IOleCache)', + ' assert.equal(esmOleCache2.IOleCache2, oleCache2.IOleCache2)', ' assert.equal(esmWbemCallResult.IWbemCallResult, wbemCallResult.IWbemCallResult)', ' assert.equal(esmWbemClassObject.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmSafeBarrel.IOleCache, oleCache.IOleCache)', + ' assert.equal(esmSafeBarrel.IOleCache2, oleCache2.IOleCache2)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', ' const createFake = runtime.createGeneratedIwbemServicesFake', ' const readStats = runtime.generatedUnsafeComStats', @@ -275,6 +296,105 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' thumbnailWrapper?.release()', ' thumbnailFake?.release()', ' }', + ' const createDataObject = runtime.createGeneratedDataObjectFake', + ' const dataObjectStats = runtime.generatedDataObjectStats', + ' const setCanonicalMode = runtime.setGeneratedDataObjectCanonicalMode', + " assert.equal(typeof setCanonicalMode, 'function')", + ' let dataObjectFake = createDataObject()', + ' let dataObjectWrapper', + ' try {', + ' dataObjectWrapper = dataObject.IDataObject._fromNative(dataObjectFake)', + ' assert.equal(dataObjectStats().currentRefCount, 2)', + ' const format = DynComFormatEtc.hglobal(13)', + ' const medium = dataObjectWrapper.getData(format)', + ' assert.deepEqual(medium.toBuffer(), Buffer.from([1, 2, 3, 4]))', + ' assert.equal(dataObjectStats().outputReleased, true)', + ' const filled = dataObjectWrapper.getDataHere(format, DynComStgMedium.hglobal(Buffer.alloc(4)))', + ' assert.deepEqual(filled.toBuffer(), Buffer.from([9, 8, 7, 6]))', + ' assert.equal(dataObjectStats().getDataHereInputReleased, true)', + ' assert.equal(dataObjectWrapper.queryGetData(format), 0)', + ' const formatFields = value => [value.clipboardFormat, value.aspect, value.index, value.tymed]', + ' const originalFields = formatFields(format)', + ' assert.deepEqual(originalFields, [13, 1, -1, 1])', + ' for (const mode of [0, 1]) {', + ' setCanonicalMode(mode)', + ' const [canonicalResult, canonical] = dataObjectWrapper.getCanonicalFormatEtc(format)', + ' assert.equal(canonicalResult, 0)', + ' assert.ok(canonical instanceof DynComFormatEtc)', + ' assert.notEqual(canonical, format)', + ' assert.deepEqual(formatFields(canonical), [1, 4, 7, 1])', + ' assert.deepEqual(formatFields(format), originalFields)', + ' }', + ' for (const mode of [2, 3]) {', + ' setCanonicalMode(mode)', + ' const [canonicalResult, canonical] = dataObjectWrapper.getCanonicalFormatEtc(format)', + ' assert.equal(canonicalResult, 0x40130)', + ' assert.ok(canonical instanceof DynComFormatEtc)', + ' assert.notEqual(canonical, format)', + ' assert.deepEqual(formatFields(canonical), originalFields)', + ' assert.deepEqual(formatFields(format), originalFields)', + ' }', + ' setCanonicalMode(-1)', + ' assert.throws(() => dataObjectWrapper.getCanonicalFormatEtc(format), /native call failed|HRESULT|0x80004005/i)', + ' setCanonicalMode(4)', + ' assert.throws(() => dataObjectWrapper.getCanonicalFormatEtc(format), /HRESULT|canonical.*status/i)', + ' assert.deepEqual(formatFields(format), originalFields)', + ' dataObjectWrapper.setData(format, DynComStgMedium.hglobal(Buffer.from([5, 6, 7, 8])))', + ' assert.deepEqual(dataObjectStats(), { getDataCalls: 1, getDataHereCalls: 1, queryGetDataCalls: 1, canonicalCalls: 6, setDataCalls: 1, lastSetRelease: 0, outputReleased: true, getDataHereInputReleased: true, setDataInputReleased: true, currentRefCount: 2 })', + ' dataObjectWrapper.release()', + ' assert.equal(dataObjectStats().currentRefCount, 1)', + ' dataObjectFake.release()', + ' assert.equal(dataObjectStats().currentRefCount, 0)', + ' dataObjectWrapper = undefined', + ' dataObjectFake = undefined', + ' } finally {', + ' dataObjectWrapper?.release()', + ' dataObjectFake?.release()', + ' }', + ' const createOleCache = runtime.createGeneratedOleCacheFake', + ' const oleCacheStats = runtime.generatedOleCacheStats', + " assert.equal(typeof createOleCache, 'function')", + " assert.equal(typeof oleCacheStats, 'function')", + ' let oleCacheFake = createOleCache()', + ' let oleCacheUnknown', + ' let oleCacheWrapper', + ' let oleCache2Wrapper', + ' try {', + ' assert.equal(oleCacheStats().currentRefCount, 1)', + " oleCacheUnknown = oleCacheFake.cast(WinGuid.parse('00000000-0000-0000-c000-000000000046'))", + ' assert.equal(oleCacheStats().currentRefCount, 2)', + ' oleCacheUnknown.release()', + ' oleCacheUnknown = undefined', + ' assert.equal(oleCacheStats().currentRefCount, 1)', + " assert.throws(() => oleCacheFake.cast(WinGuid.parse('0000010e-0000-0000-c000-000000000046')), /interface|0x80004002/i)", + ' assert.equal(oleCacheStats().currentRefCount, 1)', + ' oleCacheWrapper = oleCache.IOleCache._fromNative(oleCacheFake)', + ' assert.equal(oleCacheStats().currentRefCount, 2)', + ' oleCache2Wrapper = oleCache2.IOleCache2._fromNative(oleCacheFake)', + ' assert.equal(oleCacheStats().currentRefCount, 3)', + ' const format = DynComFormatEtc.hglobal(13)', + ' const medium = DynComStgMedium.hglobal(Buffer.from([5, 6, 7, 8]))', + ' assert.equal(oleCacheWrapper.setData(format, medium), undefined)', + ' assert.deepEqual(oleCacheStats(), { setDataCalls: 1, borrowedInputCalls: 1, lastSetRelease: 0, setDataInputReleased: true, currentRefCount: 3 })', + ' assert.deepEqual(medium.toBuffer(), Buffer.from([5, 6, 7, 8]))', + ' oleCacheWrapper.release()', + ' oleCacheWrapper = undefined', + ' assert.equal(oleCacheStats().currentRefCount, 2)', + ' assert.equal(oleCache2Wrapper.setData(format, medium), undefined)', + ' assert.deepEqual(oleCacheStats(), { setDataCalls: 2, borrowedInputCalls: 2, lastSetRelease: 0, setDataInputReleased: true, currentRefCount: 2 })', + ' assert.deepEqual(medium.toBuffer(), Buffer.from([5, 6, 7, 8]))', + ' oleCache2Wrapper.release()', + ' oleCache2Wrapper = undefined', + ' assert.equal(oleCacheStats().currentRefCount, 1)', + ' oleCacheFake.release()', + ' oleCacheFake = undefined', + ' assert.equal(oleCacheStats().currentRefCount, 0)', + ' } finally {', + ' oleCache2Wrapper?.release()', + ' oleCacheWrapper?.release()', + ' oleCacheUnknown?.release()', + ' oleCacheFake?.release()', + ' }', ' const createAudio = runtime.createGeneratedAudioClientFake', ' const audioStats = runtime.generatedAudioClientStats', ' const setServiceMode = runtime.setGeneratedAudioClientGetServiceMode', @@ -671,15 +791,22 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr consumer, [ "import { IWbemServices } from './com/windows/win32/system/wmi/IWbemServices.js'", + "import { IDataObject } from './com/windows/win32/system/com/IDataObject.js'", + "import { IOleCache } from './com/windows/win32/system/ole/IOleCache.js'", + "import { IOleCache2 } from './com/windows/win32/system/ole/IOleCache2.js'", "import { IThumbnailProvider } from './com/windows/win32/ui/shell/IThumbnailProvider.js'", "import { IAudioClientUnsafe } from './com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js'", "import { IWbemServices as FromBarrel } from './com/index.js'", "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 { DynComFormatEtc, DynComStgMedium } from '@microsoft/dynwinrt/com'", 'declare const native: DynWinRtValue', 'declare const storage: DynComRawMemory', 'declare const thumbnails: IThumbnailProvider', + 'declare const dataObjects: IDataObject', + 'declare const oleCaches: IOleCache', + 'declare const oleCaches2: IOleCache2', 'const direct: IWbemServices = IWbemServices._fromNative(native)', 'const barrel: FromBarrel = FromBarrel._fromNative(native)', "const namespaceOutput = direct.openNamespace('root', { mode: 'sync' })", @@ -689,6 +816,23 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '// @ts-expect-error only exact registered modes are accepted', "direct.openNamespace('root', { mode: 'other' })", 'thumbnails.getThumbnail(96)[0].release()', + 'const format = DynComFormatEtc.hglobal(13)', + 'dataObjects.getData(format).toBuffer()', + 'dataObjects.getDataHere(format, DynComStgMedium.hglobal(Buffer.alloc(4))).toBuffer()', + 'const canonical: [number, DynComFormatEtc] = dataObjects.getCanonicalFormatEtc(format)', + 'const canonicalMedium: number = canonical[1].tymed', + 'void canonicalMedium', + 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', + '// @ts-expect-error SetData ownership transfer is intentionally hidden', + 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', + 'const cacheSetResult: void = oleCaches.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', + 'const cache2SetResult: void = oleCaches2.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', + 'void cacheSetResult', + 'void cache2SetResult', + '// @ts-expect-error IOleCache SetData ownership transfer is intentionally hidden', + 'oleCaches.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', + '// @ts-expect-error inherited IOleCache2 SetData ownership transfer is intentionally hidden', + 'oleCaches2.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', 'const audio = IAudioClientUnsafe.from(native)', '// @ts-expect-error strategy result types are invariant', 'const wrongOutput: UnsafePointerOutput = UnsafePointerOutput.coTaskMem()', diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index c2c072ba..bc724f88 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -23,6 +23,7 @@ import { unboxObject, } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' +import { DynComFormatEtc, DynComStgMedium } from '../dist/com.js' import * as comRuntime from '../dist/com.js' import { DynCom, @@ -149,6 +150,7 @@ test('package facades exactly partition native exports', (t) => { 'DynComDispatchParams', 'DynComAllocation', 'DynComExcepInfo', + 'DynComFormatEtc', 'DynComNativeStruct', 'DynComNativeStructArray', 'DynComNativeUnion', @@ -156,6 +158,7 @@ test('package facades exactly partition native exports', (t) => { 'DynComPropVariant', 'DynComSafeArray', 'DynComStatStg', + 'DynComStgMedium', 'DynComVariant', 'DynWinRtValue', 'WinGuid', @@ -211,6 +214,23 @@ test('package facades exactly partition native exports', (t) => { } }) +test('FORMATETC and STGMEDIUM expose a closed HGLOBAL semantic subset', (t) => { + const format = DynComFormatEtc.hglobal(13) + t.is(format.clipboardFormat, 13) + t.is(format.aspect, 1) + t.is(format.index, -1) + t.is(format.tymed, 1) + + const medium = DynComStgMedium.hglobal(Buffer.from([1, 2, 3, 4])) + t.is(medium.tymed, 1) + t.deepEqual(medium.toBuffer(), Buffer.from([1, 2, 3, 4])) + t.throws(() => DynComFormatEtc.hglobal(0), { message: /non-zero/ }) + t.throws(() => DynComFormatEtc.hglobal(0x1_0000), { message: /u16/ }) + t.throws(() => DynComFormatEtc.hglobal(13, 3), { message: /DVASPECT/ }) + t.throws(() => DynComFormatEtc.hglobal(13, 16), { message: /DVASPECT/ }) + t.throws(() => DynComStgMedium.hglobal(Buffer.alloc(0)), { message: /at least one byte/ }) +}) + test('raw COM memory and pointers expose checked owner-retaining primitives', (t) => { const pointerSize = DynComRaw.pointerSize() t.true(pointerSize === 4 || pointerSize === 8) diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index bb08c13e..6ec952e3 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -20,6 +20,7 @@ const comExports = new Set([ 'DynComDispatchParams', 'DynComAllocation', 'DynComExcepInfo', + 'DynComFormatEtc', 'DynComNativeStruct', 'DynComNativeStructArray', 'DynComNativeUnion', @@ -27,6 +28,7 @@ const comExports = new Set([ 'DynComPropVariant', 'DynComSafeArray', 'DynComStatStg', + 'DynComStgMedium', 'DynComVariant', 'DynWinRtValue', 'WinGuid', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 264bb176..8530df0c 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -40,6 +40,8 @@ enum AutomationValueKind { DispatchParams(dynwinrt::com::DispatchParamsValue), ExcepInfo(dynwinrt::com::ExcepInfoValue), StatStg(dynwinrt::com::StatStgValue), + FormatEtc(dynwinrt::com::FormatEtcValue), + StgMedium(dynwinrt::com::StgMediumValue), } pub(super) struct AutomationValue { @@ -58,6 +60,8 @@ impl AutomationValue { dynwinrt::com::Value::DispatchParams(value) => AutomationValueKind::DispatchParams(value), dynwinrt::com::Value::ExcepInfo(value) => AutomationValueKind::ExcepInfo(value), dynwinrt::com::Value::StatStg(value) => AutomationValueKind::StatStg(value), + dynwinrt::com::Value::FormatEtc(value) => AutomationValueKind::FormatEtc(value), + dynwinrt::com::Value::StgMedium(value) => AutomationValueKind::StgMedium(value), _ => unreachable!("AutomationValue requires an automation COM value"), }; Self { @@ -95,6 +99,8 @@ impl AutomationValue { } AutomationValueKind::ExcepInfo(value) => dynwinrt::com::Value::ExcepInfo(value.clone()), AutomationValueKind::StatStg(value) => dynwinrt::com::Value::StatStg(value.clone()), + AutomationValueKind::FormatEtc(value) => dynwinrt::com::Value::FormatEtc(value.clone()), + AutomationValueKind::StgMedium(value) => dynwinrt::com::Value::StgMedium(value.clone()), }) } @@ -153,6 +159,28 @@ impl AutomationValue { } } + pub(super) fn take_format_etc(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::FormatEtc(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not COM FORMATETC")) + } + } + } + + pub(super) fn take_stg_medium(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::StgMedium(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not COM STGMEDIUM")) + } + } + } + pub(super) fn leak_for_shutdown(&mut self) { if let Some(value) = self.value.take() { std::mem::forget(value); @@ -1997,6 +2025,20 @@ impl DynComMethodSig { Self(self.0.clone().capture_dispatch_invoke_hresult()) } + #[napi] + pub fn canonical_format_etc_result( + &self, + input_param_index: f64, + output_param_index: f64, + ) -> napi::Result { + let input = checked_unsigned_number(input_param_index, u32::MAX.into(), "inputParamIndex")?; + let output = checked_unsigned_number(output_param_index, u32::MAX.into(), "outputParamIndex")?; + Ok(Self(self.0.clone().canonical_format_etc_result( + input as usize, + output as usize, + ))) + } + #[napi] pub fn add_in_out(&self, typ: &DynComType) -> Self { Self(self.0.clone().add_in_out(typ.0.clone())) @@ -3067,6 +3109,76 @@ pub struct DynComStatStg { value: Option, } +#[napi] +pub struct DynComFormatEtc { + value: dynwinrt::com::FormatEtcValue, +} + +#[napi] +impl DynComFormatEtc { + #[napi(factory)] + pub fn hglobal( + clipboard_format: u32, + aspect: Option, + index: Option, + ) -> napi::Result { + let clipboard_format = u16::try_from(clipboard_format) + .map_err(|_| napi::Error::from_reason("clipboardFormat must fit in u16"))?; + dynwinrt::com::FormatEtcValue::hglobal( + clipboard_format, + aspect.unwrap_or(1), + index.unwrap_or(-1), + ) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(getter)] + pub fn clipboard_format(&self) -> u32 { + u32::from(self.value.clipboard_format()) + } + + #[napi(getter)] + pub fn aspect(&self) -> u32 { + self.value.aspect() + } + + #[napi(getter)] + pub fn index(&self) -> i32 { + self.value.index() + } + + #[napi(getter)] + pub fn tymed(&self) -> u32 { + self.value.tymed() + } +} + +#[napi] +pub struct DynComStgMedium { + value: dynwinrt::com::StgMediumValue, +} + +#[napi] +impl DynComStgMedium { + #[napi(factory)] + pub fn hglobal(bytes: Buffer) -> napi::Result { + dynwinrt::com::StgMediumValue::hglobal(bytes.to_vec()) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(getter)] + pub fn tymed(&self) -> u32 { + windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + } + + #[napi] + pub fn to_buffer(&self) -> Buffer { + Buffer::from(self.value.bytes().to_vec()) + } +} + #[napi] #[derive(Debug)] pub struct DynComOwnedHandle { @@ -4800,6 +4912,16 @@ impl DynCom { DynComType(dynwinrt::com::Type::stat_stg()) } + #[napi] + pub fn format_etc_type() -> DynComType { + DynComType(dynwinrt::com::Type::format_etc()) + } + + #[napi] + pub fn stg_medium_type() -> DynComType { + DynComType(dynwinrt::com::Type::stg_medium()) + } + #[napi] pub fn interface_type(iid: &WinGUID) -> DynComType { DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) @@ -5632,6 +5754,22 @@ impl DynCom { )) } + #[napi] + pub fn format_etc(value: &DynComFormatEtc) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::FormatEtc(value.value.clone()), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn stg_medium(value: &DynComStgMedium) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::StgMedium(value.value.clone()), + dynwinrt::com::PointerOutputKind::None, + ) + } + #[napi] pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { let result = value @@ -5697,6 +5835,28 @@ impl DynCom { Ok(DynComStatStg::new(result)) } + #[napi] + pub fn take_format_etc(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not COM FORMATETC"))? + .take_format_etc()?; + value.5 = None; + Ok(DynComFormatEtc { value: result }) + } + + #[napi] + pub fn take_stg_medium(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not COM STGMEDIUM"))? + .take_stg_medium()?; + value.5 = None; + Ok(DynComStgMedium { value: result }) + } + #[napi] pub fn take_delete_object_handle(value: &mut DynWinRTValue) -> napi::Result { take_owned_handle( diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 09c33297..8d468e0a 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -9,9 +9,10 @@ use std::{ use napi::bindgen_prelude::BigInt; use napi_derive::napi; use windows::{ - core::{IUnknown, IUnknown_Vtbl, Interface, GUID, HRESULT, PCWSTR}, + core::{IUnknown, IUnknown_Vtbl, Interface, BOOL, GUID, HRESULT, PCWSTR}, Win32::System::{ Com::SAFEARRAY, + Ole::{IOleCache, IOleCache2, IOleCache2_Vtbl, IOleCache_Vtbl, UPDFCACHE_FLAGS}, Variant::VARIANT, Wmi::{ IWbemCallResult_Vtbl, IWbemClassObject_Vtbl, IWbemServices_Vtbl, WBEM_COMPARISON_FLAG, @@ -26,6 +27,7 @@ const IID_IWBEM_SERVICES: GUID = GUID::from_u128(0x9556dc99_828c_11cf_a37e_00aa0 const IID_IWBEM_CALL_RESULT: GUID = GUID::from_u128(0x44aca675_e8fc_11d0_a07c_00c04fb68820); const IID_IWBEM_CLASS_OBJECT: GUID = GUID::from_u128(0xdc12a681_737f_11cf_884d_00aa004b2e24); const IID_ITHUMBNAIL_PROVIDER: GUID = GUID::from_u128(0xe357fccd_a995_4576_b01f_234630154e96); +const IID_IDATA_OBJECT: GUID = GUID::from_u128(0x0000010e_0000_0000_c000_000000000046); const IID_IAUDIO_CLIENT: GUID = GUID::from_u128(0x1cb9ad4c_dbfa_4c32_b178_c2f568a703b2); const E_NOINTERFACE: HRESULT = HRESULT(0x80004002u32 as i32); const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); @@ -64,6 +66,22 @@ static AUDIO_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); static THUMBNAIL_CALLS: AtomicU32 = AtomicU32::new(0); static THUMBNAIL_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_GET_DATA_CALLS: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_GET_DATA_HERE_CALLS: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_QUERY_GET_DATA_CALLS: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_CANONICAL_CALLS: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_CANONICAL_MODE: AtomicI32 = AtomicI32::new(0); +static DATA_OBJECT_SET_DATA_CALLS: AtomicU32 = AtomicU32::new(0); +static DATA_OBJECT_LAST_SET_RELEASE: AtomicI32 = AtomicI32::new(-1); +static DATA_OBJECT_LAST_OUTPUT_HANDLE: AtomicUsize = AtomicUsize::new(0); +static DATA_OBJECT_LAST_GET_DATA_HERE_HANDLE: AtomicUsize = AtomicUsize::new(0); +static DATA_OBJECT_LAST_SET_DATA_HANDLE: AtomicUsize = AtomicUsize::new(0); +static DATA_OBJECT_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static OLE_CACHE_SET_DATA_CALLS: AtomicU32 = AtomicU32::new(0); +static OLE_CACHE_BORROWED_INPUT_CALLS: AtomicU32 = AtomicU32::new(0); +static OLE_CACHE_LAST_SET_RELEASE: AtomicI32 = AtomicI32::new(-1); +static OLE_CACHE_LAST_SET_DATA_HANDLE: AtomicUsize = AtomicUsize::new(0); +static OLE_CACHE_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); #[repr(C)] struct GeneratedIWbemServicesFake { @@ -982,6 +1000,564 @@ pub fn generated_thumbnail_provider_stats() -> GeneratedThumbnailProviderStats { } } +#[repr(C)] +struct GeneratedDataObjectVtbl { + base__: IUnknown_Vtbl, + get_data: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT, + get_data_here: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT, + query_get_data: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + ) -> HRESULT, + get_canonical_format_etc: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + *mut windows::Win32::System::Com::FORMATETC, + ) -> HRESULT, + set_data: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + *const windows::Win32::System::Com::STGMEDIUM, + i32, + ) -> HRESULT, + enum_format_etc: unsafe extern "system" fn(*mut c_void, u32, *mut *mut c_void) -> HRESULT, + d_advise: unsafe extern "system" fn( + *mut c_void, + *const windows::Win32::System::Com::FORMATETC, + u32, + *mut c_void, + *mut u32, + ) -> HRESULT, + d_unadvise: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, + enum_d_advise: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT, +} + +#[repr(C)] +struct GeneratedDataObjectFake { + vtable: *const GeneratedDataObjectVtbl, + references: AtomicU32, +} + +unsafe extern "system" fn data_object_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 != IID_IDATA_OBJECT { + return E_NOINTERFACE; + } + *result = this; + data_object_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn data_object_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + DATA_OBJECT_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn data_object_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + DATA_OBJECT_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +fn valid_hglobal_format(format: *const windows::Win32::System::Com::FORMATETC) -> bool { + !format.is_null() + && unsafe { + (*format).cfFormat == 13 + && (*format).ptd.is_null() + && (*format).dwAspect == 1 + && (*format).lindex == -1 + && (*format).tymed == windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + } +} + +unsafe fn write_hglobal_bytes( + medium: *mut windows::Win32::System::Com::STGMEDIUM, + bytes: &[u8], +) -> HRESULT { + if medium.is_null() || unsafe { (*medium).tymed != 0 } { + return E_POINTER; + } + let handle = match unsafe { + windows::Win32::System::Memory::GlobalAlloc( + windows::Win32::System::Memory::GMEM_MOVEABLE | windows::Win32::System::Memory::GMEM_ZEROINIT, + bytes.len(), + ) + } { + Ok(handle) => handle, + Err(_) => return HRESULT(0x8007000eu32 as i32), + }; + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + if data.is_null() { + unsafe { + let _ = windows::Win32::Foundation::GlobalFree(Some(handle)); + } + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::(), bytes.len()); + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + medium.write(windows::Win32::System::Com::STGMEDIUM { + tymed: windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + u: windows::Win32::System::Com::STGMEDIUM_0 { hGlobal: handle }, + pUnkForRelease: std::mem::ManuallyDrop::new(None), + }); + } + DATA_OBJECT_LAST_OUTPUT_HANDLE.store(handle.0.addr(), Ordering::SeqCst); + HRESULT(0) +} + +unsafe fn read_hglobal_bytes( + medium: *const windows::Win32::System::Com::STGMEDIUM, +) -> Option> { + if medium.is_null() + || unsafe { (*medium).tymed } != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + { + return None; + } + let handle = unsafe { (*medium).u.hGlobal }; + let size = unsafe { windows::Win32::System::Memory::GlobalSize(handle) }; + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + if size > 0 && data.is_null() { + return None; + } + let bytes = if size == 0 { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(data.cast::(), size) }.to_vec() + }; + if !data.is_null() { + unsafe { + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + } + } + Some(bytes) +} + +fn hglobal_handle_released(address: usize) -> bool { + address != 0 + && unsafe { + windows::Win32::System::Memory::GlobalSize(windows::Win32::Foundation::HGLOBAL( + std::ptr::with_exposed_provenance_mut(address), + )) + } == 0 +} + +unsafe extern "system" fn data_object_get_data( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, +) -> HRESULT { + DATA_OBJECT_GET_DATA_CALLS.fetch_add(1, Ordering::SeqCst); + if !valid_hglobal_format(format) { + return HRESULT(0x80040064u32 as i32); + } + unsafe { write_hglobal_bytes(medium, &[1, 2, 3, 4]) } +} + +unsafe extern "system" fn data_object_get_data_here( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, +) -> HRESULT { + DATA_OBJECT_GET_DATA_HERE_CALLS.fetch_add(1, Ordering::SeqCst); + if !valid_hglobal_format(format) { + return HRESULT(0x80040064u32 as i32); + } + let Some(mut bytes) = (unsafe { read_hglobal_bytes(medium) }) else { + return HRESULT(0x80040069u32 as i32); + }; + if bytes.len() < 4 { + return HRESULT(0x80030070u32 as i32); + } + bytes[..4].copy_from_slice(&[9, 8, 7, 6]); + let handle = unsafe { (*medium).u.hGlobal }; + DATA_OBJECT_LAST_GET_DATA_HERE_HANDLE.store(handle.0.addr(), Ordering::SeqCst); + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::(), bytes.len()); + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + } + HRESULT(0) +} + +unsafe extern "system" fn data_object_query_get_data( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, +) -> HRESULT { + DATA_OBJECT_QUERY_GET_DATA_CALLS.fetch_add(1, Ordering::SeqCst); + if valid_hglobal_format(format) { + HRESULT(0) + } else { + HRESULT(0x80040064u32 as i32) + } +} + +unsafe extern "system" fn data_object_get_canonical_format_etc( + _this: *mut c_void, + input: *const windows::Win32::System::Com::FORMATETC, + output: *mut windows::Win32::System::Com::FORMATETC, +) -> HRESULT { + DATA_OBJECT_CANONICAL_CALLS.fetch_add(1, Ordering::SeqCst); + if !valid_hglobal_format(input) || output.is_null() { + return E_POINTER; + } + let mode = DATA_OBJECT_CANONICAL_MODE.load(Ordering::SeqCst); + match mode { + -1 => return HRESULT(0x80004005u32 as i32), + 2 => return HRESULT(0x40130), + 3 => { + // DATA_S_SAMEFORMATETC must not decode these invalid scalar fields. + unsafe { + output.write(windows::Win32::System::Com::FORMATETC { + cfFormat: 0, + ptd: std::ptr::null_mut(), + dwAspect: u32::MAX, + lindex: i32::MIN, + tymed: u32::MAX, + }); + } + return HRESULT(0x40130); + } + _ => {} + } + unsafe { + output.write(windows::Win32::System::Com::FORMATETC { + cfFormat: 1, + ptd: std::ptr::null_mut(), + dwAspect: 4, + lindex: 7, + tymed: match mode { + 0 => 0, + 1 => u32::MAX, + _ => windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + }, + }); + } + HRESULT(if mode == 4 { 1 } else { 0 }) +} + +unsafe extern "system" fn data_object_set_data( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *const windows::Win32::System::Com::STGMEDIUM, + release_medium: i32, +) -> HRESULT { + DATA_OBJECT_SET_DATA_CALLS.fetch_add(1, Ordering::SeqCst); + DATA_OBJECT_LAST_SET_RELEASE.store(release_medium, Ordering::SeqCst); + if !medium.is_null() + && unsafe { (*medium).tymed } == windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + { + DATA_OBJECT_LAST_SET_DATA_HANDLE + .store(unsafe { (*medium).u.hGlobal }.0.addr(), Ordering::SeqCst); + } + if !valid_hglobal_format(format) + || release_medium != 0 + || unsafe { read_hglobal_bytes(medium) }.as_deref() != Some(&[5, 6, 7, 8]) + { + return HRESULT(0x80070057u32 as i32); + } + HRESULT(0) +} + +unsafe extern "system" fn data_object_enum_format_etc( + _this: *mut c_void, + _direction: u32, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn data_object_d_advise( + _this: *mut c_void, + _format: *const windows::Win32::System::Com::FORMATETC, + _flags: u32, + _sink: *mut c_void, + _connection: *mut u32, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn data_object_d_unadvise(_this: *mut c_void, _connection: u32) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn data_object_enum_d_advise( + _this: *mut c_void, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +static DATA_OBJECT_VTABLE: GeneratedDataObjectVtbl = GeneratedDataObjectVtbl { + base__: IUnknown_Vtbl { + QueryInterface: data_object_query_interface, + AddRef: data_object_add_ref, + Release: data_object_release, + }, + get_data: data_object_get_data, + get_data_here: data_object_get_data_here, + query_get_data: data_object_query_get_data, + get_canonical_format_etc: data_object_get_canonical_format_etc, + set_data: data_object_set_data, + enum_format_etc: data_object_enum_format_etc, + d_advise: data_object_d_advise, + d_unadvise: data_object_d_unadvise, + enum_d_advise: data_object_enum_d_advise, +}; + +#[napi(object)] +pub struct GeneratedDataObjectStats { + pub get_data_calls: u32, + pub get_data_here_calls: u32, + pub query_get_data_calls: u32, + pub canonical_calls: u32, + pub set_data_calls: u32, + pub last_set_release: i32, + pub output_released: bool, + pub get_data_here_input_released: bool, + pub set_data_input_released: bool, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_data_object_fake() -> napi::Result { + DATA_OBJECT_GET_DATA_CALLS.store(0, Ordering::SeqCst); + DATA_OBJECT_GET_DATA_HERE_CALLS.store(0, Ordering::SeqCst); + DATA_OBJECT_QUERY_GET_DATA_CALLS.store(0, Ordering::SeqCst); + DATA_OBJECT_CANONICAL_CALLS.store(0, Ordering::SeqCst); + DATA_OBJECT_CANONICAL_MODE.store(0, Ordering::SeqCst); + DATA_OBJECT_SET_DATA_CALLS.store(0, Ordering::SeqCst); + DATA_OBJECT_LAST_SET_RELEASE.store(-1, Ordering::SeqCst); + DATA_OBJECT_LAST_OUTPUT_HANDLE.store(0, Ordering::SeqCst); + DATA_OBJECT_LAST_GET_DATA_HERE_HANDLE.store(0, Ordering::SeqCst); + DATA_OBJECT_LAST_SET_DATA_HANDLE.store(0, Ordering::SeqCst); + DATA_OBJECT_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedDataObjectFake { + vtable: &DATA_OBJECT_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_data_object_canonical_mode(mode: i32) -> napi::Result<()> { + if !matches!(mode, -1..=4) { + return Err(napi::Error::from_reason( + "IDataObject canonical test mode must be between -1 and 4", + )); + } + DATA_OBJECT_CANONICAL_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + +#[napi] +pub fn generated_data_object_stats() -> GeneratedDataObjectStats { + GeneratedDataObjectStats { + get_data_calls: DATA_OBJECT_GET_DATA_CALLS.load(Ordering::SeqCst), + get_data_here_calls: DATA_OBJECT_GET_DATA_HERE_CALLS.load(Ordering::SeqCst), + query_get_data_calls: DATA_OBJECT_QUERY_GET_DATA_CALLS.load(Ordering::SeqCst), + canonical_calls: DATA_OBJECT_CANONICAL_CALLS.load(Ordering::SeqCst), + set_data_calls: DATA_OBJECT_SET_DATA_CALLS.load(Ordering::SeqCst), + last_set_release: DATA_OBJECT_LAST_SET_RELEASE.load(Ordering::SeqCst), + output_released: hglobal_handle_released(DATA_OBJECT_LAST_OUTPUT_HANDLE.load(Ordering::SeqCst)), + get_data_here_input_released: hglobal_handle_released( + DATA_OBJECT_LAST_GET_DATA_HERE_HANDLE.load(Ordering::SeqCst), + ), + set_data_input_released: hglobal_handle_released( + DATA_OBJECT_LAST_SET_DATA_HANDLE.load(Ordering::SeqCst), + ), + current_ref_count: DATA_OBJECT_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + +#[repr(C)] +struct GeneratedOleCacheFake { + vtable: *const IOleCache2_Vtbl, + references: AtomicU32, +} + +unsafe extern "system" fn ole_cache_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 != IOleCache::IID && *iid != IOleCache2::IID { + return E_NOINTERFACE; + } + *result = this; + ole_cache_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn ole_cache_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + OLE_CACHE_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn ole_cache_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + OLE_CACHE_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn ole_cache_cache( + _this: *mut c_void, + _format: *const windows::Win32::System::Com::FORMATETC, + _flags: u32, + _connection: *mut u32, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn ole_cache_uncache(_this: *mut c_void, _connection: u32) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn ole_cache_enum_cache( + _this: *mut c_void, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn ole_cache_init_cache( + _this: *mut c_void, + _data_object: *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn ole_cache_set_data( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *const windows::Win32::System::Com::STGMEDIUM, + release_medium: BOOL, +) -> HRESULT { + OLE_CACHE_SET_DATA_CALLS.fetch_add(1, Ordering::SeqCst); + OLE_CACHE_LAST_SET_RELEASE.store(release_medium.0, Ordering::SeqCst); + // Reject ownership transfer before touching the borrowed allocation. + if release_medium.0 != 0 { + return HRESULT(0x80070057u32 as i32); + } + if !valid_hglobal_format(format) + || medium.is_null() + || unsafe { (*medium).pUnkForRelease.is_some() } + || unsafe { read_hglobal_bytes(medium) }.as_deref() != Some(&[5, 6, 7, 8]) + { + return HRESULT(0x80070057u32 as i32); + } + OLE_CACHE_LAST_SET_DATA_HANDLE.store(unsafe { (*medium).u.hGlobal }.0.addr(), Ordering::SeqCst); + OLE_CACHE_BORROWED_INPUT_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn ole_cache_update_cache( + _this: *mut c_void, + _data_object: *mut c_void, + _flags: UPDFCACHE_FLAGS, + _reserved: *const c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn ole_cache_discard_cache(_this: *mut c_void, _options: u32) -> HRESULT { + E_NOTIMPL +} + +static OLE_CACHE_VTABLE: IOleCache2_Vtbl = IOleCache2_Vtbl { + base__: IOleCache_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: ole_cache_query_interface, + AddRef: ole_cache_add_ref, + Release: ole_cache_release, + }, + Cache: ole_cache_cache, + Uncache: ole_cache_uncache, + EnumCache: ole_cache_enum_cache, + InitCache: ole_cache_init_cache, + SetData: ole_cache_set_data, + }, + UpdateCache: ole_cache_update_cache, + DiscardCache: ole_cache_discard_cache, +}; + +#[napi(object)] +pub struct GeneratedOleCacheStats { + pub set_data_calls: u32, + pub borrowed_input_calls: u32, + pub last_set_release: i32, + pub set_data_input_released: bool, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_ole_cache_fake() -> napi::Result { + OLE_CACHE_SET_DATA_CALLS.store(0, Ordering::SeqCst); + OLE_CACHE_BORROWED_INPUT_CALLS.store(0, Ordering::SeqCst); + OLE_CACHE_LAST_SET_RELEASE.store(-1, Ordering::SeqCst); + OLE_CACHE_LAST_SET_DATA_HANDLE.store(0, Ordering::SeqCst); + OLE_CACHE_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedOleCacheFake { + vtable: &OLE_CACHE_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 generated_ole_cache_stats() -> GeneratedOleCacheStats { + GeneratedOleCacheStats { + set_data_calls: OLE_CACHE_SET_DATA_CALLS.load(Ordering::SeqCst), + borrowed_input_calls: OLE_CACHE_BORROWED_INPUT_CALLS.load(Ordering::SeqCst), + last_set_release: OLE_CACHE_LAST_SET_RELEASE.load(Ordering::SeqCst), + set_data_input_released: hglobal_handle_released( + OLE_CACHE_LAST_SET_DATA_HANDLE.load(Ordering::SeqCst), + ), + current_ref_count: OLE_CACHE_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + #[repr(C)] struct GeneratedAudioClientVtbl { base__: IUnknown_Vtbl, diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 417a7fd1..725da524 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -1206,6 +1206,28 @@ impl DynWinRTValue { ))), 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::Buffer(value) => Self( dynwinrt::WinRTValue::Null, None, diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index 3105e8c5..4dc84fe7 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -32,6 +32,7 @@ features = [ "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_LibraryLoader", + "Win32_System_Memory", "Win32_System_Ole", "Win32_System_Threading", "Win32_System_Variant", diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index ab6a5d85..9c4a551c 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -406,6 +406,14 @@ pub(crate) trait ArgumentList { fn get_dispatch_params(&self, _index: usize) -> Option<&crate::com::DispatchParamsValue> { None } + + fn get_format_etc(&self, _index: usize) -> Option<&crate::com::FormatEtcValue> { + None + } + + fn get_stg_medium(&self, _index: usize) -> Option<&crate::com::StgMediumValue> { + None + } } impl ArgumentList for [WinRTValue] { @@ -724,6 +732,10 @@ where std::collections::BTreeMap::::new(); let mut stat_stg_out_values = std::collections::BTreeMap::::new(); + let mut format_etc_out_values = + std::collections::BTreeMap::::new(); + let mut stg_medium_out_values = + std::collections::BTreeMap::::new(); let mut optional_out_requests: Vec> = Vec::with_capacity(out_count); // Array storage: Box'd for pointer stability (addresses don't change after creation) @@ -740,6 +752,8 @@ where let mut bstr_in_slots: Vec = Vec::new(); let mut native_union_in_slots: Vec> = Vec::new(); let mut variant_by_value_in_slots: Vec = Vec::new(); + let mut format_etc_in_slots: Vec> = Vec::new(); + let mut stg_medium_in_slots: Vec = Vec::new(); // FillArray storage: caller-allocated buffers let mut fill_array_slots: Vec> = Vec::new(); @@ -1010,6 +1024,51 @@ where stat_stg_out_values.insert(p.value_index, value); array_out_map.push(None); fill_array_map.push(None); + } else if p.typ.is_format_etc() { + if p.is_in_out() { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "FORMATETC in/out is not supported", + )); + } + let mut value = crate::com::FormatEtcOutput::new(); + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + format_etc_out_values.insert(p.value_index, value); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_stg_medium() { + let mut value = if p.is_in_out() { + crate::com::StgMediumStorage::from_value( + args.get_stg_medium(p.input_index.expect("STGMEDIUM input index")) + .expect("validated STGMEDIUM in/out value"), + ) + .map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })? + } else { + crate::com::StgMediumStorage::output() + }; + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + stg_medium_out_values.insert(p.value_index, value); + array_out_map.push(None); + fill_array_map.push(None); } else if p.typ.is_struct() { let val = if p.is_in_out() { args.get_value(p.input_index.expect("in/out input index")) @@ -1110,6 +1169,25 @@ where ) })?, ); + } else if p.is_input() && !p.is_out() && p.typ.is_format_etc() { + format_etc_in_slots.push(Box::new( + args.get_format_etc(p.input_index.expect("FORMATETC input index")) + .expect("validated FORMATETC input") + .to_raw(), + )); + } else if p.is_input() && !p.is_out() && p.typ.is_stg_medium() { + stg_medium_in_slots.push( + crate::com::StgMediumStorage::from_value( + args.get_stg_medium(p.input_index.expect("STGMEDIUM input index")) + .expect("validated STGMEDIUM input"), + ) + .map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?, + ); } } let native_struct_in_ptrs = native_struct_in_slots @@ -1200,6 +1278,14 @@ where .cast::() }) .collect::>(); + let format_etc_in_ptrs = format_etc_in_slots + .iter_mut() + .map(|value| (&mut **value as *mut windows::Win32::System::Com::FORMATETC).cast::()) + .collect::>(); + let stg_medium_in_ptrs = stg_medium_in_slots + .iter_mut() + .map(crate::com::StgMediumStorage::as_mut_ptr) + .collect::>(); // Phase 2: Build ffi_args let mut array_in_idx = 0usize; @@ -1212,6 +1298,8 @@ where let mut safe_array_in_idx = 0usize; let mut prop_variant_in_idx = 0usize; let mut dispatch_params_in_idx = 0usize; + let mut format_etc_in_idx = 0usize; + let mut stg_medium_in_idx = 0usize; for p in parameters { if p.is_out() { if let Some(slot_idx) = fill_array_map[p.value_index] { @@ -1259,6 +1347,12 @@ where variant_by_value_in_slots[variant_by_value_in_idx].as_ref() )); variant_by_value_in_idx += 1; + } else if p.typ.is_format_etc() { + ffi_args.push(arg(&format_etc_in_ptrs[format_etc_in_idx])); + format_etc_in_idx += 1; + } else if p.typ.is_stg_medium() { + ffi_args.push(arg(&stg_medium_in_ptrs[stg_medium_in_idx])); + stg_medium_in_idx += 1; } else if p.typ.is_variant() { ffi_args.push(arg(&variant_in_ptrs[variant_in_idx])); variant_in_idx += 1; @@ -1623,6 +1717,31 @@ where ) }, )?)); + } else if let Some(value) = format_etc_out_values.remove(&p.value_index) { + let value = if let Some(input_index) = p.canonical_format_input { + value.into_canonical_value( + args.get_format_etc(input_index) + .expect("validated canonical FORMATETC input"), + native_hresult.expect("canonical FORMATETC uses a semantic HRESULT"), + ) + } else { + value.into_value() + }; + result_values.push(NativeCallValue::FormatEtc(value.map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?)); + } else if let Some(value) = stg_medium_out_values.remove(&p.value_index) { + result_values.push(NativeCallValue::StgMedium(value.into_value().map_err( + |error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + }, + )?)); } else if let Some(struct_val) = struct_out_values[p.value_index].take() { result_values.push(NativeCallValue::WinRt(WinRTValue::Struct(struct_val))); } else { diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index 1e13d16d..883109b9 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -645,6 +645,287 @@ impl StatStgValue { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FormatEtcValue { + clipboard_format: u16, + aspect: u32, + index: i32, + tymed: u32, +} + +impl FormatEtcValue { + pub fn hglobal(clipboard_format: u16, aspect: u32, index: i32) -> result::Result { + if clipboard_format == 0 { + return Err(invalid_argument( + "FORMATETC clipboard format must be non-zero", + )); + } + if !matches!(aspect, 1 | 2 | 4 | 8) { + return Err(invalid_argument( + "FORMATETC aspect must contain exactly one DVASPECT value", + )); + } + Ok(Self { + clipboard_format, + aspect, + index, + tymed: windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + }) + } + + pub const fn clipboard_format(&self) -> u16 { + self.clipboard_format + } + + pub const fn aspect(&self) -> u32 { + self.aspect + } + + pub const fn index(&self) -> i32 { + self.index + } + + pub const fn tymed(&self) -> u32 { + self.tymed + } + + pub(crate) fn to_raw(&self) -> windows::Win32::System::Com::FORMATETC { + windows::Win32::System::Com::FORMATETC { + cfFormat: self.clipboard_format, + ptd: std::ptr::null_mut(), + dwAspect: self.aspect, + lindex: self.index, + tymed: self.tymed, + } + } + + fn from_raw(raw: &windows::Win32::System::Com::FORMATETC) -> result::Result { + if !raw.ptd.is_null() { + return Err(invalid_argument( + "FORMATETC target-device output is not supported", + )); + } + if raw.tymed != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 { + return Err(invalid_argument( + "FORMATETC currently supports only TYMED_HGLOBAL", + )); + } + Self::hglobal(raw.cfFormat, raw.dwAspect, raw.lindex) + } +} + +pub(crate) struct FormatEtcOutput { + raw: Box, +} + +impl FormatEtcOutput { + pub(crate) fn new() -> Self { + Self { + raw: Box::new(unsafe { std::mem::zeroed() }), + } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut c_void { + (&mut *self.raw as *mut windows::Win32::System::Com::FORMATETC).cast() + } + + pub(crate) fn into_value(mut self) -> result::Result { + let value = FormatEtcValue::from_raw(&self.raw); + self.free_target_device(); + value + } + + pub(crate) fn into_canonical_value( + mut self, + input: &FormatEtcValue, + hresult: HRESULT, + ) -> result::Result { + use windows::Win32::Foundation::{DATA_S_SAMEFORMATETC, S_OK}; + + if hresult == DATA_S_SAMEFORMATETC { + // The output is unused; this status does not transfer a target-device owner. + self.raw.ptd = std::ptr::null_mut(); + return Ok(input.clone()); + } + let value = if hresult == S_OK { + // Canonicalization does not select a transfer medium. + self.raw.tymed = input.tymed(); + FormatEtcValue::from_raw(&self.raw) + } else { + Err(invalid_argument(format!( + "unexpected canonical FORMATETC success HRESULT {:#010x}", + hresult.0 as u32 + ))) + }; + self.free_target_device(); + value + } + + fn free_target_device(&mut self) { + if self.raw.ptd.is_null() { + return; + } + unsafe { + OutputCleanup::CoTaskMemFree.cleanup(self.raw.ptd.cast()); + } + self.raw.ptd = std::ptr::null_mut(); + } +} + +impl Drop for FormatEtcOutput { + fn drop(&mut self) { + self.free_target_device(); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StgMediumValue { + hglobal_bytes: Arc<[u8]>, +} + +impl StgMediumValue { + pub fn hglobal(bytes: Vec) -> result::Result { + if bytes.is_empty() { + return Err(invalid_argument( + "TYMED_HGLOBAL storage must contain at least one byte", + )); + } + Ok(Self { + hglobal_bytes: bytes.into(), + }) + } + + pub fn bytes(&self) -> &[u8] { + &self.hglobal_bytes + } +} + +pub(crate) struct StgMediumStorage { + raw: Box, + owned_input_hglobal: Option, +} + +impl StgMediumStorage { + pub(crate) fn output() -> Self { + Self { + raw: Box::new(unsafe { std::mem::zeroed() }), + owned_input_hglobal: None, + } + } + + pub(crate) fn from_value(value: &StgMediumValue) -> result::Result { + use windows::Win32::System::Memory::{GMEM_MOVEABLE, GMEM_ZEROINIT, GlobalAlloc}; + + let handle = + unsafe { GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, value.hglobal_bytes.len()) } + .map_err(result::Error::WindowsError)?; + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + if data.is_null() { + unsafe { + let _ = windows::Win32::Foundation::GlobalFree(Some(handle)); + } + return Err(invalid_argument("GlobalLock failed for TYMED_HGLOBAL")); + } + unsafe { + std::ptr::copy_nonoverlapping( + value.hglobal_bytes.as_ptr(), + data.cast::(), + value.hglobal_bytes.len(), + ); + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + } + Ok(Self { + raw: Box::new(windows::Win32::System::Com::STGMEDIUM { + tymed: windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + u: windows::Win32::System::Com::STGMEDIUM_0 { hGlobal: handle }, + pUnkForRelease: std::mem::ManuallyDrop::new(None), + }), + owned_input_hglobal: Some(handle), + }) + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut c_void { + (&mut *self.raw as *mut windows::Win32::System::Com::STGMEDIUM).cast() + } + + pub(crate) fn into_value(mut self) -> result::Result { + if self.raw.tymed != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 { + return Err(invalid_argument( + "STGMEDIUM currently supports only TYMED_HGLOBAL", + )); + } + let handle = unsafe { self.raw.u.hGlobal }; + if let Some(owned_input_hglobal) = self.owned_input_hglobal + && (handle.0 != owned_input_hglobal.0 || self.raw.pUnkForRelease.is_some()) + { + return Err(invalid_argument( + "caller-owned TYMED_HGLOBAL storage was replaced by the callee", + )); + } + if handle.0.is_null() { + return Err(invalid_argument( + "TYMED_HGLOBAL returned a null storage handle", + )); + } + let size = unsafe { windows::Win32::System::Memory::GlobalSize(handle) }; + if size == 0 { + return Err(invalid_argument( + "TYMED_HGLOBAL returned invalid or empty storage", + )); + } + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + if data.is_null() { + return Err(invalid_argument( + "GlobalLock failed for returned TYMED_HGLOBAL", + )); + } + let bytes = unsafe { std::slice::from_raw_parts(data.cast::(), size) }.to_vec(); + unsafe { + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + } + self.release(); + Ok(StgMediumValue { + hglobal_bytes: bytes.into(), + }) + } + + fn release(&mut self) { + if let Some(handle) = self.owned_input_hglobal.take() { + let mut owned = windows::Win32::System::Com::STGMEDIUM { + tymed: windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + u: windows::Win32::System::Com::STGMEDIUM_0 { hGlobal: handle }, + pUnkForRelease: std::mem::ManuallyDrop::new(None), + }; + unsafe { + windows::Win32::System::Ole::ReleaseStgMedium(&mut owned); + std::ptr::write_bytes( + (&mut *self.raw as *mut windows::Win32::System::Com::STGMEDIUM).cast::(), + 0, + size_of::(), + ); + } + return; + } + if self.raw.tymed == 0 && self.raw.pUnkForRelease.is_none() { + return; + } + unsafe { + windows::Win32::System::Ole::ReleaseStgMedium(&mut *self.raw); + std::ptr::write_bytes( + (&mut *self.raw as *mut windows::Win32::System::Com::STGMEDIUM).cast::(), + 0, + size_of::(), + ); + } + } +} + +impl Drop for StgMediumStorage { + fn drop(&mut self) { + self.release(); + } +} + #[cfg(test)] static STATSTG_TEST_FREES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -992,6 +1273,8 @@ pub enum Value { DispatchParams(DispatchParamsValue), ExcepInfo(ExcepInfoValue), StatStg(StatStgValue), + FormatEtc(FormatEtcValue), + StgMedium(StgMediumValue), Buffer(ComBufferValue), } @@ -1008,6 +1291,8 @@ fn is_null_input_value(value: &Value) -> bool { | Value::DispatchParams(_) | Value::ExcepInfo(_) | Value::StatStg(_) + | Value::FormatEtc(_) + | Value::StgMedium(_) | Value::Buffer(_) => false, } } @@ -1757,7 +2042,9 @@ impl BufferElementPlan { | ParameterType::PropVariant | ParameterType::DispatchParams | ParameterType::ExcepInfo - | ParameterType::StatStg => { + | ParameterType::StatStg + | ParameterType::FormatEtc + | ParameterType::StgMedium => { return Err(invalid_argument( "Automation buffer elements require dedicated ownership and cleanup plans", )); @@ -2057,6 +2344,24 @@ impl Type { } } + pub fn format_etc() -> Self { + Self { + abi: ParameterType::format_etc(), + pointer_output: PointerOutputKind::None, + allow_direct_aggregate_return: false, + aggregate_capability: None, + } + } + + pub fn stg_medium() -> Self { + Self { + abi: ParameterType::stg_medium(), + pointer_output: PointerOutputKind::None, + allow_direct_aggregate_return: false, + aggregate_capability: None, + } + } + fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { Self { abi: ParameterType::pointer(), @@ -2991,6 +3296,7 @@ impl CallbackMethodPlan { | ParameterType::DispatchParams | ParameterType::ExcepInfo | ParameterType::StatStg => Some(crate::native_callback::CallbackAbiType::Pointer), + ParameterType::FormatEtc | ParameterType::StgMedium => None, ParameterType::NativeStruct(layout) => { Some(crate::native_callback::CallbackAbiType::NativeStruct( format!("{layout:?}"), @@ -3444,7 +3750,10 @@ impl CallbackMethodPlan { .map_err(|_| SINK_E_FAIL) } } - ParameterType::NativeUnion(_) | ParameterType::VariantByValue => Err(SINK_E_FAIL), + ParameterType::NativeUnion(_) + | ParameterType::VariantByValue + | ParameterType::FormatEtc + | ParameterType::StgMedium => Err(SINK_E_FAIL), } } @@ -4095,7 +4404,9 @@ impl ComCallPlan { | Value::PropVariant(_) | Value::DispatchParams(_) | Value::ExcepInfo(_) - | Value::StatStg(_) => Err(invalid_argument( + | Value::StatStg(_) + | Value::FormatEtc(_) + | Value::StgMedium(_) => Err(invalid_argument( "COM-local result requires the COM value invocation path", )), Value::Buffer(_) => Err(invalid_argument( @@ -4291,7 +4602,9 @@ impl ComCallPlan { | Value::PropVariant(_) | Value::DispatchParams(_) | Value::ExcepInfo(_) - | Value::StatStg(_) => Err(invalid_argument( + | Value::StatStg(_) + | Value::FormatEtc(_) + | Value::StgMedium(_) => Err(invalid_argument( "COM-local value passed to a scalar COM method", )), Value::Buffer(_) => Err(invalid_argument( @@ -5329,6 +5642,13 @@ pub struct MethodSignature { parameters: Vec, return_plan: ComReturnPlan, enumerator_next_vtable_index: Option, + canonical_format_etc: Option, +} + +#[derive(Debug, Clone, Copy)] +struct CanonicalFormatEtcContract { + input_param_index: usize, + output_param_index: usize, } impl MethodSignature { @@ -5338,6 +5658,7 @@ impl MethodSignature { parameters: Vec::new(), return_plan: ComReturnPlan::HResult, enumerator_next_vtable_index: None, + canonical_format_etc: None, } } @@ -5573,6 +5894,18 @@ impl MethodSignature { self } + pub fn canonical_format_etc_result( + mut self, + input_param_index: usize, + output_param_index: usize, + ) -> Self { + self.canonical_format_etc = Some(CanonicalFormatEtcContract { + input_param_index, + output_param_index, + }); + self + } + fn validate_registration( &self, interface_iid: GUID, @@ -5669,6 +6002,24 @@ impl MethodSignature { validate_automation_contracts(&self.parameters, &self.return_plan)?; validate_in_out_ownership(&self.parameters)?; validate_buffer_contracts(&self.parameters)?; + if let Some(contract) = self.canonical_format_etc { + let valid = contract.input_param_index == 0 + && contract.output_param_index == 1 + && self.parameters.len() == 2 + && matches!(self.return_plan, ComReturnPlan::SemanticHResult) + && self.parameters[0].direction == ComParameterDirection::In + && self.parameters[1].direction == ComParameterDirection::Out + && self.parameters.iter().all(|parameter| { + parameter.typ.abi.is_format_etc() + && parameter.buffer.is_none() + && !parameter.nullable + }); + if !valid { + return Err(invalid_argument( + "canonical FORMATETC results require exactly FORMATETC In/Out parameters at 0/1 and a semantic HRESULT", + )); + } + } let enumerator_buffers = self .parameters .iter() @@ -5728,8 +6079,14 @@ impl MethodSignature { cleanup: typ.output_cleanup(), }, }; - let native = - lower_completed_method(&self.table, vtable_index, native_parameters, native_return); + let native = lower_completed_method( + &self.table, + vtable_index, + native_parameters, + native_return, + self.canonical_format_etc + .map(|contract| (contract.input_param_index, contract.output_param_index)), + ); Ok(RegisteredMethod { plan: ComCallPlan::new(native, self.parameters, self.return_plan), callback_plan, @@ -5795,6 +6152,27 @@ fn validate_automation_contracts( "STATSTG outputs require an HRESULT return convention", )); } + if parameter.typ.abi.is_format_etc() + && !matches!( + parameter.direction, + ComParameterDirection::In + | ComParameterDirection::Out + | ComParameterDirection::OptionalOut + ) + { + return Err(invalid_argument("FORMATETC does not support in/out")); + } + if (parameter.typ.abi.is_format_etc() || parameter.typ.abi.is_stg_medium()) + && parameter.direction != ComParameterDirection::In + && !matches!( + return_plan, + ComReturnPlan::HResult | ComReturnPlan::SemanticHResult + ) + { + return Err(invalid_argument( + "FORMATETC/STGMEDIUM outputs require an HRESULT return convention", + )); + } if parameter.typ.abi.is_excep_info() && !matches!( return_plan, @@ -10481,6 +10859,124 @@ mod tests { .invoke_values((&mut object as *mut FakeComObject).cast(), args) } + static LAST_STG_MEDIUM_HANDLE: AtomicUsize = AtomicUsize::new(0); + static REPLACED_STG_MEDIUM_HANDLE: AtomicUsize = AtomicUsize::new(0); + + unsafe extern "system" fn write_hglobal_medium( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT { + if format.is_null() + || medium.is_null() + || unsafe { (*format).tymed } != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + { + return HRESULT(0x80070057u32 as i32); + } + let handle = unsafe { + windows::Win32::System::Memory::GlobalAlloc( + windows::Win32::System::Memory::GMEM_MOVEABLE + | windows::Win32::System::Memory::GMEM_ZEROINIT, + 4, + ) + } + .unwrap(); + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + unsafe { + std::ptr::copy_nonoverlapping([1u8, 2, 3, 4].as_ptr(), data.cast::(), 4); + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + medium.write(windows::Win32::System::Com::STGMEDIUM { + tymed: windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + u: windows::Win32::System::Com::STGMEDIUM_0 { hGlobal: handle }, + pUnkForRelease: std::mem::ManuallyDrop::new(None), + }); + } + LAST_STG_MEDIUM_HANDLE.store(handle.0.addr(), Ordering::SeqCst); + HRESULT(0) + } + + unsafe extern "system" fn write_hglobal_medium_then_fail( + this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT { + let result = unsafe { write_hglobal_medium(this, format, medium) }; + if result.is_err() { + result + } else { + HRESULT(0x80004005u32 as i32) + } + } + + unsafe extern "system" fn fill_hglobal_medium( + _this: *mut c_void, + format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT { + if format.is_null() + || medium.is_null() + || unsafe { (*format).tymed } != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + || unsafe { (*medium).tymed } != windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32 + { + return HRESULT(0x80070057u32 as i32); + } + let handle = unsafe { (*medium).u.hGlobal }; + let data = unsafe { windows::Win32::System::Memory::GlobalLock(handle) }; + if data.is_null() || unsafe { windows::Win32::System::Memory::GlobalSize(handle) } < 4 { + return HRESULT(0x80030070u32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping([9u8, 8, 7, 6].as_ptr(), data.cast::(), 4); + let _ = windows::Win32::System::Memory::GlobalUnlock(handle); + } + HRESULT(0) + } + + unsafe extern "system" fn replace_hglobal_medium( + _this: *mut c_void, + _format: *const windows::Win32::System::Com::FORMATETC, + medium: *mut windows::Win32::System::Com::STGMEDIUM, + ) -> HRESULT { + if medium.is_null() { + return HRESULT(0x80070057u32 as i32); + } + let original = unsafe { (*medium).u.hGlobal }; + let replacement = unsafe { + windows::Win32::System::Memory::GlobalAlloc( + windows::Win32::System::Memory::GMEM_MOVEABLE + | windows::Win32::System::Memory::GMEM_ZEROINIT, + 4, + ) + } + .unwrap(); + LAST_STG_MEDIUM_HANDLE.store(original.0.addr(), Ordering::SeqCst); + REPLACED_STG_MEDIUM_HANDLE.store(replacement.0.addr(), Ordering::SeqCst); + unsafe { + (*medium).u.hGlobal = replacement; + } + HRESULT(0) + } + + unsafe extern "system" fn write_canonical_format( + _this: *mut c_void, + input: *const windows::Win32::System::Com::FORMATETC, + output: *mut windows::Win32::System::Com::FORMATETC, + ) -> HRESULT { + if input.is_null() || output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + unsafe { + output.write(windows::Win32::System::Com::FORMATETC { + cfFormat: (*input).cfFormat, + ptd: std::ptr::null_mut(), + dwAspect: (*input).dwAspect, + lindex: (*input).lindex, + tymed: (*input).tymed, + }); + } + HRESULT(0) + } + fn invoke_test_stat_stg(function: *mut c_void, flags: u32) -> result::Result> { let table = MetadataTable::new(); invoke_test_pod( @@ -13338,6 +13834,310 @@ mod tests { ); } + #[test] + fn format_etc_and_stg_medium_hglobal_calls_copy_and_release_native_storage() { + let table = MetadataTable::new(); + assert!(FormatEtcValue::hglobal(13, 0, -1).is_err()); + assert!(FormatEtcValue::hglobal(13, 3, -1).is_err()); + assert!(FormatEtcValue::hglobal(13, 16, -1).is_err()); + assert!(FormatEtcValue::hglobal(0, 1, -1).is_err()); + assert!(StgMediumValue::hglobal(Vec::new()).is_err()); + let format = FormatEtcValue::hglobal(13, 1, -1).unwrap(); + let error = invoke_test_pod( + write_hglobal_medium as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::stg_medium()), + &[Value::WinRt(WinRTValue::I32(13))], + ) + .unwrap_err(); + assert!(error.message().contains("FORMATETC")); + LAST_STG_MEDIUM_HANDLE.store(0, Ordering::SeqCst); + let output = invoke_test_pod( + write_hglobal_medium as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::stg_medium()), + &[Value::FormatEtc(format.clone())], + ) + .unwrap(); + let Value::StgMedium(medium) = &output[0] else { + panic!("expected STGMEDIUM output"); + }; + assert_eq!(medium.bytes(), [1, 2, 3, 4]); + let released = windows::Win32::Foundation::HGLOBAL(std::ptr::with_exposed_provenance_mut( + LAST_STG_MEDIUM_HANDLE.load(Ordering::SeqCst), + )); + assert_eq!( + unsafe { windows::Win32::System::Memory::GlobalSize(released) }, + 0 + ); + + let input_medium = StgMediumValue::hglobal(vec![0; 4]).unwrap(); + let output = invoke_test_pod( + fill_hglobal_medium as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_in_out(Type::stg_medium()), + &[ + Value::FormatEtc(format.clone()), + Value::StgMedium(input_medium), + ], + ) + .unwrap(); + let Value::StgMedium(medium) = &output[0] else { + panic!("expected STGMEDIUM in/out result"); + }; + assert_eq!(medium.bytes(), [9, 8, 7, 6]); + + LAST_STG_MEDIUM_HANDLE.store(0, Ordering::SeqCst); + REPLACED_STG_MEDIUM_HANDLE.store(0, Ordering::SeqCst); + let error = invoke_test_pod( + replace_hglobal_medium as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_in_out(Type::stg_medium()), + &[ + Value::FormatEtc(format.clone()), + Value::StgMedium(StgMediumValue::hglobal(vec![0; 4]).unwrap()), + ], + ) + .unwrap_err(); + assert!(error.message().contains("was replaced by the callee")); + let original = windows::Win32::Foundation::HGLOBAL(std::ptr::with_exposed_provenance_mut( + LAST_STG_MEDIUM_HANDLE.load(Ordering::SeqCst), + )); + assert_eq!( + unsafe { windows::Win32::System::Memory::GlobalSize(original) }, + 0 + ); + let replacement = + windows::Win32::Foundation::HGLOBAL(std::ptr::with_exposed_provenance_mut( + REPLACED_STG_MEDIUM_HANDLE.load(Ordering::SeqCst), + )); + assert_eq!( + unsafe { windows::Win32::System::Memory::GlobalSize(replacement) }, + 4 + ); + unsafe { + let _ = windows::Win32::Foundation::GlobalFree(Some(replacement)); + } + assert_eq!( + unsafe { windows::Win32::System::Memory::GlobalSize(replacement) }, + 0 + ); + + let output = invoke_test_pod( + write_canonical_format as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::format_etc()), + &[Value::FormatEtc(format.clone())], + ) + .unwrap(); + let Value::FormatEtc(canonical) = &output[0] else { + panic!("expected FORMATETC output"); + }; + assert_eq!(canonical, &format); + + LAST_STG_MEDIUM_HANDLE.store(0, Ordering::SeqCst); + let error = invoke_test_pod( + write_hglobal_medium_then_fail as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::stg_medium()), + &[Value::FormatEtc(format)], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + let released = windows::Win32::Foundation::HGLOBAL(std::ptr::with_exposed_provenance_mut( + LAST_STG_MEDIUM_HANDLE.load(Ordering::SeqCst), + )); + assert_eq!( + unsafe { windows::Win32::System::Memory::GlobalSize(released) }, + 0 + ); + } + + #[test] + fn canonical_format_etc_result_rules_preserve_status_and_cleanup() { + use windows::Win32::Foundation::{DATA_S_SAMEFORMATETC, S_OK}; + use windows::Win32::System::Com::{CoTaskMemAlloc, DVTARGETDEVICE, FORMATETC}; + + #[repr(C)] + struct CanonicalCall { + vtable: *const *mut c_void, + status: HRESULT, + write_output: bool, + target_device: bool, + clipboard_format: u16, + aspect: u32, + tymed: u32, + } + + unsafe extern "system" fn canonical( + this: *mut c_void, + input: *const FORMATETC, + output: *mut FORMATETC, + ) -> HRESULT { + let call = unsafe { &*this.cast::() }; + if input.is_null() || output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + if call.write_output { + let target = if call.target_device { + let target = unsafe { CoTaskMemAlloc(size_of::()) }; + if target.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::write_bytes(target.cast::(), 0, size_of::()) + }; + target.cast() + } else { + std::ptr::null_mut() + }; + unsafe { + output.write(FORMATETC { + cfFormat: call.clipboard_format, + ptd: target, + dwAspect: call.aspect, + lindex: -1, + tymed: call.tymed, + }); + } + } + call.status + } + + let table = MetadataTable::new(); + let input = FormatEtcValue::hglobal(13, 1, -1).unwrap(); + let ordinary = || { + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::format_etc()) + .preserve_hresult() + }; + let method = ordinary() + .canonical_format_etc_result(0, 1) + .build(0) + .unwrap(); + let vtable = [canonical as *mut c_void]; + let mut call = CanonicalCall { + vtable: vtable.as_ptr(), + status: S_OK, + write_output: true, + target_device: false, + clipboard_format: 1, + aspect: 2, + tymed: 0, + }; + let invoke = |call: &mut CanonicalCall| { + method.plan.invoke_values( + (call as *mut CanonicalCall).cast(), + &[Value::FormatEtc(input.clone())], + ) + }; + for tymed in [0, u32::MAX] { + call.tymed = tymed; + let result = invoke(&mut call).unwrap(); + assert!(matches!(&result[0], Value::WinRt(WinRTValue::HResult(hr)) if *hr == S_OK)); + let Value::FormatEtc(format) = &result[1] else { + panic!("expected canonical FORMATETC value"); + }; + assert_eq!(format.clipboard_format(), 1); + assert_eq!(format.aspect(), 2); + assert_eq!(format.tymed(), input.tymed()); + } + + call.status = DATA_S_SAMEFORMATETC; + call.clipboard_format = 0; + call.aspect = 0; + for write_output in [false, true] { + call.write_output = write_output; + let result = invoke(&mut call).unwrap(); + assert!( + matches!(&result[0], Value::WinRt(WinRTValue::HResult(hr)) if *hr == DATA_S_SAMEFORMATETC) + ); + assert!(matches!(&result[1], Value::FormatEtc(format) if format == &input)); + } + + call.write_output = true; + call.clipboard_format = 1; + call.aspect = 2; + call.tymed = 0; + call.target_device = true; + for (status, message) in [ + (S_OK, "target-device output is not supported"), + (HRESULT(0x80004005u32 as i32), "80004005"), + (HRESULT(1), "unexpected canonical FORMATETC success HRESULT"), + ] { + call.status = status; + crate::native_call::reset_co_task_mem_test_frees(); + let error = invoke(&mut call).unwrap_err(); + assert!(error.message().contains(message), "{}", error.message()); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + } + + call.status = S_OK; + call.target_device = false; + let error = ordinary() + .build(0) + .unwrap() + .plan + .invoke_values( + (&mut call as *mut CanonicalCall).cast(), + &[Value::FormatEtc(input)], + ) + .unwrap_err(); + assert!(error.message().contains("only TYMED_HGLOBAL")); + } + + #[test] + fn canonical_format_etc_signature_rejects_other_shapes() { + let table = MetadataTable::new(); + let valid = || { + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::format_etc()) + .preserve_hresult() + }; + for (input, output) in [(1, 0), (0, 0), (0, usize::MAX)] { + assert!( + valid() + .canonical_format_etc_result(input, output) + .build(0) + .is_err() + ); + } + assert!( + MethodSignature::new(&table) + .add_in(Type::format_etc()) + .add_out(Type::format_etc()) + .canonical_format_etc_result(0, 1) + .build(0) + .is_err() + ); + assert!( + MethodSignature::new(&table) + .add_in(Type::stg_medium()) + .add_out(Type::format_etc()) + .preserve_hresult() + .canonical_format_etc_result(0, 1) + .build(0) + .is_err() + ); + assert!( + MethodSignature::new(&table) + .add_nullable_in(Type::format_etc()) + .add_out(Type::format_etc()) + .preserve_hresult() + .canonical_format_etc_result(0, 1) + .build(0) + .is_err() + ); + } + #[test] fn excep_info_deferred_fill_runs_once_and_cleans_on_every_failure_path() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index aa4b30ce..3c570f59 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -36,6 +36,8 @@ pub(crate) enum NativeCallValue { PropVariant(crate::com::PropVariantValue), ExcepInfo(crate::com::ExcepInfoValue), StatStg(crate::com::StatStgValue), + FormatEtc(crate::com::FormatEtcValue), + StgMedium(crate::com::StgMediumValue), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -74,6 +76,8 @@ pub(crate) enum ParameterType { DispatchParams, ExcepInfo, StatStg, + FormatEtc, + StgMedium, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -228,6 +232,14 @@ impl ParameterType { Self::StatStg } + pub(crate) fn format_etc() -> Self { + Self::FormatEtc + } + + pub(crate) fn stg_medium() -> Self { + Self::StgMedium + } + pub(crate) fn as_winrt(&self) -> Option<&TypeHandle> { match self { Self::WinRT(typ) => Some(typ), @@ -244,7 +256,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => None, + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => None, } } @@ -263,7 +277,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => None, + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => None, } } @@ -348,6 +364,14 @@ impl ParameterType { matches!(self, Self::StatStg) } + pub(crate) fn is_format_etc(&self) -> bool { + matches!(self, Self::FormatEtc) + } + + pub(crate) fn is_stg_medium(&self) -> bool { + matches!(self, Self::StgMedium) + } + pub(crate) fn is_array(&self) -> bool { self.as_winrt().is_some_and(TypeHandle::is_array) } @@ -376,6 +400,7 @@ impl ParameterType { | Self::NativeStruct(_) | Self::NativeStructPointer { .. } | Self::NativeUnion(_) + | Self::StgMedium ) || matches!( self, Self::WinRT(typ) @@ -413,7 +438,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => AbiType::Ptr, + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => AbiType::Ptr, Self::NativeStruct(_) | Self::NativeUnion(_) | Self::VariantByValue => { panic!("aggregate values do not have a scalar AbiType") } @@ -433,7 +460,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => libffi::middle::Type::pointer(), + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => libffi::middle::Type::pointer(), Self::NativeStruct(layout) => layout.libffi_type(), Self::NativeUnion(layout) => layout.libffi_type(), Self::VariantByValue => variant_by_value_libffi_type(), @@ -468,7 +497,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => { + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => { panic!("native POD storage is allocated by the dynamic executor") } } @@ -490,7 +521,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg => { + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium => { unreachable!("native POD output conversion uses NativeStructValue") } } @@ -527,7 +560,9 @@ impl ParameterType { | Self::PropVariant | Self::DispatchParams | Self::ExcepInfo - | Self::StatStg, + | Self::StatStg + | Self::FormatEtc + | Self::StgMedium, _, ) => { unreachable!("native POD output conversion uses NativeStructValue") @@ -546,6 +581,8 @@ impl ParameterType { Self::PropVariant => OutputCleanup::PropVariantClear, Self::ExcepInfo => OutputCleanup::None, Self::StatStg => OutputCleanup::None, + Self::FormatEtc => OutputCleanup::None, + Self::StgMedium => OutputCleanup::None, Self::Bstr { .. } => OutputCleanup::BstrFree, Self::CoTaskMemWideString => OutputCleanup::CoTaskMemFree, Self::WinRT(_) @@ -589,6 +626,7 @@ pub enum ParamKind { pub struct Parameter { pub(crate) typ: ParameterType, pub(crate) output_cleanup: OutputCleanup, + pub(crate) canonical_format_input: Option, /// Index in the method result vector for out and FillArray parameters. pub value_index: usize, /// Index in the caller-provided argument slice. FillArray parameters have @@ -686,6 +724,7 @@ impl AbiMethodSignature { kind: ParamKind::In, typ, output_cleanup: OutputCleanup::None, + canonical_format_input: None, value_index: input_index, input_index: Some(input_index), }); @@ -707,6 +746,7 @@ impl AbiMethodSignature { kind: ParamKind::Out, typ, output_cleanup, + canonical_format_input: None, value_index: self.out_count, input_index: None, }); @@ -725,6 +765,7 @@ impl AbiMethodSignature { kind: ParamKind::OptionalOut, typ, output_cleanup, + canonical_format_input: None, value_index: self.out_count, input_index: Some(input_index), }); @@ -753,6 +794,7 @@ impl AbiMethodSignature { kind: ParamKind::InOut, typ, output_cleanup, + canonical_format_input: None, value_index: self.out_count, input_index: Some(input_index), }); @@ -767,6 +809,7 @@ impl AbiMethodSignature { kind: ParamKind::OutFillArray, typ, output_cleanup: OutputCleanup::None, + canonical_format_input: None, value_index: self.out_count, input_index: Some(input_index), }); @@ -816,6 +859,8 @@ impl AbiMethodSignature { || p.typ.is_dispatch_params() || p.typ.is_excep_info() || p.typ.is_stat_stg() + || p.typ.is_format_etc() + || p.typ.is_stg_medium() }); // Check if the single in-param (if any) is a simple non-HString, non-Struct type @@ -917,6 +962,7 @@ pub(crate) fn lower_completed_method( index: usize, parameters: Vec<(ParamKind, ParameterType, OutputCleanup)>, return_kind: MethodReturn, + canonical_format_etc: Option<(usize, usize)>, ) -> Method { let mut signature = AbiMethodSignature::new(table); for (kind, typ, cleanup) in parameters { @@ -935,6 +981,13 @@ pub(crate) fn lower_completed_method( }; } signature.return_kind = return_kind; + if let Some((input, output)) = canonical_format_etc { + signature.parameters[output].canonical_format_input = Some( + signature.parameters[input] + .input_index + .expect("validated canonical FORMATETC input parameter"), + ); + } signature.build(index) } @@ -1349,7 +1402,9 @@ impl call::ArgumentList for ComInvocationArgs<'_> { | crate::com::Value::PropVariant(_) | crate::com::Value::DispatchParams(_) | crate::com::Value::ExcepInfo(_) - | crate::com::Value::StatStg(_) => { + | crate::com::Value::StatStg(_) + | crate::com::Value::FormatEtc(_) + | crate::com::Value::StgMedium(_) => { panic!("COM-local argument requested as a WinRT value") } crate::com::Value::Buffer(_) => { @@ -1406,6 +1461,20 @@ impl call::ArgumentList for ComInvocationArgs<'_> { _ => None, } } + + fn get_format_etc(&self, index: usize) -> Option<&crate::com::FormatEtcValue> { + match &self.original[index] { + crate::com::Value::FormatEtc(value) => Some(value), + _ => None, + } + } + + fn get_stg_medium(&self, index: usize) -> Option<&crate::com::StgMediumValue> { + match &self.original[index] { + crate::com::Value::StgMedium(value) => Some(value), + _ => None, + } + } } impl Method { @@ -1441,6 +1510,8 @@ impl Method { || parameter.typ.is_dispatch_params() || parameter.typ.is_excep_info() || parameter.typ.is_stat_stg() + || parameter.typ.is_format_etc() + || parameter.typ.is_stg_medium() }) || self.direct_return_type().is_some_and(|typ| { typ.native_struct_layout().is_some() || typ.native_union_layout().is_some() @@ -1452,6 +1523,8 @@ impl Method { || typ.is_dispatch_params() || typ.is_excep_info() || typ.is_stat_stg() + || typ.is_format_etc() + || typ.is_stg_medium() }) } @@ -1951,7 +2024,9 @@ impl Method { | NativeCallValue::SafeArray(_) | NativeCallValue::PropVariant(_) | NativeCallValue::ExcepInfo(_) - | NativeCallValue::StatStg(_) => Err(invalid_argument( + | NativeCallValue::StatStg(_) + | NativeCallValue::FormatEtc(_) + | NativeCallValue::StgMedium(_) => Err(invalid_argument( "COM-local result reached the WinRT invocation path", )), }) @@ -2143,6 +2218,24 @@ impl Method { continue; } + if parameter.typ.is_format_etc() { + if !matches!(&args[input_index], crate::com::Value::FormatEtc(_)) { + return Err(invalid_argument( + "Argument type mismatch: expected FORMATETC", + )); + } + continue; + } + + if parameter.typ.is_stg_medium() { + if !matches!(&args[input_index], crate::com::Value::StgMedium(_)) { + return Err(invalid_argument( + "Argument type mismatch: expected STGMEDIUM", + )); + } + continue; + } + let crate::com::Value::WinRt(value) = &args[input_index] else { return Err(invalid_argument( "COM-local value passed to a scalar or pointer parameter", @@ -2209,6 +2302,8 @@ impl Method { NativeCallValue::PropVariant(value) => crate::com::Value::PropVariant(value), NativeCallValue::ExcepInfo(value) => crate::com::Value::ExcepInfo(value), NativeCallValue::StatStg(value) => crate::com::Value::StatStg(value), + NativeCallValue::FormatEtc(value) => crate::com::Value::FormatEtc(value), + NativeCallValue::StgMedium(value) => crate::com::Value::StgMedium(value), }) .collect() }) diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index f7a5f358..a380e6cd 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -335,11 +335,14 @@ Current code registries are migrated without changing behavior: - semantic HRESULT exceptions; - `IWbemServices::OpenNamespace`; - `IDispatch::Invoke` compound behavior; -- `STATSTG` and allocator-specific outputs; and +- `STATSTG` and allocator-specific outputs; +- `IDataObject::GetDataHere` caller-allocated, non-replacing STGMEDIUM InOut; +- `IDataObject::SetData` and `IOleCache::SetData` caller-retained STGMEDIUM ownership; +- `IDataObject::GetCanonicalFormatEtc` output validity and ignored `tymed`; and - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,681/7,929 safe census, generated unsafe manifests, and all live tests agree +5,691/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -400,19 +403,19 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,326 | -| `exact_registry_dependent` | 355 | -| **Total** | **5,681** | +| `standard_derived` | 5,333 | +| `exact_registry_dependent` | 358 | +| **Total** | **5,691** | -The registry contains **495 declared entries**, all 495 match the pinned -metadata, and 404 distinct entries are consumed by safe plans. Safe plans have -655 entry/interface dependencies and 404 family/interface dependencies. -Per-interface dependency-set totals also include 5,974 metadata-attribute -dependencies and 26,076 COM-standard-rule dependencies. +The registry contains **499 declared entries**, all 499 match the pinned +metadata, and 408 distinct entries are consumed by safe plans. Safe plans have +660 entry/interface dependencies and 408 family/interface dependencies. +Per-interface dependency-set totals also include 5,976 metadata-attribute +dependencies and 26,114 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 172 | +| `ownership` | 176 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 7 | @@ -422,7 +425,7 @@ dependencies and 26,076 COM-standard-rule dependencies. | `enumerator-next` | 74 | | `borrowed-handle` | 54 | | `counted-buffer` | 16 | -| `semantic-hresult` | 2 | +| `semantic-hresult` | 3 | | `compound-dispatch` | 1 | Family rollups deliberately count each interface once per family: @@ -435,10 +438,10 @@ 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` | 162 | 111 | 116 | +| `com.ownership.v1` | 165 | 114 | 119 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | -| `com.semantic-hresult.v1` | 1 | 1 | 2 | +| `com.semantic-hresult.v1` | 2 | 2 | 3 | | `automation.idispatch-invoke.v1` | 1 | 1 | 1 | | `graphics.private-data-hazard.v1` | 7 | 0 | 0 | | `shell.flag-selected-string.v1` | 1 | 1 | 3 | @@ -453,11 +456,11 @@ 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,568 | -| `com.interface.input-borrow.v1` | 1,881 | -| `com.interface.typed-output-plus-one.v1` | 3,453 | -| `com.iunknown.identity-refcount.v1` | 5,681 | -| `com.query-interface.output-plus-one.v1` | 5,681 | +| `com.hresult.failure.v1` | 5,573 | +| `com.interface.input-borrow.v1` | 1,890 | +| `com.interface.typed-output-plus-one.v1` | 3,457 | +| `com.iunknown.identity-refcount.v1` | 5,691 | +| `com.query-interface.output-plus-one.v1` | 5,691 | | `com.standard-cleanup.matching-allocator.v1` | 1,436 | These are dependency counts: an inherited contract can be consumed by several diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index b2c588c1..c8484b27 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,681 complete safe -> interface projections out of 7,929 eligible interfaces (71.65%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,691 complete safe +> interface projections out of 7,929 eligible interfaces (71.77%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -613,6 +613,7 @@ and `@microsoft/dynwinrt/com`. | DISPPARAMS / EXCEPINFO | Exact `IDispatch::Invoke` input/output contracts, dedicated JS wrappers, optional null outputs, deferred fill, and failure cleanup | Output/InOut DISPPARAMS, input/InOut EXCEPINFO, nested occurrences, and arbitrary deferred/function-pointer contracts | | SAFEARRAY | Rank 1–8, signed bounds, typed scalar/bool/BSTR/interface/VARIANT elements, SafeArray API validation and cleanup | Unsupported element VARTYPEs, rank > 8, untyped arrays whose VARTYPE cannot be proven, and Automation InOut replacement | | PROPVARIANT | Scalar numeric/bool, LPWSTR, CLSID, FILETIME, blob, and supported vectors with PropVariantClear | Nested VARIANT vectors, streams/interfaces, arrays, clipboard/storage types, BYREF, and unknown VARTYPEs | +| FORMATETC / STGMEDIUM | Dedicated target-device-independent `TYMED_HGLOBAL` values; owned outputs use `ReleaseStgMedium`; exact `IDataObject::GetDataHere` evidence permits caller-allocation-preserving InOut; exact IID/slot/shape/fingerprint evidence pins `SetData.fRelease=FALSE` | `DVTARGETDEVICE`, non-HGLOBAL media, unproven InOut contracts, JavaScript callback implementation, and ownership-transfer input | | Allocator ownership | COM Release, BSTR output/replacement and array elements, VARIANT clear, CoTaskMem buffers/PWSTR elements, boxed GUID, retained JS buffers | LocalFree, custom allocators, allocator interfaces, unknown ownership | | Interface pointers | Typed input/output interfaces, QueryInterface, dynamic IID output, and generated multi-interface callback objects with inherited IID aliases | Interface in/out replacement, aggregation, and `IInspectable` implementation | | Apartments | Explicit initialization, non-agile owner-thread implementations, synchronous same-thread callbacks, and rejection before entering JS on a foreign thread | Cross-apartment marshaling, GIT/agility handling, and callback dispatch | @@ -630,7 +631,8 @@ and `@microsoft/dynwinrt/com`. - unsupported SAFEARRAY element types/ranks and InOut replacement; - BSTR pointer nesting, scalar input `BSTR*`, callee-allocated outer arrays without exact allocators, and unknown/custom BSTR allocation contracts; -- FORMATETC and STGMEDIUM; +- `DVTARGETDEVICE`, non-HGLOBAL FORMATETC/STGMEDIUM alternatives, and + FORMATETC/STGMEDIUM callback methods; - callback methods containing unmodeled ownership, Automation, union, array, or interface-replacement contracts; - cross-thread/apartment marshaling; and @@ -656,6 +658,7 @@ and `@microsoft/dynwinrt/com`. | VARIANT | Supported subset | Dedicated `DynComVariant`; supported tags are VT_EMPTY, VT_NULL, I1/UI1/I2/UI2/I4/UI4/I8/UI8/INT/UINT, R4/R8, BOOL, BSTR, UNKNOWN, DISPATCH, and arrays of supported SAFEARRAY elements. Pointer contracts remain distinct from required input-only by-value aggregates. | | SAFEARRAY | Supported subset | `DynComSafeArray` preserves rank/bounds and validates VARTYPE and element width through SafeArray APIs. Supported elements are the scalar integer/float family, VARIANT_BOOL, BSTR, IUnknown, IDispatch, and VARIANT. | | PROPVARIANT | Supported subset | `DynComPropVariant` supports the scalar family, LPWSTR, CLSID, FILETIME, BLOB, and vectors of numeric/bool/string/GUID/FILETIME elements. | +| FORMATETC / STGMEDIUM | Supported HGLOBAL subset | `DynComFormatEtc.hglobal()` represents one exact DVASPECT with `ptd == NULL`; `DynComStgMedium.hglobal()` copies bytes into call-local movable HGLOBAL storage. Outputs are copied before `ReleaseStgMedium`, `GetDataHere` rejects replacement of caller-owned storage, and generated `IDataObject::SetData` and `IOleCache::SetData` (including `IOleCache2`) fix `fRelease` to `FALSE`. | | DISPPARAMS / EXCEPINFO | Supported for `IDispatch::Invoke` | `DynComDispatchParams` accepts natural-order `DynComVariant[]` plus optional named DISPIDs. `DynComExcepInfo` exposes code/source/description/helpFile/helpContext/scode. Optional Invoke outputs pass native null when not requested. | | Typed interface parameters and outputs | Supported | Interface outputs carry an owned COM reference. | | Opaque pointers and handle-shaped typedefs | Supported with limits | They are pointer values, not COM objects. Cleanup remains type-specific. | @@ -677,6 +680,22 @@ and `@microsoft/dynwinrt/com`. | 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. | | Explicit apartment initialization | Supported | `initializeCom()` never silently chooses an apartment for the caller. | +`IDataObject::GetCanonicalFormatEtc` has a separate result contract. For `S_OK`, +the runtime ignores the native output's `tymed` and retains the caller's +supported transfer medium while decoding the remaining canonical fields. +For `DATA_S_SAMEFORMATETC`, the returned value is a copy of the input; the unused +output is not decoded or adopted. The native HRESULT is preserved in both +cases. Other FORMATETC outputs retain the strict HGLOBAL validator, and +unsupported target-device output is cleaned and rejected. + +STGMEDIUM InOut is not a type-wide capability. Its safe projection requires +exact caller-allocation-preservation evidence, currently registered only for +`IDataObject::GetDataHere`. The callee must not resize or replace the HGLOBAL, +and the caller retains cleanup responsibility. `IWiaDataTransfer::idtGetData` +has a separate property-selected file-transfer and filename-output contract; +it is not safe-generated. Its unsafe/raw capabilities remain subject to the +existing layout and contract restrictions. + The generator emits native POD storage only after every architecture-specific layout fact has been validated. A `Buffer` in this path represents the struct's backing bytes/address; it is not interpreted as pointer-width handle bits. @@ -704,8 +723,8 @@ of every type in the 24 MB metadata file. | Unsupported `PROPVARIANT` alternatives | Property System | Streams/interfaces, arrays, clipboard/storage alternatives, nested VT_VECTOR\|VT_VARIANT, BYREF, and unknown combinations are rejected. | Runtime validation + Win32 winmd signature | | Native structs with nested owned pointers outside dedicated contracts | Storage and Shell APIs | `STATSTG` has a dedicated output-only model that adopts and frees its CoTaskMem name on every success and failure path. Arbitrary nested pointer structs still fail closed. | Runtime ownership tests + Win32 winmd signature | | Unsupported `SAFEARRAY` shapes | Automation and Office-style COM APIs | Exact declaration-registry entries support documented `VT_I4`, `VT_UI1`, `VT_UI4`, `VT_R8`, `VT_BSTR`, `VT_VARIANT`, and `VT_UNKNOWN` plus an exact interface IID. Unknown VARTYPE, signature drift, input `SAFEARRAY**`, InOut replacement, unsupported records/dispatch contracts, rank > 8, inconsistent bounds/length/element width, and unproven nullable outputs are rejected. | Exact Microsoft citations + SafeArray API validation + Win32 winmd signatures | -| `FORMATETC` / `STGMEDIUM` | `IDataObject`, clipboard, drag-and-drop | `STGMEDIUM` is a union of handles and interfaces with type-specific release behavior. | Win32 winmd + codegen diagnostic | -| Untagged/by-value/output/nested unions, bitfields, flexible arrays, and nested owned-resource structs | `STGMEDIUM`, `STRRET`, `BINDPTR`, audio/media formats | Tagged pointer-input unions support only safely POD fields. Missing discriminants, nested unions, BSTR/interfaces/resources, bitfields, and flexible tails fail closed. | Win32 winmd + codegen diagnostics | +| Unsupported `FORMATETC` / `STGMEDIUM` alternatives | `IDataObject`, clipboard, drag-and-drop | The dedicated model currently accepts only target-device-independent `TYMED_HGLOBAL`. `DVTARGETDEVICE`, GDI, metafile, file, stream, storage, and callback shapes remain closed until their own layout and ownership contracts exist. | Win32 winmd + Microsoft FORMATETC/STGMEDIUM contracts | +| Untagged/by-value/output/nested unions, bitfields, flexible arrays, and nested owned-resource structs | `STRRET`, `BINDPTR`, audio/media formats | Dedicated STGMEDIUM handling does not generalize to arbitrary unions. Tagged pointer-input unions support only safely POD fields. Missing discriminants, nested unions, BSTR/interfaces/resources, bitfields, and flexible tails fail closed. | Win32 winmd + codegen diagnostics | | Unknown packing or non-authoritative explicit offsets | Explicit/packed native records | Exact x86/x64/ARM64 size, alignment, and field offsets are mandatory. Missing facts fail closed rather than assuming the host compiler's defaults. | Layout validation policy | | Writable caller-sized native arrays outside the modeled subset | Owning, pointer-element, native-POD, or incompletely described arrays | `IDispatch::GetIDsOfNames` is supported in the complete interface when one metadata count unambiguously groups borrowed string pointers with plain scalar output. Missing count direction, element layout/ownership, or an unambiguous group still fails closed. | Win32 winmd `NativeArrayInfo` + semantic validation | | Unsupported BSTR pointer nesting, replacement arrays, or callee-allocated outer arrays | Automation collection APIs | Exact counted input/caller-output BSTR arrays are supported; deeper/replacement shapes still require authoritative outer allocation and per-element contracts. | Win32 winmd signature + ownership analysis | @@ -718,10 +737,11 @@ of every type in the 24 MB metadata file. | General out-of-process activation controls | Custom `CLSCTX` scenarios | The unsafe runtime's `DynCom.coCreateInstance()` currently uses `CLSCTX_INPROC_SERVER`. | Runtime/public-API boundary | | Flat Win32 DLL exports | `CreateFile`, registry functions, GDI, etc. | These are not COM interfaces and need a separate DLL-export/handle model. | Architecture boundary | -Consequently, `IDataObject` remains an important, widely encountered interface -that is not currently supported as a complete generated binding. -`IPropertyStore` and `IDispatch` are complete; derived Automation interfaces -still validate all of their additional methods independently. +Consequently, `IDataObject` now generates completely for the closed HGLOBAL +subset. Unsupported target-device and storage-medium inputs cannot be +constructed, while an unsupported native output is cleaned and rejected during +decoding. `IPropertyStore` and `IDispatch` are complete; derived Automation +interfaces still validate all of their additional methods independently. ## Complete-interface census after by-value VARIANT @@ -1222,13 +1242,15 @@ parameters to be exact Out values, and separating counted character pointers from terminated strings, the HWND-specific census was **5,567 / 7,929**. The exact CoTaskMem output-ownership, parameter-direction, and null-input registries subsequently promote 114 additional complete interfaces, bringing -the current literal census to -**5,681 / 7,929 = 71.648379%**. The result remains above the 70% target without -admitting any creator-owned, destroyable, InOut, undocumented, optional, or -`HWND**` shape. +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 +the current literal census to **5,691 / 7,929 = 71.774499%**. The result remains +above the 70% target without admitting any unmodeled target-device, storage +medium, 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,681, or coverage +if the denominator changes, complete generation drops below 5,691, or coverage falls below 70%. ## Public-code frequency snapshot @@ -1276,7 +1298,7 @@ against the resolved namespace. |---:|---|---:|---:|---|---| | 1 | `ID3D11Device` | 27,552 | 87 | Yes | Fail closed: untyped output ownership | | 2 | `IDXGIFactory` | 17,432 | 83 | Yes | Fail closed: untyped output ownership | -| 3 | `IDataObject` | 10,648 | 44 | Yes | Fail closed: `STGMEDIUM` has unmodeled discriminant/resource ownership | +| 3 | `IDataObject` | 10,648 | 44 | Yes | Generates completely for target-device-independent `TYMED_HGLOBAL`; generated fake-vtable coverage exercises GetData/GetDataHere/Query/GetCanonical/SetData | | 4 | `IMalloc` | 10,624 | 56 | Yes | Generates completely and is live-tested through `CoGetMalloc` | | 5 | `IClassFactory` | 6,712 | 70 | Yes | Generates completely and is live-tested through `CoGetClassObject` | | 6 | `IDispatch` via `IID_IDispatch` | 6,408 | 46 | Yes | Complete inherited interface generates; `Invoke` uses dedicated DISPPARAMS/EXCEPINFO and explicit optional-output requests | @@ -1309,13 +1331,14 @@ against the resolved namespace. - **29 of 30** candidates are defined as `IUnknown`-rooted interfaces in Windows.Win32.winmd. `ICoreWebView2` is the only external-metadata case. -- **23 of 29** Win32-metadata candidates pass complete codegen validation. - **6 of 29** fail closed on an unsupported ABI or ownership shape. +- **24 of 29** Win32-metadata candidates pass complete codegen validation. + **5 of 29** fail closed on an unsupported ABI or ownership shape. - Among the **top 10** by `.cpp` hits, only `IClassFactory`, - `IDispatch`, `IPersistFile`, `IConnectionPoint`, `IWICImagingFactory`, and - `IMalloc` pass complete codegen. + `IDataObject`, `IDispatch`, `IPersistFile`, `IConnectionPoint`, + `IWICImagingFactory`, and `IMalloc` pass complete codegen. - The largest unsupported demand clusters are: - - discriminated resource unions and non-POD layout (`IDataObject`, parts of Shell and streams); + - discriminated resource unions and non-POD layout (parts of Shell, streams, + and non-HGLOBAL data-transfer media); - Automation contracts beyond the exact supported `IDispatch` compounds (XML and Task Scheduler BYREF/InOut and nested ownership); - explicit output ownership (`DXGI`, audio); @@ -1330,7 +1353,7 @@ against the resolved namespace. This means the current suite provides useful ABI breadth, but it does **not** cover every high-frequency interface. In particular, -`IDataObject`, graphics interfaces, audio, and live real-object +graphics interfaces, audio, non-HGLOBAL data transfer, and live real-object `IDispatch::Invoke` coverage remain material gaps. ## Engineering priority map @@ -1363,7 +1386,7 @@ hardware, and whether it adds a distinct ABI shape. | `IAudioClient` | Low-level audio streaming | Fails closed because its format and output-pointer shapes are not fully modeled. | | `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. | | `IPropertyStore` | Shell/property metadata | Complete generation and live ShellLink `SetValue`/`GetValue`/`Commit` coverage pass with dedicated PROPVARIANT ownership. | -| `IDataObject` | Clipboard and drag-and-drop | Unsupported until FORMATETC and STGMEDIUM are modeled. | +| `IDataObject` | Clipboard and drag-and-drop | Complete safe generation for target-device-independent `TYMED_HGLOBAL`; generated fake-vtable coverage verifies owned GetData output, caller-owned GetDataHere storage, semantic HRESULT, canonical FORMATETC, and borrowed SetData input. | ## Automated coverage diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 5222e7ca..14a4b760 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,681 | 71.65% | -| Rejected because at least one contract is incomplete | 2,248 | 28.35% | +| Complete safe generation | 5,691 | 71.77% | +| Rejected because at least one contract is incomplete | 2,238 | 28.23% | 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,681 figure is semantic codegen coverage, not a claim that every interface +The 5,691 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: @@ -128,7 +128,7 @@ implementation, aggregation, or custom marshaling. | API or family | Current blocker | Raw direction | | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `IDataObject` and clipboard/drag-and-drop | `FORMATETC` and `STGMEDIUM` combine unions, handles, interfaces, and release rules. | Opaque aligned storage and explicit `ReleaseStgMedium`, followed by a dedicated semantic wrapper. | +| Non-HGLOBAL/device-specific clipboard and drag-and-drop | `DVTARGETDEVICE` and the remaining `STGMEDIUM` alternatives have distinct layout and release rules. | Opaque aligned storage and explicit type-specific cleanup until each semantic alternative exists. | | `IAudioClient` format negotiation | Variable audio-format layouts and untyped CoTaskMem output. | Raw format memory plus pointer output; later add a typed audio-format value. | | DXGI/D3D `GetPrivateData` | The same payload may be bytes or an AddRef'd interface pointer. | Caller-selected byte storage or pointer slot with explicit adoption. | | Generic typed interface `InOut` | Replacing an interface pointer requires explicit old/new reference transfer. | `UnsafeInterfaceReplacement` with one independent `+1` owner per slot. | @@ -342,33 +342,33 @@ 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,442 of 1,446** x64 manual-contract interfaces now have at least one portable -executable generated high-level method. **1,441** have an executable manual +**1,433 of 1,437** x64 manual-contract interfaces now have at least one portable +executable generated high-level method. **1,432** 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,083 executable +target. Across the portable generated surface there are **6,067 executable manual methods**, **0 remaining portable manual-classified methods omitted**, -and **1,163 runtime-blocked methods** still omitted. +and **1,161 runtime-blocked methods** still omitted. ### Safe contract evidence census Stage 1 of the [Classic COM contract evidence registry](../architecture/classic-com-contract-evidence-registry.md) -classifies all 5,681 safe-complete interfaces exactly once: +classifies all 5,691 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,326 | -| `exact_registry_dependent` | 355 | +| `standard_derived` | 5,333 | +| `exact_registry_dependent` | 358 | -The registry declares 495 selector-specific entries; all 495 match pinned -metadata, 404 distinct entries are safe-consumed, and safe plans contain 655 -entry/interface plus 404 family/interface dependencies. They also consume -5,974 metadata-attribute and 26,076 universal COM-rule dependency sets. +The registry declares 499 selector-specific entries; all 499 match pinned +metadata, 408 distinct entries are safe-consumed, and safe plans contain 660 +entry/interface plus 408 family/interface dependencies. They also consume +5,976 metadata-attribute and 26,114 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 172, parameter-direction 45, bounded-two-call 16, +borrowed-handle 54, ownership 176, parameter-direction 45, bounded-two-call 16, counted-buffer 16, conditional-output 7, flag-selected-buffer 3, null-input 2, -semantic-HRESULT 2, and compound-dispatch 1. Complete per-entry status, +semantic-HRESULT 3, and compound-dispatch 1. 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. @@ -378,6 +378,13 @@ entries remain typed COM standard rules. Twenty-five safe interfaces consume the generic enumerator rule because one contract is inherited. ISequentialStream `Read`/`Write` and IDispatch `Invoke` are distinct exact entries with full selectors, fingerprints, and citations. +The storage-medium contracts also pin `IOleCache::SetData` (including inherited +`IOleCache2` calls) to caller-retained ownership and describe the distinct +`IDataObject::GetCanonicalFormatEtc` success/result semantics. +STGMEDIUM InOut additionally requires the exact caller-allocation-preserving +`IDataObject::GetDataHere` contract. `IWiaDataTransfer::idtGetData` is excluded +from safe support until its distinct file-transfer and filename ownership +semantics are modeled. The strict embedded registry lives in `tools/dynwinrt-codegen/contracts/classic-com/`. JSON is the sole source for @@ -394,18 +401,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,681 of 7,929 interfaces. The separate outbound raw census -classifies the 2,248 safe-incomplete interfaces as: +the safe census is 5,691 of 7,929 interfaces. The separate outbound raw census +classifies the 2,238 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,446 | 390 | -| i686 | 411 | 1,423 | 414 | -| ARM64 | 412 | 1,446 | 390 | +| x64 | 412 | 1,437 | 389 | +| i686 | 411 | 1,414 | 413 | +| ARM64 | 412 | 1,437 | 389 | -Including safe-complete interfaces, x64 and ARM64 have 6,093 -metadata-complete, 1,446 manual, and 390 blocked interfaces. i686 has 6,092 -metadata-complete, 1,423 manual, and 414 blocked interfaces. +Including safe-complete interfaces, x64 and ARM64 have 6,103 +metadata-complete, 1,437 manual, and 389 blocked interfaces. i686 has 6,102 +metadata-complete, 1,414 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 @@ -415,14 +422,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,251 interfaces require no cleanup, 4,536 use a Phase 1 standard -cleanup, none use a known external cleanup, and 1,142 have unknown cleanup. +target, 2,237 interfaces require no cleanup, 4,530 use a Phase 1 standard +cleanup, none use a known external cleanup, and 1,162 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,681 safe-complete interfaces, cleanup is derived from the validated +For all 5,691 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, @@ -509,7 +516,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,681 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,691 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 c1645d81..9332ea9c 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": 5681, - "safe_incomplete": 2248, + "safe_complete": 5691, + "safe_incomplete": 2238, "safeEvidence": { - "safeComplete": 5681, - "standardDerived": 5326, - "exactRegistryDependent": 355, - "metadataFactOccurrences": 5974, - "comStandardFactOccurrences": 26076, - "registeredExactEntries": 495, - "metadataMatchedExactEntries": 495, - "safeConsumedExactEntries": 404, - "exactEntryInterfaceDependencies": 655, - "exactFamilyInterfaceDependencies": 404, + "safeComplete": 5691, + "standardDerived": 5333, + "exactRegistryDependent": 358, + "metadataFactOccurrences": 5976, + "comStandardFactOccurrences": 26114, + "registeredExactEntries": 499, + "metadataMatchedExactEntries": 499, + "safeConsumedExactEntries": 408, + "exactEntryInterfaceDependencies": 660, + "exactFamilyInterfaceDependencies": 408, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, @@ -102,10 +102,10 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 2, - "ownership": 172, + "ownership": 176, "parameter-direction": 45, "safearray": 263, - "semantic-hresult": 2 + "semantic-hresult": 3 }, "byEntryId": { "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": 1, @@ -445,6 +445,8 @@ "com.ownership.entry.windows-win32-storage-xps.ixpsomvisualbrush.97e294af5b3746b48057874d2f64119b.getvisuallookup.slot-21.param-0-lookup.v1": 1, "com.ownership.entry.windows-win32-system-com-structuredstorage.istorage.0000000b00000000c000000000000046.stat.slot-17.v1": 1, "com.ownership.entry.windows-win32-system-com.icatinformation.0002e01300000000c000000000000046.getcategorydesc.slot-4.param-2-pszdesc.v1": 1, + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getdatahere.slot-4.v1": 1, + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.setdata.slot-7.v1": 1, "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.alloc.slot-3.v1": 1, "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.didalloc.slot-7.v1": 1, "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.free.slot-5.v1": 1, @@ -454,6 +456,7 @@ "com.ownership.entry.windows-win32-system-com.ipersistfile.0000010b00000000c000000000000046.getcurfile.slot-8.param-0-ppszfilename.v1": 2, "com.ownership.entry.windows-win32-system-com.istream.0000000c00000000c000000000000046.stat.slot-12.v1": 5, "com.ownership.entry.windows-win32-system-mmc.iheaderctrl.43136eb3d36c11cfadbc00aa00a80033.getcolumntext.slot-6.param-1-ptext.v1": 1, + "com.ownership.entry.windows-win32-system-ole.iolecache.0000011e00000000c000000000000046.setdata.slot-7.v1": 2, "com.ownership.entry.windows-win32-system-search.imetadata.780102b0c43b4876bc7b5e9ba5c88794.getdata.slot-3.param-0-ppszkey.v1": 1, "com.ownership.entry.windows-win32-system-search.imetadata.780102b0c43b4876bc7b5e9ba5c88794.getdata.slot-3.param-1-ppszvalue.v1": 1, "com.ownership.entry.windows-win32-system-search.inamedentity.abdbd0b17d5449fbab5cbff4130004cd.defaultphrase.slot-4.param-0-ppszphrase.v1": 1, @@ -483,6 +486,7 @@ "com.parameter-direction.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getstring.slot-12.param-3-pcchlength.v1": 15, "com.reserved-null-input.entry.windows-win32-system-com-structuredstorage.istorage.0000000b00000000c000000000000046.enumelements.slot-11.param-1-reserved2.v1": 1, "com.reserved-null-input.entry.windows-win32-system-com-structuredstorage.istorage.0000000b00000000c000000000000046.openstream.slot-4.param-1-reserved1.v1": 1, + "com.semantic-hresult.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getcanonicalformatetc.slot-6.v1": 1, "com.semantic-hresult.entry.windows-win32-system-com.ipersistfile.0000010b00000000c000000000000046.getcurfile.slot-8.v1": 2, "com.sequential-stream-buffer.entry.windows-win32-system-com.isequentialstream.0c733a302a1c11ceade500aa0044773d.read.slot-3.param-0-pv.v1": 7, "com.sequential-stream-buffer.entry.windows-win32-system-com.isequentialstream.0c733a302a1c11ceade500aa0044773d.write.slot-4.param-0-pv.v1": 7, @@ -519,18 +523,18 @@ "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, - "com.ownership.v1": 116, + "com.ownership.v1": 119, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, - "com.semantic-hresult.v1": 2, + "com.semantic-hresult.v1": 3, "com.sequential-stream-buffer.v1": 7, "shell.flag-selected-string.v1": 3, "windows.borrowed-hwnd-output.v1": 45, "wmi.conditional-output.v1": 1 }, "byMetadataAttribute": { - "CanReturnMultipleSuccessValuesAttribute": 42, - "ConstAttribute": 3327, + "CanReturnMultipleSuccessValuesAttribute": 43, + "ConstAttribute": 3328, "FreeWithAttribute": 3, "NativeArrayInfoAttribute": 2602 }, @@ -540,11 +544,11 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5568, - "com.interface.input-borrow.v1": 1881, - "com.interface.typed-output-plus-one.v1": 3453, - "com.iunknown.identity-refcount.v1": 5681, - "com.query-interface.output-plus-one.v1": 5681, + "com.hresult.failure.v1": 5573, + "com.interface.input-borrow.v1": 1890, + "com.interface.typed-output-plus-one.v1": 3457, + "com.iunknown.identity-refcount.v1": 5691, + "com.query-interface.output-plus-one.v1": 5691, "com.standard-cleanup.matching-allocator.v1": 1436 }, "exactEntryStatus": { @@ -4966,7 +4970,7 @@ "slot": 15, "parameter": null }, - "sourceFingerprint": "1B89A2E869A1ED374C21050F3BB13F09929D6D9F9B5943EAAFC345EFDA825014", + "sourceFingerprint": "A5343D6AEAFA7833E8F245B3F31FF29258F3282002CA64CAD896AC24FB509DF9", "citation": "https://learn.microsoft.com/windows/win32/api/mfobjects/nf-mfobjects-imfattributes-getblob", "registered": true, "metadataMatched": true, @@ -8881,7 +8885,7 @@ "slot": 17, "parameter": null }, - "sourceFingerprint": "22517D81811094DCECE75634DC1BA343E41E60AD54433B9124934646A2D56877", + "sourceFingerprint": "1DB59BBEEDA81F2FC282009B93D5BFB15CAD142B71CD0F3E3A0DC5DC0F430270", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-istorage-stat", "registered": true, "metadataMatched": true, @@ -8909,6 +8913,42 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getdatahere.slot-4.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.System.Com", + "interface": "IDataObject", + "iid": "0000010e-0000-0000-c000-000000000046", + "method": "GetDataHere", + "slot": 4, + "parameter": null + }, + "sourceFingerprint": "65165D814B216835E273E9342B4CBEC2A4F6F1A68477F3F07036C2479BDADBFF", + "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-getdatahere", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.setdata.slot-7.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.System.Com", + "interface": "IDataObject", + "iid": "0000010e-0000-0000-c000-000000000046", + "method": "SetData", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1", + "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-setdata", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.alloc.slot-3.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -8920,7 +8960,7 @@ "slot": 3, "parameter": null }, - "sourceFingerprint": "2A96941D7141039452FE007E69FB04C3AA6CE28DFF7B96115B6C919DC6B42A69", + "sourceFingerprint": "095F011D5BE23DA24EA7CA4309C53CCF4ECB8B8B60BCA0846742499F1E84898A", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-alloc", "registered": true, "metadataMatched": true, @@ -8938,7 +8978,7 @@ "slot": 7, "parameter": null }, - "sourceFingerprint": "A74ACDD3DD6DEE7213EEDC685F8FF23C6009DBAC882459F3684399B4269D4FD8", + "sourceFingerprint": "395A986979A14C11BCB10FC14BFEB496896FAD070892908170A75ED6F660B940", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-didalloc", "registered": true, "metadataMatched": true, @@ -8956,7 +8996,7 @@ "slot": 5, "parameter": null }, - "sourceFingerprint": "0D9A3FDC75ED4D0CACDD6EB87FD4B37CDDC76AE3A7FE6A092684BCC423EC65E6", + "sourceFingerprint": "E1C7995289D17394650CF05A60AFF69254C558CED37A4B40551AFF7254B41E30", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-free", "registered": true, "metadataMatched": true, @@ -8974,7 +9014,7 @@ "slot": 6, "parameter": null }, - "sourceFingerprint": "60D609C9AA79872157DA36E7E382AD705F616A2F8FA5F30703ED370BF225668C", + "sourceFingerprint": "87ED4B22DC04424CA8CAA93DE49034399E71D2238B0650048EB0849FBEBE23B8", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-getsize", "registered": true, "metadataMatched": true, @@ -8992,7 +9032,7 @@ "slot": 8, "parameter": null }, - "sourceFingerprint": "9E45919984C17476FC1E0B6203DAFC5CDE37B14901CFBBB7EC67B46DAEAFDBC0", + "sourceFingerprint": "14D3F94202737A2BC0DC15525A628D507EEBDE97ED85C3D03F746E131A6F5E1B", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-heapminimize", "registered": true, "metadataMatched": true, @@ -9010,7 +9050,7 @@ "slot": 4, "parameter": null }, - "sourceFingerprint": "5B38A32AADFCAE023617814069CB356DB3FD8FDA0397144711B3A3807A446016", + "sourceFingerprint": "A915CB91303E7DBD93152D531CA1E514EA47903D755FDFE9D391B9D0C5147821", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-realloc", "registered": true, "metadataMatched": true, @@ -9049,7 +9089,7 @@ "slot": 12, "parameter": null }, - "sourceFingerprint": "718E5AFEC6B381CDF9A3AEB64F7FE25127C2C71D12B3E006E9547E4073AC5F26", + "sourceFingerprint": "476DC766C1F33B1B7F54C76E908DEA8DE9CB2D3B9BE2FFE76B8D34A2498A0A9C", "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-istream-stat", "registered": true, "metadataMatched": true, @@ -9077,6 +9117,24 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.ownership.entry.windows-win32-system-ole.iolecache.0000011e00000000c000000000000046.setdata.slot-7.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.System.Ole", + "interface": "IOleCache", + "iid": "0000011e-0000-0000-c000-000000000046", + "method": "SetData", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "AACEA7AC7F8360EE26C559E2EC69F254DF944977174AB767769B40AF899D5573", + "citation": "https://learn.microsoft.com/windows/win32/api/oleidl/nf-oleidl-iolecache-setdata", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 2 + }, "com.ownership.entry.windows-win32-system-search.imetadata.780102b0c43b4876bc7b5e9ba5c88794.getdata.slot-3.param-0-ppszkey.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -9854,6 +9912,24 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.semantic-hresult.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getcanonicalformatetc.slot-6.v1": { + "familyId": "com.semantic-hresult.v1", + "contractKind": "semantic-hresult", + "selector": { + "namespace": "Windows.Win32.System.Com", + "interface": "IDataObject", + "iid": "0000010e-0000-0000-c000-000000000046", + "method": "GetCanonicalFormatEtc", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "CD6292C4AFD80B76A7C3BA8122D4D98DA02105748829B7F63543A045AE92DDEA", + "citation": "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-getcanonicalformatetc", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.semantic-hresult.entry.windows-win32-system-com.ipersistfile.0000010b00000000c000000000000046.getcurfile.slot-8.v1": { "familyId": "com.semantic-hresult.v1", "contractKind": "semantic-hresult", @@ -9925,7 +10001,7 @@ "slot": 3, "parameter": null }, - "sourceFingerprint": "AC437FAE3FE761589AEB3C27EDDBC3F5ECBAC3D34464872BA0064D5E668C17AA", + "sourceFingerprint": "635D64CF667EC5716BD113C798140DA01A17182B87BD964CF1DDC2418C7A4122", "citation": "https://learn.microsoft.com/windows/win32/api/directml/nf-directml-idmlobject-getprivatedata", "registered": true, "metadataMatched": true, @@ -9943,7 +10019,7 @@ "slot": 66, "parameter": null }, - "sourceFingerprint": "DA0CC272AF987868D2497EFFE79A96349D84D51D7E4C11E8567974815A6F0A28", + "sourceFingerprint": "F725DBA168899774D4D4E42041028F8F933A834C4F44235DD23B5F9EEF4FBE29", "citation": "https://learn.microsoft.com/windows/win32/api/d3d10/nf-d3d10-id3d10device-getprivatedata", "registered": true, "metadataMatched": true, @@ -9961,7 +10037,7 @@ "slot": 4, "parameter": null }, - "sourceFingerprint": "2E96AE1D44B409A41A9509E45B1DB3C6AA3A59E2AAA66ABE544021DFC363F8E0", + "sourceFingerprint": "2BF68FF1CFEE2BFB2255C78CFC2E74227E03C700566123EDA480A0DD7398E2F4", "citation": "https://learn.microsoft.com/windows/win32/api/d3d10/nf-d3d10-id3d10devicechild-getprivatedata", "registered": true, "metadataMatched": true, @@ -9979,7 +10055,7 @@ "slot": 34, "parameter": null }, - "sourceFingerprint": "8DA4BA24A6A660589252D8690C3D1C30B53A5070A6D987D917097BF4558EC213", + "sourceFingerprint": "3106265D0B36373DB200256806A73708755E6A7838AB1E572AA7698F2EE98F15", "citation": "https://learn.microsoft.com/windows/win32/api/d3d11/nf-d3d11-id3d11device-getprivatedata", "registered": true, "metadataMatched": true, @@ -9997,7 +10073,7 @@ "slot": 4, "parameter": null }, - "sourceFingerprint": "6FFBA22644296AB929DD001ECCC7AAD2B1EB1949BB0878BF0C2CDF7F063EAF53", + "sourceFingerprint": "75B1995A6A2E5E455E66836B32275D64603A694AE4BC6D7CBEA7949FBCF7C9FD", "citation": "https://learn.microsoft.com/windows/win32/api/d3d11/nf-d3d11-id3d11devicechild-getprivatedata", "registered": true, "metadataMatched": true, @@ -10015,7 +10091,7 @@ "slot": 3, "parameter": null }, - "sourceFingerprint": "D1901D622093A53FE505636B00289593DC41B95D73811CEFF4BB33E669501731", + "sourceFingerprint": "50437F3F872990B745233579660A36F6024535195C2382E3D228685DF38920BA", "citation": "https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12object-getprivatedata", "registered": true, "metadataMatched": true, @@ -10033,7 +10109,7 @@ "slot": 5, "parameter": null }, - "sourceFingerprint": "822F781335150C935D2F6B91F34727F8B9923E0EFCCE751563E0ECFDD49FD5A0", + "sourceFingerprint": "477DC2A7CFE0A0B8707FC20233F24582DA183BCAA6666972ECB8756EAB638AE4", "citation": "https://learn.microsoft.com/windows/win32/api/dxgi/nf-dxgi-idxgiobject-getprivatedata", "registered": true, "metadataMatched": true, @@ -10051,7 +10127,7 @@ "slot": 5, "parameter": null }, - "sourceFingerprint": "94F522A39E514578ED19BD294398A38591677F63BB11A3047C5545D3DE77AD1A", + "sourceFingerprint": "3A53EA122647781A17DBD92F9E2FEA185CB9D355008BB1D6271D7D447A800766", "citation": "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-icontextmenu-getcommandstring", "registered": true, "metadataMatched": true, @@ -10651,37 +10727,37 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6093, - "raw_manual_contract": 1446, - "raw_runtime_blocked": 390, + "raw_metadata_complete": 6103, + "raw_manual_contract": 1437, + "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1446, - "safe_incomplete_raw_runtime_blocked": 390 + "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_runtime_blocked": 389 }, "i686": { - "raw_metadata_complete": 6092, - "raw_manual_contract": 1423, - "raw_runtime_blocked": 414, + "raw_metadata_complete": 6102, + "raw_manual_contract": 1414, + "raw_runtime_blocked": 413, "safe_incomplete_raw_metadata_complete": 411, - "safe_incomplete_raw_manual_contract": 1423, - "safe_incomplete_raw_runtime_blocked": 414 + "safe_incomplete_raw_manual_contract": 1414, + "safe_incomplete_raw_runtime_blocked": 413 }, "x64": { - "raw_metadata_complete": 6093, - "raw_manual_contract": 1446, - "raw_runtime_blocked": 390, + "raw_metadata_complete": 6103, + "raw_manual_contract": 1437, + "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1446, - "safe_incomplete_raw_runtime_blocked": 390 + "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_runtime_blocked": 389 } }, "blocker_reason_counts": { "arm64": { - "incomplete_pointee_layout_for_storage": 339, + "incomplete_pointee_layout_for_storage": 338, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10690,11 +10766,11 @@ "unsupported_layout_kind": 4 }, "i686": { - "incomplete_pointee_layout_for_storage": 363, + "incomplete_pointee_layout_for_storage": 362, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10703,11 +10779,11 @@ "unsupported_layout_kind": 4 }, "x64": { - "incomplete_pointee_layout_for_storage": 339, + "incomplete_pointee_layout_for_storage": 338, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10718,52 +10794,52 @@ }, "manual_reason_counts": { "arm64": { - "external_pointee_storage": 986, + "external_pointee_storage": 976, "missing_allocator": 1044, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, "missing_output_ownership": 1044, - "nested_pointer_lifetime": 570, + "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, - "pointee_missing_layout": 412, + "pointee_missing_layout": 404, "pointee_recursive_layout": 25, "pointee_unsupported_bitfield": 16, - "pointee_unsupported_flexible_array": 111, + "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, "pointee_unsupported_packing": 110, "variant_safearray_element_contract": 2 }, "i686": { - "external_pointee_storage": 987, + "external_pointee_storage": 977, "missing_allocator": 1044, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, "missing_output_ownership": 1044, - "nested_pointer_lifetime": 544, + "nested_pointer_lifetime": 534, "opaque_pointee_contract": 289, - "pointee_missing_layout": 399, + "pointee_missing_layout": 391, "pointee_recursive_layout": 25, "pointee_unsupported_bitfield": 16, - "pointee_unsupported_flexible_array": 111, + "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, "pointee_unsupported_packing": 146, "variant_safearray_element_contract": 2 }, "x64": { - "external_pointee_storage": 986, + "external_pointee_storage": 976, "missing_allocator": 1044, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, "missing_output_ownership": 1044, - "nested_pointer_lifetime": 570, + "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, - "pointee_missing_layout": 412, + "pointee_missing_layout": 404, "pointee_recursive_layout": 25, "pointee_unsupported_bitfield": 16, - "pointee_unsupported_flexible_array": 111, + "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, "pointee_unsupported_packing": 110, "variant_safearray_element_contract": 2 @@ -10819,9 +10895,9 @@ }, { "category": "NativeStruct", - "direct_occurrences": 9126, - "expanded_occurrences": 20547, - "named_types": 1548 + "direct_occurrences": 9089, + "expanded_occurrences": 20502, + "named_types": 1546 }, { "category": "NativeUnion", diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 300118bd..6dac20cf 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -4076,8 +4076,8 @@ Windows.Win32.System.ClrHosting,IObjectHandle,c460e2b4-e199-412a-8456-84dc3e4838 Windows.Win32.System.ClrHosting,ITypeName,b81ff171-20f3-11d2-8dcc-00a0c9b00522,true,standard_derived, Windows.Win32.System.ClrHosting,ITypeNameBuilder,b81ff171-20f3-11d2-8dcc-00a0c9b00523,true,standard_derived, Windows.Win32.System.ClrHosting,ITypeNameFactory,b81ff171-20f3-11d2-8dcc-00a0c9b00521,true,standard_derived, -Windows.Win32.System.Com,AsyncIAdviseSink,00000150-0000-0000-c000-000000000046,false,,external_pointee_storage -Windows.Win32.System.Com,AsyncIAdviseSink2,00000151-0000-0000-c000-000000000046,false,,external_pointee_storage +Windows.Win32.System.Com,AsyncIAdviseSink,00000150-0000-0000-c000-000000000046,true,standard_derived, +Windows.Win32.System.Com,AsyncIAdviseSink2,00000151-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,AsyncIMultiQI,000e0020-0000-0000-c000-000000000046,false,,incomplete_pointee_layout_for_storage Windows.Win32.System.Com,AsyncIPipeByte,db2f3acb-2f86-11d1-8e04-00c04fb9989a,true,standard_derived, Windows.Win32.System.Com,AsyncIPipeDouble,db2f3acf-2f86-11d1-8e04-00c04fb9989a,true,standard_derived, @@ -4110,8 +4110,8 @@ Windows.Win32.System.Com.Events,IPublisherFilter,465e5cc0-7b26-11d1-88fb-0080c7d Windows.Win32.System.Com,IActivationFilter,00000017-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,IAddrExclusionControl,00000148-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,IAddrTrackingControl,00000147-0000-0000-c000-000000000046,true,standard_derived, -Windows.Win32.System.Com,IAdviseSink,0000010f-0000-0000-c000-000000000046,false,,external_pointee_storage -Windows.Win32.System.Com,IAdviseSink2,00000125-0000-0000-c000-000000000046,false,,external_pointee_storage +Windows.Win32.System.Com,IAdviseSink,0000010f-0000-0000-c000-000000000046,true,standard_derived, +Windows.Win32.System.Com,IAdviseSink2,00000125-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,IAgileObject,94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90,true,standard_derived, Windows.Win32.System.Com,IAsyncManager,0000002a-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,IAsyncRpcChannelBuffer,a5029fb6-3c34-11d1-9c99-00c04fb998aa,false,,missing_allocator @@ -4136,8 +4136,8 @@ Windows.Win32.System.Com,IConnectionPoint,b196b286-bab4-101a-b69c-00aa00341d07,t Windows.Win32.System.Com,IConnectionPointContainer,b196b284-bab4-101a-b69c-00aa00341d07,true,standard_derived, Windows.Win32.System.Com,IContext,000001c0-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Com,IContextCallback,000001da-0000-0000-c000-000000000046,false,,nested_pointer_lifetime -Windows.Win32.System.Com,IDataAdviseHolder,00000110-0000-0000-c000-000000000046,false,,external_pointee_storage -Windows.Win32.System.Com,IDataObject,0000010e-0000-0000-c000-000000000046,false,,incomplete_pointee_layout_for_storage +Windows.Win32.System.Com,IDataAdviseHolder,00000110-0000-0000-c000-000000000046,true,standard_derived, +Windows.Win32.System.Com,IDataObject,0000010e-0000-0000-c000-000000000046,true,exact_registry_dependent, Windows.Win32.System.Com,IDispatch,00020400-0000-0000-c000-000000000046,true,exact_registry_dependent, Windows.Win32.System.Com,IEnumCATEGORYINFO,0002e011-0000-0000-c000-000000000046,false,,safe_projection_incomplete Windows.Win32.System.Com,IEnumConnectionPoints,b196b285-bab4-101a-b69c-00aa00341d07,true,exact_registry_dependent, @@ -5075,7 +5075,7 @@ Windows.Win32.System.Mmc,Views,d6b8c29d-a1ff-4d72-aab0-e381e9b9338d,true,standar Windows.Win32.System.Mmc,_AppEvents,de46cbdd-53f5-4635-af54-4fe71e923d3f,true,standard_derived, Windows.Win32.System.Mmc,_Application,a3afb9cc-b653-4741-86ab-f0470ec1384c,true,standard_derived, Windows.Win32.System.Mmc,_EventConnector,c0bccd30-de44-4528-8403-a05a6a1cc8ea,true,standard_derived, -Windows.Win32.System.Ole,IAdviseSinkEx,3af24290-0c96-11ce-a0cf-00aa00600ab8,false,,external_pointee_storage +Windows.Win32.System.Ole,IAdviseSinkEx,3af24290-0c96-11ce-a0cf-00aa00600ab8,true,standard_derived, Windows.Win32.System.Ole,ICanHandleException,c5598e60-b307-11d1-b27d-006008c3fbfb,false,,safe_projection_incomplete Windows.Win32.System.Ole,IClassFactory2,b196b28f-bab4-101a-b69c-00aa00341d07,true,standard_derived, Windows.Win32.System.Ole,IContinue,0000012a-0000-0000-c000-000000000046,true,standard_derived, @@ -5103,8 +5103,8 @@ Windows.Win32.System.Ole,IGetVBAObject,91733a60-3f4c-101b-a3f6-00aa0034e4e9,fals Windows.Win32.System.Ole,IObjectIdentity,ca04b7e6-0d21-11d1-8cc5-00c04fc2b085,true,standard_derived, Windows.Win32.System.Ole,IObjectWithSite,fc4801a3-2ba9-11cf-a229-00aa003d7352,true,standard_derived, Windows.Win32.System.Ole,IOleAdviseHolder,00000111-0000-0000-c000-000000000046,true,standard_derived, -Windows.Win32.System.Ole,IOleCache,0000011e-0000-0000-c000-000000000046,false,,external_pointee_storage -Windows.Win32.System.Ole,IOleCache2,00000128-0000-0000-c000-000000000046,false,,external_pointee_storage +Windows.Win32.System.Ole,IOleCache,0000011e-0000-0000-c000-000000000046,true,exact_registry_dependent, +Windows.Win32.System.Ole,IOleCache2,00000128-0000-0000-c000-000000000046,true,exact_registry_dependent, Windows.Win32.System.Ole,IOleCacheControl,00000129-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Ole,IOleClientSite,00000118-0000-0000-c000-000000000046,true,standard_derived, Windows.Win32.System.Ole,IOleCommandTarget,b722bccb-4e68-101b-a2bc-00aa00404770,false,,incomplete_pointee_layout_for_storage @@ -6906,7 +6906,7 @@ Windows.Win32.UI.TextServices,ITfPersistentPropertyLoaderACP,4ef89150-0807-11d3- Windows.Win32.UI.TextServices,ITfPreservedKeyNotifySink,6f77c993-d2b1-446e-853e-5912efc8a286,true,standard_derived, Windows.Win32.UI.TextServices,ITfProperty,e2449660-9542-11d2-bf46-00105a2799b5,true,standard_derived, Windows.Win32.UI.TextServices,ITfPropertyStore,6834b120-88cb-11d2-bf45-00105a2799b5,true,standard_derived, -Windows.Win32.UI.TextServices,ITfQueryEmbedded,0fab9bdb-d250-4169-84e5-6be118fdd7a8,false,,external_pointee_storage +Windows.Win32.UI.TextServices,ITfQueryEmbedded,0fab9bdb-d250-4169-84e5-6be118fdd7a8,true,standard_derived, Windows.Win32.UI.TextServices,ITfRange,aa80e7ff-2021-11d2-93e0-0060b067b86e,false,,external_pointee_storage Windows.Win32.UI.TextServices,ITfRangeACP,057a6296-029b-4154-b79a-0d461d4ea94c,false,,external_pointee_storage Windows.Win32.UI.TextServices,ITfRangeBackup,463a506d-6992-49d2-9b88-93d55e70bb16,true,standard_derived, diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 30bad4d2..1a7fd2ae 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4559,10 +4559,10 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_681); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_681); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_326); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 355); + assert_eq!(report.summary.safe_complete, 5_691); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_691); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_333); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 358); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4570,34 +4570,34 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.metadata_fact_occurrences, - 5_974 + 5_976 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_076 + 26_114 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 495); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 499); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 495 + 499 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 404 + 408 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 655 + 660 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 404 + 408 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4610,15 +4610,15 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 2), - ("ownership".into(), 172), + ("ownership".into(), 176), ("parameter-direction".into(), 45), ("safearray".into(), 263), - ("semantic-hresult".into(), 2), + ("semantic-hresult".into(), 3), ]) ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 116 + 119 ); assert_eq!( report.summary.safe_evidence.by_family_id["windows.borrowed-hwnd-output.v1"], @@ -4632,7 +4632,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(), 404); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 408); assert!( report .summary @@ -4677,7 +4677,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 404 + 408 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( @@ -4744,6 +4744,34 @@ mod tests { promoted_audio.evidence_class, Some(SafeEvidenceClass::ExactRegistryDependent) )); + let data_object = report + .interfaces + .iter() + .find(|interface| { + interface.namespace == "Windows.Win32.System.Com" && interface.name == "IDataObject" + }) + .unwrap(); + assert!(data_object.safe_complete); + assert!(matches!( + data_object.evidence_class, + Some(SafeEvidenceClass::ExactRegistryDependent) + )); + assert!(data_object.exact_entry_ids.contains( + &"com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.setdata.slot-7.v1".into() + )); + assert!(data_object.exact_entry_ids.contains( + &"com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getdatahere.slot-4.v1".into() + )); + let wia = report + .interfaces + .iter() + .find(|interface| { + interface.namespace == "Windows.Win32.Devices.ImageAcquisition" + && interface.name == "IWiaDataTransfer" + }) + .unwrap(); + assert!(!wia.safe_complete); + assert!(wia.evidence_class.is_none()); assert_eq!( promoted_audio .exact_entry_ids @@ -4812,8 +4840,8 @@ mod tests { ), ( 412 - usize::from(target == CensusTarget::I686), - 1_446 - 23 * usize::from(target == CensusTarget::I686), - 390 + 24 * usize::from(target == CensusTarget::I686) + 1_437 - 23 * usize::from(target == CensusTarget::I686), + 389 + 24 * usize::from(target == CensusTarget::I686) ) ); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 593d2fb1..42d6124f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -2319,15 +2319,15 @@ mod tests { }; let coverage = measure_stage2_coverage(&winmd).unwrap(); println!("{}", serde_json::to_string(&coverage).unwrap()); - assert_eq!(coverage.x64_manual_interfaces, 1_446); - assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_442); + assert_eq!(coverage.x64_manual_interfaces, 1_437); + assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_433); assert_eq!( coverage.x64_manual_interfaces_with_executable_manual_method, - 1_441 + 1_432 ); - assert_eq!(coverage.executable_manual_methods, 6_083); + assert_eq!(coverage.executable_manual_methods, 6_067); assert_eq!(coverage.remaining_manual_methods, 0); - assert_eq!(coverage.runtime_blocked_methods, 1_163); + assert_eq!(coverage.runtime_blocked_methods, 1_161); } #[test] diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index fe4dffe4..91adc38a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -213,6 +213,8 @@ pub(super) enum ComType { DispatchParams, ExcepInfo, StatStg, + FormatEtc, + StgMedium, ManagedInterface { iid: String, }, @@ -310,6 +312,8 @@ pub(super) enum ResultConversion { PropVariant, ExcepInfo, StatStg, + FormatEtc, + StgMedium, MallocAllocation, MallocReallocation, } @@ -452,6 +456,16 @@ pub(super) enum ProjectedComMethodKind { synchronous_flags: i32, semisynchronous_flags: i32, }, + BorrowedStgMediumInput { + release_param_index: usize, + }, + PreservedStgMediumInOut { + medium_param_index: usize, + }, + CanonicalFormatEtc { + input_param_index: usize, + output_param_index: usize, + }, } /// The JS runtime `typeof`/shape category a validated value uses at a call @@ -568,7 +582,10 @@ pub(super) fn dispatch_shape(typ: &ComType) -> Option { | ComScalarRepr::NativeUsize => Some(DispatchShape::BigInt), ComScalarRepr::Primitive(_) => Some(DispatchShape::Number), }, - ComType::ManagedInterface { .. } | ComType::DispatchParams => Some(DispatchShape::Object), + ComType::ManagedInterface { .. } + | ComType::DispatchParams + | ComType::FormatEtc + | ComType::StgMedium => Some(DispatchShape::Object), // Raw/aliased pointers and BSTR accept multiple overlapping JS input // shapes (`bigint`, `number`, `Buffer`, `Uint8Array`, or `string`) // depending on position, so they can collide with any other category diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index d2dfd838..1995100b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -408,7 +408,10 @@ fn render_js(meta: &ProjectedComInterface) -> String { match method.kind { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } - | ProjectedComMethodKind::OwningCallerOutput { .. } => { + | ProjectedComMethodKind::OwningCallerOutput { .. } + | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::PreservedStgMediumInOut { .. } + | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { emit_method_js(&mut out, method, &iface_var) } ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -774,6 +777,15 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { ComReturnConvention::Void => parts.push(".returnsVoid()".into()), ComReturnConvention::Direct(typ) => parts.push(format!(".returns({})", abi_type_js(typ))), } + if let ProjectedComMethodKind::CanonicalFormatEtc { + input_param_index, + output_param_index, + } = method.kind + { + parts.push(format!( + ".canonicalFormatEtcResult({input_param_index}, {output_param_index})" + )); + } if parts.is_empty() { "new DynComMethodSig()".into() } else { @@ -887,6 +899,8 @@ fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComTyp | ResultConversion::PropVariant | ResultConversion::ExcepInfo | ResultConversion::StatStg + | ResultConversion::FormatEtc + | ResultConversion::StgMedium | ResultConversion::MallocAllocation | ResultConversion::MallocReallocation, ) @@ -1229,6 +1243,14 @@ fn emit_method_js_named( if matches!(param.typ, ComType::ExactNullPointer) { return Some("DynCom.exactNullPointer(null)".into()); } + if matches!( + method.kind, + ProjectedComMethodKind::BorrowedStgMediumInput { + release_param_index + } if release_param_index == index + ) { + return Some("DynCom.i32(0)".into()); + } for group in &method.shared_counts { match group { SharedCountPlan::StringInputScalarOutput { @@ -2408,7 +2430,10 @@ fn render_dts(meta: &ProjectedComInterface) -> String { let (params, ret) = match method.kind { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } - | ProjectedComMethodKind::OwningCallerOutput { .. } => { + | ProjectedComMethodKind::OwningCallerOutput { .. } + | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::PreservedStgMediumInOut { .. } + | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { (dts_params(method), dts_return_type(method)) } ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -2624,6 +2649,8 @@ fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, Pointer | ComType::DispatchParams | ComType::ExcepInfo | ComType::StatStg + | ComType::FormatEtc + | ComType::StgMedium | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } @@ -2724,6 +2751,8 @@ fn collect_native_pods(meta: &ProjectedComInterface) -> Vec {} @@ -2814,6 +2843,12 @@ fn collect_runtime_types(meta: &ProjectedComInterface) -> Vec<&'static str> { ComType::StatStg => { types.insert("DynComStatStg"); } + ComType::FormatEtc => { + types.insert("DynComFormatEtc"); + } + ComType::StgMedium => { + types.insert("DynComStgMedium"); + } ComType::AllocatorPointer | ComType::ConsumedAllocatorPointer | ComType::InspectedAllocatorPointer => { @@ -2892,6 +2927,8 @@ fn collect_scalar_alias( | ComType::DispatchParams | ComType::ExcepInfo | ComType::StatStg + | ComType::FormatEtc + | ComType::StgMedium | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} 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 9f455aba..52e82bea 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -200,6 +200,113 @@ fn renderer_serializes_validated_com_sink_plan() { ); } +#[test] +fn storage_medium_result_rules_and_borrowing_are_serialized_from_ir() { + let format_param = |name: &str, direction| ProjectedComParam { + name: name.into(), + typ: ComType::FormatEtc, + direction, + surface_input: direction == ComParamDirection::In, + surface_result: direction == ComParamDirection::Out, + nullable: false, + }; + let mut method = ProjectedComMethod { + name: "Normalize".into(), + camel_name: "normalize".into(), + vtable_index: 6, + params: vec![ + format_param("input", ComParamDirection::In), + format_param("output", ComParamDirection::Out), + ], + return_convention: ComReturnConvention::SemanticHResult, + results: vec![ + ProjectedComResult { + typ: ComType::HResult, + source: ResultSource::DirectReturn, + conversion: ResultConversion::Value, + }, + ProjectedComResult { + typ: ComType::FormatEtc, + source: ResultSource::Param(1), + conversion: ResultConversion::FormatEtc, + }, + ], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::CanonicalFormatEtc { + input_param_index: 0, + output_param_index: 1, + }, + doc: None, + overload: None, + }; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addIn(DynCom.formatEtcType()).addOut(DynCom.formatEtcType()).preserveHresult().canonicalFormatEtcResult(0, 1)" + ); + method.kind = ProjectedComMethodKind::Normal; + assert!(!super::build_method_sig_js(&method).contains("canonicalFormatEtcResult")); + + method.name = "Fill".into(); + method.camel_name = "fill".into(); + method.kind = ProjectedComMethodKind::PreservedStgMediumInOut { + medium_param_index: 1, + }; + method.params[1] = ProjectedComParam { + name: "medium".into(), + typ: ComType::StgMedium, + direction: ComParamDirection::InOut, + surface_input: true, + surface_result: true, + nullable: false, + }; + method.return_convention = ComReturnConvention::HResult; + method.results = vec![ProjectedComResult { + typ: ComType::StgMedium, + source: ResultSource::Param(1), + conversion: ResultConversion::StgMedium, + }]; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addIn(DynCom.formatEtcType()).addInOut(DynCom.stgMediumType())" + ); + let mut js = String::new(); + emit_method_js(&mut js, &method, "_iface"); + assert!(js.contains("fill(input, medium)")); + assert!(js.contains("return DynCom.takeStgMedium(_out);"), "{js}"); + assert_eq!(dts_return_type(&method), "DynComStgMedium"); + + method.name = "Store".into(); + method.camel_name = "store".into(); + method.kind = ProjectedComMethodKind::BorrowedStgMediumInput { + release_param_index: 2, + }; + method.params[1] = ProjectedComParam { + name: "medium".into(), + typ: ComType::StgMedium, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }; + method.params.push(ProjectedComParam { + name: "transfer".into(), + typ: ComType::Win32Bool, + direction: ComParamDirection::In, + surface_input: false, + surface_result: false, + nullable: false, + }); + method.return_convention = ComReturnConvention::HResult; + method.results.clear(); + let mut js = String::new(); + emit_method_js(&mut js, &method, "_iface"); + assert!(js.contains("store(input, medium)")); + assert!(js.contains("DynCom.stgMedium(medium), DynCom.i32(0)")); + assert!(!dts_params(&method).join(", ").contains("transfer")); +} + #[test] fn renderer_serializes_direct_and_void_com_sink_returns() { let methods = vec![ diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs index 67a1f754..b5f2d095 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -60,6 +60,8 @@ pub(super) fn abi_type_js(typ: &ComType) -> String { ComType::DispatchParams => "DynCom.dispatchParamsType()".into(), ComType::ExcepInfo => "DynCom.excepInfoType()".into(), ComType::StatStg => "DynCom.statStgType()".into(), + ComType::FormatEtc => "DynCom.formatEtcType()".into(), + ComType::StgMedium => "DynCom.stgMediumType()".into(), ComType::ManagedInterface { iid } => { format!("DynCom.interfaceType(WinGuid.parse('{iid}'))") } @@ -158,6 +160,8 @@ pub(super) fn type_dts(typ: &ComType) -> String { ComType::DispatchParams => "DynComDispatchParams".into(), ComType::ExcepInfo => "DynComExcepInfo".into(), ComType::StatStg => "DynComStatStg".into(), + ComType::FormatEtc => "DynComFormatEtc".into(), + ComType::StgMedium => "DynComStgMedium".into(), ComType::ManagedInterface { .. } => "DynWinRtValue".into(), ComType::CoTaskMemWideString => "string".into(), ComType::StringArray { .. } => "string[]".into(), @@ -208,6 +212,8 @@ pub(super) fn result_type_dts(result: &ProjectedComResult) -> String { ResultConversion::PropVariant => "DynComPropVariant".into(), ResultConversion::ExcepInfo => "DynComExcepInfo".into(), ResultConversion::StatStg => "DynComStatStg".into(), + ResultConversion::FormatEtc => "DynComFormatEtc".into(), + ResultConversion::StgMedium => "DynComStgMedium".into(), ResultConversion::MallocAllocation | ResultConversion::MallocReallocation => { "DynComAllocation | null".into() } @@ -289,6 +295,8 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { ComType::DispatchParams => format!("DynCom.dispatchParams({variable})"), ComType::ExcepInfo => unreachable!("EXCEPINFO is output-only"), ComType::StatStg => unreachable!("STATSTG is output-only"), + ComType::FormatEtc => format!("DynCom.formatEtc({variable})"), + ComType::StgMedium => format!("DynCom.stgMedium({variable})"), ComType::ManagedInterface { .. } => variable.to_string(), ComType::CoTaskMemWideString => { unreachable!("CoTaskMem string elements are output-only") @@ -374,6 +382,8 @@ pub(super) fn unwrap_result_js(result: &ProjectedComResult, expression: &str) -> ResultConversion::PropVariant => format!("DynCom.takePropVariant({expression})"), ResultConversion::ExcepInfo => format!("DynCom.takeExcepInfo({expression})"), ResultConversion::StatStg => format!("DynCom.takeStatStg({expression})"), + ResultConversion::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), + ResultConversion::StgMedium => format!("DynCom.takeStgMedium({expression})"), ResultConversion::MallocAllocation => { format!("DynCom.takeMallocAllocation(this._obj, {expression})") } @@ -467,6 +477,8 @@ fn unwrap_value_js(typ: &ComType, expression: &str) -> String { ComType::DispatchParams => unreachable!("DISPPARAMS is input-only"), ComType::ExcepInfo => format!("DynCom.takeExcepInfo({expression})"), ComType::StatStg => format!("DynCom.takeStatStg({expression})"), + ComType::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), + ComType::StgMedium => format!("DynCom.takeStgMedium({expression})"), ComType::ManagedInterface { .. } => expression.to_string(), ComType::CoTaskMemWideString => { unreachable!("CoTaskMem string elements are array-only") diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs index 962cb0ce..1f25b57e 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs @@ -165,6 +165,8 @@ pub(in crate::codegen::com) enum ComAbiType { DispatchParams, ExcepInfo, StatStg, + FormatEtc, + StgMedium, FunctionPointer(SignatureId), Unknown(UnsupportedReason), } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index c66813c9..3e1f1157 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -294,6 +294,8 @@ fn map_method( .map_err(ModelError::InvalidContract)?; crate::com_metadata::validate_attached_safe_array_evidence(raw) .map_err(ModelError::InvalidContract)?; + crate::com_metadata::validate_storage_medium_contract_presence(raw) + .map_err(ModelError::InvalidContract)?; if let Some(contract) = &raw.exact_contract { crate::com_metadata::validate_exact_method_contract( interface_namespace, @@ -429,6 +431,28 @@ fn map_method( validation_flag: 6, }) } + Some(RawExactMethodContractKind::BorrowedStgMediumInput) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::BorrowedStgMediumInput { + release_param: ParamIndex::new( + contract + .ownership_transfer_param_index + .expect("validated SetData ownership-transfer parameter"), + ), + }) + } + Some(RawExactMethodContractKind::PreservedStgMediumInOut) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::PreservedStgMediumInOut { + medium_param: ParamIndex::new(contract.buffer_param_index), + }) + } + Some(RawExactMethodContractKind::CanonicalFormatEtc) => { + method.with_special_contract(ComMethodSpecialContract::CanonicalFormatEtc { + input_param: ParamIndex::new(0), + output_param: ParamIndex::new(1), + }) + } None => method, } }; @@ -501,6 +525,44 @@ fn map_param( )?, None, ) + } else if matches!( + &raw.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Com" + && name == "FORMATETC" + && raw.typ.pointer_depth == 1 + ) { + ( + insert_abi( + model, + Some(QualifiedName::new("Windows.Win32.System.Com", "FORMATETC")?), + None, + ComAbiType::FormatEtc, + )?, + None, + ) + } else if matches!( + &raw.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Com" + && name == "STGMEDIUM" + && raw.typ.pointer_depth == 1 + ) { + ( + insert_abi( + model, + Some(QualifiedName::new("Windows.Win32.System.Com", "STGMEDIUM")?), + None, + ComAbiType::StgMedium, + )?, + None, + ) } else if raw_method.exact_contract.as_ref().is_some_and(|contract| { contract.kind == RawExactMethodContractKind::StatStg && contract.buffer_param_index == param_index @@ -967,6 +1029,8 @@ pub(in crate::codegen::com) fn census_raw_base_category(raw: &RawComType) -> &'s ComAbiType::DispatchParams => "DispatchParams", ComAbiType::ExcepInfo => "ExcepInfo", ComAbiType::StatStg => "StatStg", + ComAbiType::FormatEtc => "FormatEtc", + ComAbiType::StgMedium => "StgMedium", ComAbiType::FunctionPointer(_) => "FunctionPointer", ComAbiType::Unknown(_) => "Unknown", }; @@ -1165,6 +1229,12 @@ fn map_raw_named_struct( if namespace == "Windows.Win32.System.Com" && name == "EXCEPINFO" { return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::ExcepInfo); } + if namespace == "Windows.Win32.System.Com" && name == "FORMATETC" { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::FormatEtc); + } + if namespace == "Windows.Win32.System.Com" && name == "STGMEDIUM" { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::StgMedium); + } if namespace == "Windows.Win32.System.Com.StructuredStorage" && name == "PROPVARIANT" { return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::PropVariant); } @@ -1462,6 +1532,8 @@ fn validate_pod_field_type( | ComAbiType::DispatchParams | ComAbiType::ExcepInfo | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)), } @@ -1531,6 +1603,8 @@ fn abi_size_alignment( | ComAbiType::DispatchParams | ComAbiType::ExcepInfo | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium | ComAbiType::Unknown(_) => { return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); } @@ -1748,6 +1822,8 @@ fn buffer_element_ownership( | ComAbiType::DispatchParams | ComAbiType::ExcepInfo | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => BufferElementOwnership::Unknown, }; @@ -1884,6 +1960,20 @@ fn map_ownership( ComAbiType::StatStg if direction == Direction::Out => { Ok((ComOwnership::StatStgOwned, Cleanup::StatStgClear)) } + ComAbiType::FormatEtc if direction == Direction::Out => { + Ok((ComOwnership::FormatEtcOwned, Cleanup::FormatEtcClear)) + } + ComAbiType::StgMedium if direction == Direction::Out => { + Ok((ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium)) + } + ComAbiType::FormatEtc if direction == Direction::InOut => Err( + ModelError::Unsupported(UnsupportedReason::Other( + "FORMATETC in/out requires a dedicated replacement contract".into(), + )), + ), + ComAbiType::FormatEtc | ComAbiType::StgMedium => { + Ok((ComOwnership::Borrowed, Cleanup::None)) + } ComAbiType::DispatchParams if direction == Direction::Out => Err( ModelError::Unsupported(UnsupportedReason::Other( "DISPPARAMS is input-only".into(), diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index 3551224a..13477a8d 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -53,6 +53,16 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { synchronous_flags: i32, semisynchronous_flags: i32, }, + BorrowedStgMediumInput { + release_param: ParamIndex, + }, + PreservedStgMediumInOut { + medium_param: ParamIndex, + }, + CanonicalFormatEtc { + input_param: ParamIndex, + output_param: ParamIndex, + }, Malloc, } @@ -141,10 +151,24 @@ impl ComMethodContract { } pub(super) fn validate(&self, model: &ComModel) -> Result<(), ModelError> { - for param in &self.params { + for (index, param) in self.params.iter().enumerate() { (|| { model.require_supported_type(param.abi_type())?; let abi = model.types().get(param.abi_type())?.abi(); + if matches!(abi, ComAbiType::StgMedium) + && param.direction() == super::contract::Direction::InOut + && (self.special_contract + != Some(ComMethodSpecialContract::PreservedStgMediumInOut { + medium_param: ParamIndex::new(index), + }) + || param.ownership() != &ComOwnership::Borrowed + || param.cleanup() != &Cleanup::None) + { + return Err(ModelError::InvalidContract( + "STGMEDIUM in/out requires exact contract evidence for caller-allocated preservation" + .into(), + )); + } let is_counted_buffer = matches!(abi, ComAbiType::CountedBuffer { .. }); if is_counted_buffer != param.count().is_some() { return Err(ModelError::InvalidContract( @@ -165,6 +189,8 @@ impl ComMethodContract { .. } | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium ) { return Err(ModelError::InvalidContract(format!( @@ -1006,6 +1032,51 @@ mod tests { .unwrap() } + #[test] + fn storage_medium_in_out_requires_a_borrowed_preservation_plan() { + let mut model = ComModel::default(); + let medium = model + .types_mut() + .insert(ComTypeDefinition::new(None, None, ComAbiType::StgMedium)) + .unwrap(); + let method = ComMethodContract::new( + "FillMedium", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![param("medium", medium, Direction::InOut, None)], + ComReturnKind::HResult, + ) + .unwrap(); + assert!(method.validate(&model).is_err()); + assert!( + method + .clone() + .with_special_contract(ComMethodSpecialContract::PreservedStgMediumInOut { + medium_param: ParamIndex::new(1), + }) + .validate(&model) + .is_err() + ); + let mut preserved = + method.with_special_contract(ComMethodSpecialContract::PreservedStgMediumInOut { + medium_param: ParamIndex::new(0), + }); + preserved.validate(&model).unwrap(); + preserved.params[0] = ComParamContract::new( + "medium", + medium, + Direction::InOut, + false, + Nullability::Required, + None, + ComOwnership::StgMediumOwned, + Cleanup::ReleaseStgMedium, + ) + .unwrap(); + assert!(preserved.validate(&model).is_err()); + } + #[test] fn method_contract_validates_count_directions_and_types() { let mut model = ComModel::default(); diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs index e02ffdb5..8cf5b0f6 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs @@ -33,6 +33,8 @@ pub(in crate::codegen::com) enum ComOwnership { PropVariantOwned, ExcepInfoOwned, StatStgOwned, + FormatEtcOwned, + StgMediumOwned, LocalOwned, HandleOwned(HandleCleanup), CustomOwned(CleanupId), @@ -51,6 +53,8 @@ pub(in crate::codegen::com) enum Cleanup { PropVariantClear, ExcepInfoClear, StatStgClear, + FormatEtcClear, + ReleaseStgMedium, LocalFree, Handle(HandleCleanup), Custom(CleanupId), @@ -111,6 +115,8 @@ pub(super) fn validate_ownership_cleanup( | (ComOwnership::PropVariantOwned, Cleanup::PropVariantClear) | (ComOwnership::ExcepInfoOwned, Cleanup::ExcepInfoClear) | (ComOwnership::StatStgOwned, Cleanup::StatStgClear) + | (ComOwnership::FormatEtcOwned, Cleanup::FormatEtcClear) + | (ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium) | (ComOwnership::LocalOwned, Cleanup::LocalFree) => true, (ComOwnership::HandleOwned(expected), Cleanup::Handle(actual)) => expected == actual, (ComOwnership::CustomOwned(expected), Cleanup::Custom(actual)) => expected == actual, diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 993227ed..2a69113f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -507,6 +507,8 @@ fn validate_projected_surface_names(meta: &ProjectedComInterface) -> Result<(), | ComType::DispatchParams | ComType::ExcepInfo | ComType::StatStg + | ComType::FormatEtc + | ComType::StgMedium | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} @@ -688,6 +690,23 @@ fn project_method( synchronous_flags, semisynchronous_flags, }, + Some(ComMethodSpecialContract::BorrowedStgMediumInput { release_param }) => { + ProjectedComMethodKind::BorrowedStgMediumInput { + release_param_index: release_param.index(), + } + } + Some(ComMethodSpecialContract::PreservedStgMediumInOut { medium_param }) => { + ProjectedComMethodKind::PreservedStgMediumInOut { + medium_param_index: medium_param.index(), + } + } + Some(ComMethodSpecialContract::CanonicalFormatEtc { + input_param, + output_param, + }) => ProjectedComMethodKind::CanonicalFormatEtc { + input_param_index: input_param.index(), + output_param_index: output_param.index(), + }, Some(ComMethodSpecialContract::Malloc) | None => project_dynamic_method_kind( method.name(), dynamic_iid.map(|contract| { @@ -983,7 +1002,24 @@ fn project_method( ) { surface_input = false; } - if direction == ComParamDirection::InOut && !is_scalar_in_out(&typ) { + if matches!( + &kind, + ProjectedComMethodKind::BorrowedStgMediumInput { + release_param_index + } if *release_param_index == index + ) { + surface_input = false; + } + if direction == ComParamDirection::InOut + && !is_scalar_in_out(&typ) + && !matches!( + (&typ, &kind), + ( + ComType::StgMedium, + ProjectedComMethodKind::PreservedStgMediumInOut { medium_param_index } + ) if *medium_param_index == index + ) + { return Err(format!( "{}: unsupported [in, out] parameter `{}`", context(), @@ -1259,6 +1295,32 @@ fn project_method( } } + if let ProjectedComMethodKind::CanonicalFormatEtc { + input_param_index, + output_param_index, + } = kind + { + if input_param_index != 0 + || output_param_index != 1 + || params.len() != 2 + || return_convention != ComReturnConvention::SemanticHResult + || params[0].typ != ComType::FormatEtc + || params[0].direction != ComParamDirection::In + || params[0].nullable + || params[1].typ != ComType::FormatEtc + || params[1].direction != ComParamDirection::Out + || results.len() != 2 + || results[0].source != ResultSource::DirectReturn + || results[1].source != ResultSource::Param(1) + || results[1].conversion != ResultConversion::FormatEtc + { + return Err(format!( + "{}: canonical FORMATETC requires the exact semantic HRESULT and input/output result plan", + context() + )); + } + } + Ok(ProjectedComMethod { name: method.name().into(), camel_name: camel_case(method.name()), @@ -1642,6 +1704,8 @@ fn project_value_type( ComAbiType::DispatchParams => Ok(ComType::DispatchParams), ComAbiType::ExcepInfo => Ok(ComType::ExcepInfo), ComAbiType::StatStg => Ok(ComType::StatStg), + ComAbiType::FormatEtc => Ok(ComType::FormatEtc), + ComAbiType::StgMedium => Ok(ComType::StgMedium), ComAbiType::NativeUnion(_) | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => { Err(format!( "unsupported Classic-COM semantic type {}", @@ -2042,6 +2106,8 @@ fn project_native_pod_field_type( | ComAbiType::DispatchParams | ComAbiType::ExcepInfo | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(format!( "unsupported nested native POD field {}", @@ -2817,6 +2883,16 @@ fn result_conversion( (ComOwnership::StatStgOwned, Cleanup::StatStgClear) if matches!(typ, ComType::StatStg) => { Ok(ResultConversion::StatStg) } + (ComOwnership::FormatEtcOwned, Cleanup::FormatEtcClear) + if matches!(typ, ComType::FormatEtc) => + { + Ok(ResultConversion::FormatEtc) + } + (ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium) + if matches!(typ, ComType::StgMedium) => + { + Ok(ResultConversion::StgMedium) + } (ownership, cleanup) => Err(format!( "{}: unsupported projected ownership {ownership:?} with cleanup {cleanup:?}", param.name() diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 36701da9..8a4f73e1 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -381,6 +381,9 @@ pub enum RawExactMethodContractKind { StatStg, Malloc, FlagSelectedString, + BorrowedStgMediumInput, + PreservedStgMediumInOut, + CanonicalFormatEtc, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -396,6 +399,8 @@ pub struct RawExactMethodContract { pub actual_length_param_index: Option, pub discriminator_param_index: Option, pub reserved_null_param_index: Option, + pub ownership_transfer_param_index: Option, + pub source_fingerprint: Option<&'static str>, pub citation: &'static str, pub reason: &'static str, } @@ -409,9 +414,15 @@ impl RawExactMethodContract { RawExactMethodContractKind::UnsafePrivateData => { crate::contract_registry::ExactFamilyId::PrivateDataHazard } - RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc => { + RawExactMethodContractKind::StatStg + | RawExactMethodContractKind::Malloc + | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ExactFamilyId::Ownership } + RawExactMethodContractKind::CanonicalFormatEtc => { + crate::contract_registry::ExactFamilyId::SemanticHresult + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ExactFamilyId::ShellCommandString } @@ -437,9 +448,15 @@ impl RawExactMethodContract { RawExactMethodContractKind::UnsafePrivateData => { crate::contract_registry::ContractKind::Hazard } - RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc => { + RawExactMethodContractKind::StatStg + | RawExactMethodContractKind::Malloc + | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ContractKind::Ownership } + RawExactMethodContractKind::CanonicalFormatEtc => { + crate::contract_registry::ContractKind::SemanticHresult + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ContractKind::FlagSelectedBuffer } @@ -1308,7 +1325,10 @@ pub(crate) fn collect_exact_registry_entries( family_id: contract.family_id(), contract_kind: contract.contract_kind(), selector: method_selector(), - source_fingerprint: method_fingerprint.clone(), + source_fingerprint: contract + .source_fingerprint + .unwrap_or(&method_fingerprint) + .into(), reason: contract.reason.into(), citation: contract.citation.into(), }); @@ -2170,6 +2190,9 @@ fn apply_exact_method_contract( } RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} + RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc => {} RawExactMethodContractKind::FlagSelectedString => { let buffer = contract.buffer_param_index; let capacity = contract.capacity_param_index; @@ -2315,6 +2338,38 @@ fn registered_exact_method_contract( "IMalloc::HeapMinimize has no parameters and no return value", "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-heapminimize", ), + ("Windows.Win32.System.Com", "IDataObject", "GetDataHere") => ( + RawExactMethodContractKind::PreservedStgMediumInOut, + 1, + 0, + None, + "IDataObject::GetDataHere fills caller-allocated storage without resizing or replacing the HGLOBAL and must leave pUnkForRelease null; the caller retains cleanup responsibility", + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-getdatahere", + ), + ("Windows.Win32.System.Com", "IDataObject", "SetData") => ( + RawExactMethodContractKind::BorrowedStgMediumInput, + 1, + 0, + None, + "IDataObject::SetData transfers STGMEDIUM ownership only when fRelease is TRUE; the safe projection pins fRelease to FALSE so call-local HGLOBAL storage remains caller-owned", + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-setdata", + ), + ("Windows.Win32.System.Ole", "IOleCache", "SetData") => ( + RawExactMethodContractKind::BorrowedStgMediumInput, + 1, + 0, + None, + "IOleCache::SetData transfers STGMEDIUM ownership when fRelease is TRUE; the safe projection fixes FALSE so the cache borrows call-local storage", + "https://learn.microsoft.com/windows/win32/api/oleidl/nf-oleidl-iolecache-setdata", + ), + ("Windows.Win32.System.Com", "IDataObject", "GetCanonicalFormatEtc") => ( + RawExactMethodContractKind::CanonicalFormatEtc, + 1, + 0, + None, + "IDataObject::GetCanonicalFormatEtc ignores tymed on S_OK and returns the input format on DATA_S_SAMEFORMATETC without decoding the unused output", + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-getcanonicalformatetc", + ), ("Windows.Win32.Graphics.Dxgi", "IDXGIObject", "GetPrivateData") => ( RawExactMethodContractKind::UnsafePrivateData, 2, @@ -2382,7 +2437,8 @@ fn registered_exact_method_contract( "ID3D11DeviceChild" | "ID3D11Device" => "Windows.Win32.Graphics.Direct3D11", "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", - "IStream" => "Windows.Win32.System.Com", + "IStream" | "IDataObject" => "Windows.Win32.System.Com", + "IOleCache" => "Windows.Win32.System.Ole", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", "IContextMenu" => "Windows.Win32.UI.Shell", "IMalloc" => "Windows.Win32.System.Com", @@ -2401,6 +2457,8 @@ fn registered_exact_method_contract( "IStorage" => "IStorage", "IContextMenu" => "IContextMenu", "IMalloc" => "IMalloc", + "IDataObject" => "IDataObject", + "IOleCache" => "IOleCache", _ => unreachable!("matched exact method interface"), }, declaring_iid: match kind { @@ -2426,6 +2484,15 @@ fn registered_exact_method_contract( RawExactMethodContractKind::FlagSelectedString => { "000214e4-0000-0000-c000-000000000046" } + RawExactMethodContractKind::BorrowedStgMediumInput => match interface { + "IDataObject" => "0000010e-0000-0000-c000-000000000046", + "IOleCache" => "0000011e-0000-0000-c000-000000000046", + _ => unreachable!("matched exact borrowed STGMEDIUM input"), + }, + RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc => { + "0000010e-0000-0000-c000-000000000046" + } }, method_name: match kind { RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", @@ -2441,6 +2508,9 @@ fn registered_exact_method_contract( _ => unreachable!("matched exact IMalloc method"), }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", + RawExactMethodContractKind::BorrowedStgMediumInput => "SetData", + RawExactMethodContractKind::PreservedStgMediumInOut => "GetDataHere", + RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", }, vtable_index: match (interface, method) { ("IMFAttributes", "GetBlob") => 15, @@ -2459,6 +2529,9 @@ fn registered_exact_method_contract( ("IMalloc", "GetSize") => 6, ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, + ("IDataObject" | "IOleCache", "SetData") => 7, + ("IDataObject", "GetDataHere") => 4, + ("IDataObject", "GetCanonicalFormatEtc") => 6, _ => unreachable!("matched exact method identity"), }, buffer_param_index: buffer, @@ -2468,6 +2541,24 @@ fn registered_exact_method_contract( .then_some(1), reserved_null_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) .then_some(2), + ownership_transfer_param_index: (kind + == RawExactMethodContractKind::BorrowedStgMediumInput) + .then_some(2), + source_fingerprint: match (interface, method) { + ("IDataObject", "GetDataHere") => { + Some("65165D814B216835E273E9342B4CBEC2A4F6F1A68477F3F07036C2479BDADBFF") + } + ("IDataObject", "SetData") => { + Some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1") + } + ("IOleCache", "SetData") => { + Some("AACEA7AC7F8360EE26C559E2EC69F254DF944977174AB767769B40AF899D5573") + } + ("IDataObject", "GetCanonicalFormatEtc") => { + Some("CD6292C4AFD80B76A7C3BA8122D4D98DA02105748829B7F63543A045AE92DDEA") + } + _ => None, + }, citation, reason, }) @@ -2585,6 +2676,29 @@ fn raw_hresult(typ: &RawComType) -> bool { .is_some_and(|underlying| matches!(underlying.native_type, RawNativeType::I32)) } +pub(crate) fn validate_storage_medium_contract_presence(raw: &RawComMethod) -> Result<(), String> { + let required = registered_exact_method_contract( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.metadata_name, + ) + .is_some_and(|contract| { + matches!( + contract.kind, + RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc + ) + }); + if required && raw.exact_contract.is_none() { + return Err(format!( + "{}.{} requires its exact storage-medium contract", + raw.declaring_interface, raw.metadata_name + )); + } + Ok(()) +} + pub(crate) fn validate_exact_method_contract( current_namespace: &str, current_interface: &str, @@ -2603,6 +2717,20 @@ pub(crate) fn validate_exact_method_contract( if &expected != contract { return Err("exact method contract evidence does not match the registry".into()); } + if let Some(expected_fingerprint) = contract.source_fingerprint { + let mut source = raw.clone(); + source.exact_contract = None; + let actual_fingerprint = raw_method_fingerprint(&source); + if actual_fingerprint != expected_fingerprint { + return Err(format!( + "{}.{} source fingerprint changed: expected {}, found {}", + contract.declaring_interface, + contract.method_name, + expected_fingerprint, + actual_fingerprint + )); + } + } if raw.declaring_namespace != contract.declaring_namespace || raw.declaring_interface != contract.declaring_interface || !raw @@ -2739,6 +2867,64 @@ pub(crate) fn validate_exact_method_contract( && raw_u32_scalar(&raw.params[capacity], RawParamDirection::In, false) && raw_hresult(&raw.return_type) } + RawExactMethodContractKind::BorrowedStgMediumInput => { + raw.params.len() == 3 + && raw.params[0].name == "pformatetc" + && raw.params[0].direction == RawParamDirection::In + && !raw.params[0].optional + && raw.params[0].typ.pointer_depth == 1 + && matches!( + &raw.params[0].typ.native_type, + RawNativeType::Named { + namespace, + name, + kind: RawNamedKind::Struct, + .. + } if namespace == "Windows.Win32.System.Com" && name == "FORMATETC" + ) + && raw.params[1].name == "pmedium" + && raw.params[1].direction == RawParamDirection::In + && !raw.params[1].optional + && raw.params[1].typ.pointer_depth == 1 + && matches!( + &raw.params[1].typ.native_type, + RawNativeType::Named { + namespace, + name, + kind: RawNamedKind::Struct, + .. + } if namespace == "Windows.Win32.System.Com" && name == "STGMEDIUM" + ) + && raw.params[2].name == "fRelease" + && raw.params[2].direction == RawParamDirection::In + && !raw.params[2].optional + && raw.params[2].typ.pointer_depth == 0 + && matches!( + &raw.params[2].typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Foundation" && name == "BOOL" + ) + && raw.params[2] + .typ + .underlying + .as_deref() + .is_some_and(|underlying| { + underlying.pointer_depth == 0 + && matches!(underlying.native_type, RawNativeType::I32) + }) + && raw_hresult(&raw.return_type) + } + RawExactMethodContractKind::PreservedStgMediumInOut => { + raw_method_shape(raw) + == "GetDataHere@4(pformatetc:in:required:noconstattr:Windows.Win32.System.Com.FORMATETC[Struct]/ptr1/Mutable,pmedium:inout:required:noconstattr:Windows.Win32.System.Com.STGMEDIUM[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } + RawExactMethodContractKind::CanonicalFormatEtc => { + raw_method_shape(raw) + == "GetCanonicalFormatEtc@6(pformatectIn:in:required:noconstattr:Windows.Win32.System.Com.FORMATETC[Struct]/ptr1/Mutable,pformatetcOut:out:required:noconstattr:Windows.Win32.System.Com.FORMATETC[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:semantic_hresult:not_enumerator_next" + } }; let indices_valid = match contract.kind { RawExactMethodContractKind::FixedCapacityBytes @@ -2761,9 +2947,25 @@ pub(crate) fn validate_exact_method_contract( .is_some_and(|index| index < raw.params.len()) } RawExactMethodContractKind::Malloc => true, + RawExactMethodContractKind::BorrowedStgMediumInput => { + contract.buffer_param_index == 1 + && contract.ownership_transfer_param_index == Some(2) + && contract.actual_length_param_index.is_none() + && contract.discriminator_param_index.is_none() + && contract.reserved_null_param_index.is_none() + } + RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc => { + contract.buffer_param_index == 1 + && contract.ownership_transfer_param_index.is_none() + && contract.actual_length_param_index.is_none() + && contract.discriminator_param_index.is_none() + && contract.reserved_null_param_index.is_none() + } }; if !valid_shape - || raw.semantic_hresult.is_some() + || (raw.semantic_hresult.is_some() + && contract.kind != RawExactMethodContractKind::CanonicalFormatEtc) || raw.enumerator_next.is_some() || !indices_valid { @@ -4543,6 +4745,8 @@ mod tests { actual_length_param_index: None, discriminator_param_index: None, reserved_null_param_index: None, + ownership_transfer_param_index: None, + source_fingerprint: None, citation: "test://drift", reason: "drift", }) @@ -4864,6 +5068,113 @@ mod tests { ); } + #[test] + fn data_object_set_data_exact_contract_is_fingerprint_pinned() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let interface = + parse_com_interface(&winmd, "Windows.Win32.System.Com", "IDataObject").unwrap(); + let raw = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "SetData") + .unwrap(); + let contract = raw.exact_contract.as_ref().unwrap(); + let mut source = raw.clone(); + source.exact_contract = None; + assert_eq!( + raw_method_fingerprint(&source), + contract.source_fingerprint.unwrap() + ); + validate_exact_method_contract( + "Windows.Win32.System.Com", + "IDataObject", + "0000010e-0000-0000-c000-000000000046", + raw, + contract, + ) + .unwrap(); + } + + #[test] + fn storage_medium_contracts_pin_borrowing_and_canonical_results() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let mut errors = Vec::new(); + for (namespace, name, method_name) in [ + ("Windows.Win32.System.Com", "IDataObject", "GetDataHere"), + ("Windows.Win32.System.Ole", "IOleCache", "SetData"), + ("Windows.Win32.System.Ole", "IOleCache2", "SetData"), + ( + "Windows.Win32.System.Com", + "IDataObject", + "GetCanonicalFormatEtc", + ), + ] { + let interface = parse_com_interface(&winmd, namespace, name).unwrap(); + let method = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == method_name) + .unwrap(); + let contract = method.exact_contract.as_ref().unwrap_or_else(|| { + panic!( + "{name}.{method_name} is missing its exact storage-medium contract: {} ({})", + raw_method_shape(method), + raw_method_fingerprint(method), + ) + }); + if let Err(error) = validate_exact_method_contract( + namespace, + name, + &interface.interface.iid, + method, + contract, + ) { + errors.push(format!("{error}: {}", raw_method_shape(method))); + } + for mutation in 0..9 { + let mut drift = method.clone(); + match mutation { + 0 => drift.declaring_iid = "00000000-0000-0000-0000-000000000001".into(), + 1 => drift.vtable_index += 1, + 2 => drift.params[0].typ.pointer_depth += 1, + 3 => drift.params[0].direction = RawParamDirection::InOut, + 4 => drift.params[0].optional = true, + 5 => drift.params[0].const_attribute = !drift.params[0].const_attribute, + 6 => drift.params[1].typ.pointer_depth += 1, + 7 => drift.params[1].optional = !drift.params[1].optional, + 8 => drift.params[1].const_attribute = !drift.params[1].const_attribute, + _ => unreachable!(), + } + assert!( + validate_exact_method_contract( + namespace, + name, + &interface.interface.iid, + &drift, + contract, + ) + .is_err(), + "{name}.{method_name} admitted contract mutation {mutation}" + ); + } + } + assert!(errors.is_empty(), "{errors:#?}"); + } + #[test] fn hstring_mapping_requires_the_canonical_namespace() { assert!(is_canonical_hstring_name( diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index 05ae6ee0..34956b03 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -482,6 +482,8 @@ const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ "buffers.counted-buffer.entry.windows-win32-storage-packaging-opc.iopcsignaturecustomobject.5d77a19e62c144e7becd45da5ae51a56.getxml.slot-3.param-0-xmlmarkup.v1", "buffers.counted-buffer.entry.windows-win32-system-com.itypeinfo.0002040100000000c000000000000046.getnames.slot-7.param-1-rgbstrnames.v1", "com.ownership.entry.windows-win32-storage-packaging-opc.iopcsignaturecustomobject.5d77a19e62c144e7becd45da5ae51a56.getxml.slot-3.param-0-xmlmarkup.v1", + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getdatahere.slot-4.v1", + "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.setdata.slot-7.v1", "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.alloc.slot-3.v1", "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.didalloc.slot-7.v1", "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.free.slot-5.v1", @@ -491,12 +493,14 @@ const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ "com.ownership.entry.windows-win32-system-com.ipersistfile.0000010b00000000c000000000000046.getcurfile.slot-8.param-0-ppszfilename.v1", "com.ownership.entry.windows-win32-system-com.istream.0000000c00000000c000000000000046.stat.slot-12.v1", "com.ownership.entry.windows-win32-system-com-structuredstorage.istorage.0000000b00000000c000000000000046.stat.slot-17.v1", + "com.ownership.entry.windows-win32-system-ole.iolecache.0000011e00000000c000000000000046.setdata.slot-7.v1", "shell.flag-selected-string.entry.windows-win32-ui-shell.icontextmenu.000214e400000000c000000000000046.getcommandstring.slot-5.v1", "com.ownership.entry.windows-win32-ui-shell.ifiledialog.42f85136db7e439c85f1e4075d135fc8.getfilename.slot-16.param-0-pszname.v1", "com.ownership.entry.windows-win32-ui-shell.ishellitem.43826d1ee71842eebc55a1e261c37bfe.getdisplayname.slot-5.param-1-ppszname.v1", "com.ownership.entry.windows-win32-ui-shell.ishelllinka.000214ee00000000c000000000000046.getidlist.slot-4.param-0-ppidl.v1", "com.ownership.entry.windows-win32-ui-shell.ishelllinkw.000214f900000000c000000000000046.getidlist.slot-4.param-0-ppidl.v1", "com.semantic-hresult.entry.windows-win32-system-com.ipersistfile.0000010b00000000c000000000000046.getcurfile.slot-8.v1", + "com.semantic-hresult.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getcanonicalformatetc.slot-6.v1", "com.sequential-stream-buffer.entry.windows-win32-system-com.isequentialstream.0c733a302a1c11ceade500aa0044773d.read.slot-3.param-0-pv.v1", "com.sequential-stream-buffer.entry.windows-win32-system-com.isequentialstream.0c733a302a1c11ceade500aa0044773d.write.slot-4.param-0-pv.v1", "graphics.private-data-hazard.entry.windows-win32-ai-machinelearning-directml.idmlobject.c8263aac9e0c4a2d9b8e007521a3317c.getprivatedata.slot-3.v1", @@ -1139,7 +1143,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(), 495); + assert_eq!(ids.len(), 499); assert_eq!(registry.conditional_outputs.len(), 7); assert_eq!(registry.ownership_outputs.len(), 148); assert_eq!( diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index e25b68b2..21b53c50 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2126,6 +2126,214 @@ fn thumbnail_provider_returns_a_delete_object_owned_handle() { ); } +#[test] +fn data_object_projects_hglobal_format_and_medium_values() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "IDataObject", + ) + .expect("IDataObject must exist"); + let set_data_contract = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "SetData") + .and_then(|method| method.exact_contract.as_ref()) + .expect("SetData must carry exact ownership evidence"); + assert_eq!( + set_data_contract.kind, + com_metadata::RawExactMethodContractKind::BorrowedStgMediumInput + ); + assert_eq!(set_data_contract.ownership_transfer_param_index, Some(2)); + assert!( + set_data_contract + .citation + .ends_with("nf-objidl-idataobject-setdata") + ); + let output = com::generate_com_interface_files(&interface, &win32_winmd()) + .unwrap_or_else(|error| panic!("IDataObject: {error}")); + assert!( + output + .dts + .contains("getData(pformatetcIn: DynComFormatEtc): DynComStgMedium;") + ); + assert!(output.dts.contains( + "getDataHere(pformatetc: DynComFormatEtc, pmedium: DynComStgMedium): DynComStgMedium;" + )); + assert!( + output + .dts + .contains("setData(pformatetc: DynComFormatEtc, pmedium: DynComStgMedium): void;") + ); + assert!(!output.dts.contains("fRelease")); + assert!( + output + .js + .contains("DynCom.stgMedium(pmedium), DynCom.i32(0)") + ); + assert!(output.js.contains(".canonicalFormatEtcResult(0, 1)")); + let mut missing_canonical = interface.clone(); + missing_canonical + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "GetCanonicalFormatEtc") + .unwrap() + .exact_contract = None; + assert!(com::generate_com_interface_files(&missing_canonical, &win32_winmd()).is_err()); + + let advise_sink = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "IAdviseSink", + ) + .expect("IAdviseSink must exist"); + let advise_output = com::generate_com_interface_files(&advise_sink, &win32_winmd()) + .unwrap_or_else(|error| panic!("IAdviseSink: {error}")); + assert!(!advise_output.js.contains("static implementation(handlers)")); + assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); +} + +#[test] +fn storage_medium_in_out_requires_exact_preservation_evidence() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "IDataObject", + ) + .unwrap(); + let index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetDataHere") + .unwrap(); + let contract = interface.raw_methods.as_ref().unwrap()[index] + .exact_contract + .as_ref() + .unwrap(); + assert_eq!( + contract.kind, + com_metadata::RawExactMethodContractKind::PreservedStgMediumInOut + ); + assert_eq!(contract.buffer_param_index, 1); + assert_eq!(contract.vtable_index, 4); + for mutation in 0..6 { + let mut drift = interface.clone(); + let method = &mut drift.raw_methods.as_mut().unwrap()[index]; + match mutation { + 0 => method.exact_contract = None, + 1 => { + method.exact_contract = None; + method.metadata_name = "FillMedium".into(); + method.projected_name = "FillMedium".into(); + } + 2 => method.params[1].direction = com_metadata::RawParamDirection::Out, + 3 => method.params[1].typ.pointer_depth = 2, + 4 => method.params[1].optional = true, + 5 => method.exact_contract.as_mut().unwrap().buffer_param_index = 0, + _ => unreachable!(), + } + assert!( + com::generate_com_interface_files(&drift, &win32_winmd()).is_err(), + "GetDataHere admitted mutation {mutation}" + ); + } + let wia = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Devices.ImageAcquisition", + "IWiaDataTransfer", + ) + .unwrap(); + let method = wia + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "idtGetData") + .unwrap(); + assert_eq!( + method.params[0].direction, + com_metadata::RawParamDirection::InOut + ); + assert_eq!(method.params[0].typ.pointer_depth, 1); + assert!(method.exact_contract.is_none()); + let error = com::generate_com_interface_files(&wia, &win32_winmd()).unwrap_err(); + assert!( + error.contains( + "STGMEDIUM in/out requires exact contract evidence for caller-allocated preservation" + ), + "{error}" + ); +} + +#[test] +fn ole_cache_inherited_set_data_is_borrowed_and_fails_closed_on_drift() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + for name in ["IOleCache", "IOleCache2"] { + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Ole", name) + .unwrap(); + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + assert!( + output + .dts + .contains("setData(pformatetc: DynComFormatEtc, pmedium: DynComStgMedium): void;") + ); + assert!(!output.dts.contains("fRelease")); + assert!( + output + .js + .contains("DynCom.stgMedium(pmedium), DynCom.i32(0)") + ); + let index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "SetData") + .unwrap(); + let contract = interface.raw_methods.as_ref().unwrap()[index] + .exact_contract + .as_ref() + .unwrap(); + assert_eq!(contract.declaring_interface, "IOleCache"); + assert_eq!( + contract.declaring_iid, + "0000011e-0000-0000-c000-000000000046" + ); + for mutation in 0..3 { + let mut drift = interface.clone(); + let method = &mut drift.raw_methods.as_mut().unwrap()[index]; + match mutation { + 0 => method.exact_contract = None, + 1 => method.params[2].typ.pointer_depth = 1, + 2 => method.params[1].direction = com_metadata::RawParamDirection::InOut, + _ => unreachable!(), + } + assert!( + com::generate_com_interface_files(&drift, &win32_winmd()).is_err(), + "{name}.SetData admitted mutation {mutation}" + ); + } + } +} + #[test] fn high_value_exact_contracts_generate_complete_safe_interfaces() { if !win32_available() {