From 3ada6cec4626ed5cf885ce95bdd3a52f71e2d341 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 4 Sep 2026 17:51:43 +0800 Subject: [PATCH 1/8] Expand Classic COM stabilization coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .../generated-unsafe-companion.e2e.ts | 64 +++- bindings/js/src/com.rs | 15 + .../js/src/generated_unsafe_test_hooks.rs | 355 +++++++++++++++++- .../classic-com-generated-unsafe.md | 17 +- docs/architecture/classic-com-support.md | 1 + .../dynwinrt-codegen/tests/win32_com_test.rs | 29 +- 6 files changed, 463 insertions(+), 18 deletions(-) diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 610a09d0..ed7e9188 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -88,6 +88,7 @@ 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 thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') const runner = join(output, 'generated-companion-runner.cjs') writeFileSync( @@ -101,6 +102,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr `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 thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, `const cjsBarrel = require(${JSON.stringify(join(output, 'com', 'unsafe', 'index.js'))})`, @@ -118,20 +120,24 @@ 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 esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, ` 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 thumbnail.IThumbnailProvider, 'function')", " assert.equal(typeof audio.IAudioClientUnsafe, 'function')", ' assert.equal(esmAudio.IAudioClientUnsafe, audio.IAudioClientUnsafe)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(safeBarrel.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(cjsBarrel.UnsafePointerOutput, UnsafePointerOutput)', ' assert.equal(esmWbem.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', ' const createFake = runtime.createGeneratedIwbemServicesFake', ' const readStats = runtime.generatedUnsafeComStats', - ' const setOpenNamespaceMode = runtime.setGeneratedIwbemServicesOpenNamespaceMode', + ' const setConditionalMode = runtime.setGeneratedIwbemServicesConditionalMode', " assert.equal(typeof createFake, 'function')", " assert.equal(typeof readStats, 'function')", ' runtime.initializeCom(1)', @@ -145,7 +151,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.throws(() => wrapper.openNamespace('root', invalidOptions), /options|mode/)", ' assert.equal(readStats().openNamespaceCalls, 0)', ' }', - ' setOpenNamespaceMode(0)', + ' setConditionalMode(0)', ' const syncBefore = readStats()', " const workingNamespace = wrapper.openNamespace('root', { mode: 'sync' })", ' assert.ok(workingNamespace)', @@ -157,7 +163,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(readStats().currentRefCount, syncBefore.currentRefCount + 1)', ' workingNamespace.release()', ' assert.equal(readStats().currentRefCount, syncBefore.currentRefCount)', - ' setOpenNamespaceMode(1)', + ' setConditionalMode(1)', ' const asyncBefore = readStats()', " const callResult = wrapper.openNamespace('root', { mode: 'semisync' })", ' assert.ok(callResult)', @@ -170,7 +176,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(readStats().currentRefCount, asyncBefore.currentRefCount + 1)', ' callResult.release()', ' assert.equal(readStats().currentRefCount, asyncBefore.currentRefCount)', - ' setOpenNamespaceMode(-1)', + ' setConditionalMode(-1)', ' const failureBefore = readStats()', " assert.throws(() => wrapper.openNamespace('root', { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", ' assert.equal(readStats().currentRefCount, failureBefore.currentRefCount)', @@ -178,6 +184,29 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.throws(() => wrapper.openNamespace('root', { mode: 'semisync' }), /native call failed|HRESULT|0x80004005/i)", ' assert.equal(readStats().currentRefCount, resultFailureBefore.currentRefCount)', ' assert.equal(readStats().openNamespaceCalls, 4)', + ' setConditionalMode(0)', + " const object = wrapper.getObject('root', { mode: 'sync' })", + ' object.release()', + " wrapper.putClass(fake, { mode: 'sync' })", + " wrapper.deleteClass('Class', { mode: 'sync' })", + " wrapper.putInstance(fake, { mode: 'sync' })", + " wrapper.deleteInstance('root', { mode: 'sync' })", + " const methodOutput = wrapper.execMethod('root', 'Method', fake, { mode: 'sync' })", + ' methodOutput.release()', + ' setConditionalMode(1)', + " for (const result of [wrapper.getObject('root', { mode: 'semisync' }), wrapper.putClass(fake, { mode: 'semisync' }), wrapper.deleteClass('Class', { mode: 'semisync' }), wrapper.putInstance(fake, { mode: 'semisync' }), wrapper.deleteInstance('root', { mode: 'semisync' }), wrapper.execMethod('root', 'Method', fake, { mode: 'semisync' })]) result.release()", + ' setConditionalMode(-1)', + ' const conditionalFailureBefore = readStats().currentRefCount', + " assert.throws(() => wrapper.getObject('root', { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", + " assert.throws(() => wrapper.putClass(fake, { mode: 'semisync' }), /native call failed|HRESULT|0x80004005/i)", + " assert.throws(() => wrapper.execMethod('root', 'Method', fake, { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", + ' assert.equal(readStats().currentRefCount, conditionalFailureBefore)', + ' assert.equal(readStats().getObjectCalls, 3)', + ' assert.equal(readStats().putClassCalls, 3)', + ' assert.equal(readStats().deleteClassCalls, 2)', + ' assert.equal(readStats().putInstanceCalls, 2)', + ' assert.equal(readStats().deleteInstanceCalls, 2)', + ' assert.equal(readStats().execMethodCalls, 3)', ' wrapper.release()', ' assert.equal(readStats().currentRefCount, 1)', ' wrapper.release()', @@ -190,6 +219,33 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' wrapper?.release()', ' fake?.release()', ' }', + ' const createThumbnail = runtime.createGeneratedThumbnailProviderFake', + ' const thumbnailStats = runtime.generatedThumbnailProviderStats', + ' let thumbnailFake = createThumbnail()', + ' let thumbnailWrapper', + ' try {', + ' assert.equal(thumbnailStats().currentRefCount, 1)', + ' thumbnailWrapper = thumbnail.IThumbnailProvider._fromNative(thumbnailFake)', + ' assert.equal(thumbnailStats().currentRefCount, 2)', + ' const [bitmap, alphaType] = thumbnailWrapper.getThumbnail(96)', + " assert.equal(typeof bitmap.value, 'bigint')", + ' assert.ok(bitmap.value > 0n)', + ' assert.equal(alphaType, 2)', + ' assert.equal(thumbnailStats().calls, 1)', + ' bitmap.release()', + ' assert.equal(bitmap.isReleased, true)', + ' assert.throws(() => bitmap.value, /released/)', + ' bitmap.release()', + ' thumbnailWrapper.release()', + ' assert.equal(thumbnailStats().currentRefCount, 1)', + ' thumbnailFake.release()', + ' assert.equal(thumbnailStats().currentRefCount, 0)', + ' thumbnailWrapper = undefined', + ' thumbnailFake = undefined', + ' } finally {', + ' thumbnailWrapper?.release()', + ' thumbnailFake?.release()', + ' }', ' const createAudio = runtime.createGeneratedAudioClientFake', ' const audioStats = runtime.generatedAudioClientStats', ' const setServiceMode = runtime.setGeneratedAudioClientGetServiceMode', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index a7f0629f..264bb176 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -6644,6 +6644,21 @@ mod tests { .as_bool()); } + #[test] + fn delete_object_owned_handle_drop_releases_bitmap() { + let bitmap = unsafe { windows::Win32::Graphics::Gdi::CreateBitmap(1, 1, 1, 1, None) }; + assert!(!bitmap.is_invalid()); + let pointer = bitmap.0; + drop(DynComOwnedHandle::new( + pointer.addr(), + dynwinrt::com::OwnedHandleCleanup::DeleteObject, + )); + assert!(!unsafe { + windows::Win32::Graphics::Gdi::DeleteObject(windows::Win32::Graphics::Gdi::HGDIOBJ(pointer)) + } + .as_bool()); + } + #[test] fn delete_object_owned_handle_rejects_other_pointer_provenance() { let mut value = DynWinRTValue::from_com_result( diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index a46d80e3..083cd29f 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -15,6 +15,8 @@ use crate::DynWinRTValue; const IID_IWBEM_SERVICES: GUID = GUID::from_u128(0x9556dc99_828c_11cf_a37e_00aa003240c7); const IID_IWBEM_CONTEXT: GUID = GUID::from_u128(0x44aca674_e8fc_11d0_a07c_00c04fb68820); 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_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); @@ -24,13 +26,19 @@ static QUERY_INTERFACE_CALLS: AtomicU32 = AtomicU32::new(0); static ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); static RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_CALLS: AtomicU32 = AtomicU32::new(0); -static OPEN_NAMESPACE_MODE: AtomicI32 = AtomicI32::new(0); static OPEN_NAMESPACE_WORKING_SLOT_NULL: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_WORKING_ARGUMENT_NULL: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_RESULT_SLOT_NULL: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_RESULT_ARGUMENT_NULL: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_CONTEXT_ARGUMENT_NULL: AtomicU32 = AtomicU32::new(0); static OPEN_NAMESPACE_LAST_FLAGS: AtomicI32 = AtomicI32::new(0); +static WMI_CONDITIONAL_MODE: AtomicI32 = AtomicI32::new(0); +static GET_OBJECT_CALLS: AtomicU32 = AtomicU32::new(0); +static PUT_CLASS_CALLS: AtomicU32 = AtomicU32::new(0); +static DELETE_CLASS_CALLS: AtomicU32 = AtomicU32::new(0); +static PUT_INSTANCE_CALLS: AtomicU32 = AtomicU32::new(0); +static DELETE_INSTANCE_CALLS: AtomicU32 = AtomicU32::new(0); +static EXEC_METHOD_CALLS: AtomicU32 = AtomicU32::new(0); static QUERY_OBJECT_SINK_CALLS: AtomicU32 = AtomicU32::new(0); static LAST_FLAGS: AtomicI32 = AtomicI32::new(0); static CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); @@ -43,6 +51,8 @@ static AUDIO_GET_SERVICE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static THUMBNAIL_CALLS: AtomicU32 = AtomicU32::new(0); +static THUMBNAIL_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); #[repr(C)] struct GeneratedIWbemServicesVtbl { @@ -57,6 +67,55 @@ struct GeneratedIWbemServicesVtbl { ) -> HRESULT, cancel_async_call: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, query_object_sink: unsafe extern "system" fn(*mut c_void, i32, *mut *mut c_void) -> HRESULT, + get_object: unsafe extern "system" fn( + *mut c_void, + *mut u16, + i32, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, + ) -> HRESULT, + get_object_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + put_class: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + i32, + *mut c_void, + *mut *mut c_void, + ) -> HRESULT, + put_class_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + delete_class: + unsafe extern "system" fn(*mut c_void, *mut u16, i32, *mut c_void, *mut *mut c_void) -> HRESULT, + delete_class_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + create_class_enum: unsafe extern "system" fn(*mut c_void) -> HRESULT, + create_class_enum_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + put_instance: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + i32, + *mut c_void, + *mut *mut c_void, + ) -> HRESULT, + put_instance_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + delete_instance: + unsafe extern "system" fn(*mut c_void, *mut u16, i32, *mut c_void, *mut *mut c_void) -> HRESULT, + delete_instance_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + create_instance_enum: unsafe extern "system" fn(*mut c_void) -> HRESULT, + create_instance_enum_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + exec_query: unsafe extern "system" fn(*mut c_void) -> HRESULT, + exec_query_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + exec_notification_query: unsafe extern "system" fn(*mut c_void) -> HRESULT, + exec_notification_query_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, + exec_method: unsafe extern "system" fn( + *mut c_void, + *mut u16, + *mut u16, + i32, + *mut c_void, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, + ) -> HRESULT, } #[repr(C)] @@ -80,6 +139,7 @@ unsafe extern "system" fn query_interface( && *iid != IID_IWBEM_SERVICES && *iid != IID_IWBEM_CONTEXT && *iid != IID_IWBEM_CALL_RESULT + && *iid != IID_IWBEM_CLASS_OBJECT { return E_NOINTERFACE; } @@ -134,7 +194,7 @@ unsafe extern "system" fn open_namespace( { return E_POINTER; } - match OPEN_NAMESPACE_MODE.load(Ordering::SeqCst) { + match WMI_CONDITIONAL_MODE.load(Ordering::SeqCst) { 0 if flags == 0 && !working_namespace.is_null() && result.is_null() => { add_ref(this); unsafe { *working_namespace = this }; @@ -160,6 +220,143 @@ unsafe extern "system" fn open_namespace( } } +unsafe fn complete_conditional_call( + this: *mut c_void, + flags: i32, + context: *mut c_void, + synchronous_output: *mut *mut c_void, + semisynchronous_output: *mut *mut c_void, + synchronous_returns_value: bool, +) -> HRESULT { + if !context.is_null() + || (!synchronous_output.is_null() && unsafe { !(*synchronous_output).is_null() }) + || (!semisynchronous_output.is_null() && unsafe { !(*semisynchronous_output).is_null() }) + { + return E_POINTER; + } + match WMI_CONDITIONAL_MODE.load(Ordering::SeqCst) { + 0 if flags == 0 + && semisynchronous_output.is_null() + && (synchronous_returns_value == !synchronous_output.is_null()) => + { + if synchronous_returns_value { + add_ref(this); + unsafe { *synchronous_output = this }; + } + HRESULT(0) + } + 1 if flags == 0x10 && synchronous_output.is_null() && !semisynchronous_output.is_null() => { + add_ref(this); + unsafe { *semisynchronous_output = this }; + HRESULT(0) + } + -1 => { + if !synchronous_output.is_null() { + add_ref(this); + unsafe { *synchronous_output = this }; + } + if !semisynchronous_output.is_null() { + add_ref(this); + unsafe { *semisynchronous_output = this }; + } + HRESULT(0x80004005u32 as i32) + } + _ => E_NOTIMPL, + } +} + +unsafe extern "system" fn get_object( + this: *mut c_void, + object_path: *mut u16, + flags: i32, + context: *mut c_void, + object: *mut *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + GET_OBJECT_CALLS.fetch_add(1, Ordering::SeqCst); + if object_path.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, object, result, true) } +} + +unsafe extern "system" fn put_class( + this: *mut c_void, + object: *mut c_void, + flags: i32, + context: *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + PUT_CLASS_CALLS.fetch_add(1, Ordering::SeqCst); + if object.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } +} + +unsafe extern "system" fn delete_class( + this: *mut c_void, + class_name: *mut u16, + flags: i32, + context: *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + DELETE_CLASS_CALLS.fetch_add(1, Ordering::SeqCst); + if class_name.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } +} + +unsafe extern "system" fn put_instance( + this: *mut c_void, + instance: *mut c_void, + flags: i32, + context: *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + PUT_INSTANCE_CALLS.fetch_add(1, Ordering::SeqCst); + if instance.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } +} + +unsafe extern "system" fn delete_instance( + this: *mut c_void, + object_path: *mut u16, + flags: i32, + context: *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + DELETE_INSTANCE_CALLS.fetch_add(1, Ordering::SeqCst); + if object_path.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } +} + +unsafe extern "system" fn exec_method( + this: *mut c_void, + object_path: *mut u16, + method_name: *mut u16, + flags: i32, + context: *mut c_void, + input: *mut c_void, + output: *mut *mut c_void, + result: *mut *mut c_void, +) -> HRESULT { + EXEC_METHOD_CALLS.fetch_add(1, Ordering::SeqCst); + if object_path.is_null() || method_name.is_null() || input.is_null() { + return E_POINTER; + } + unsafe { complete_conditional_call(this, flags, context, output, result, true) } +} + +unsafe extern "system" fn unimplemented_wbem_method(_this: *mut c_void) -> HRESULT { + E_NOTIMPL +} + unsafe extern "system" fn cancel_async_call(_this: *mut c_void, _sink: *mut c_void) -> HRESULT { E_NOTIMPL } @@ -191,6 +388,25 @@ static VTABLE: GeneratedIWbemServicesVtbl = GeneratedIWbemServicesVtbl { open_namespace, cancel_async_call, query_object_sink, + get_object, + get_object_async: unimplemented_wbem_method, + put_class, + put_class_async: unimplemented_wbem_method, + delete_class, + delete_class_async: unimplemented_wbem_method, + create_class_enum: unimplemented_wbem_method, + create_class_enum_async: unimplemented_wbem_method, + put_instance, + put_instance_async: unimplemented_wbem_method, + delete_instance, + delete_instance_async: unimplemented_wbem_method, + create_instance_enum: unimplemented_wbem_method, + create_instance_enum_async: unimplemented_wbem_method, + exec_query: unimplemented_wbem_method, + exec_query_async: unimplemented_wbem_method, + exec_notification_query: unimplemented_wbem_method, + exec_notification_query_async: unimplemented_wbem_method, + exec_method, }; #[napi(object)] @@ -205,6 +421,12 @@ pub struct GeneratedUnsafeComStats { pub open_namespace_result_argument_null: bool, pub open_namespace_context_argument_null: bool, pub open_namespace_last_flags: i32, + pub get_object_calls: u32, + pub put_class_calls: u32, + pub delete_class_calls: u32, + pub put_instance_calls: u32, + pub delete_instance_calls: u32, + pub exec_method_calls: u32, pub query_object_sink_calls: u32, pub last_flags: i32, pub current_ref_count: u32, @@ -217,13 +439,19 @@ pub fn create_generated_iwbem_services_fake() -> napi::Result { ADD_REF_CALLS.store(0, Ordering::SeqCst); RELEASE_CALLS.store(0, Ordering::SeqCst); OPEN_NAMESPACE_CALLS.store(0, Ordering::SeqCst); - OPEN_NAMESPACE_MODE.store(0, Ordering::SeqCst); + WMI_CONDITIONAL_MODE.store(0, Ordering::SeqCst); OPEN_NAMESPACE_WORKING_SLOT_NULL.store(0, Ordering::SeqCst); OPEN_NAMESPACE_WORKING_ARGUMENT_NULL.store(0, Ordering::SeqCst); OPEN_NAMESPACE_RESULT_SLOT_NULL.store(0, Ordering::SeqCst); OPEN_NAMESPACE_RESULT_ARGUMENT_NULL.store(0, Ordering::SeqCst); OPEN_NAMESPACE_CONTEXT_ARGUMENT_NULL.store(0, Ordering::SeqCst); OPEN_NAMESPACE_LAST_FLAGS.store(0, Ordering::SeqCst); + GET_OBJECT_CALLS.store(0, Ordering::SeqCst); + PUT_CLASS_CALLS.store(0, Ordering::SeqCst); + DELETE_CLASS_CALLS.store(0, Ordering::SeqCst); + PUT_INSTANCE_CALLS.store(0, Ordering::SeqCst); + DELETE_INSTANCE_CALLS.store(0, Ordering::SeqCst); + EXEC_METHOD_CALLS.store(0, Ordering::SeqCst); QUERY_OBJECT_SINK_CALLS.store(0, Ordering::SeqCst); LAST_FLAGS.store(0, Ordering::SeqCst); CURRENT_REF_COUNT.store(1, Ordering::SeqCst); @@ -255,6 +483,12 @@ pub fn generated_unsafe_com_stats() -> GeneratedUnsafeComStats { .load(Ordering::SeqCst) != 0, open_namespace_last_flags: OPEN_NAMESPACE_LAST_FLAGS.load(Ordering::SeqCst), + get_object_calls: GET_OBJECT_CALLS.load(Ordering::SeqCst), + put_class_calls: PUT_CLASS_CALLS.load(Ordering::SeqCst), + delete_class_calls: DELETE_CLASS_CALLS.load(Ordering::SeqCst), + put_instance_calls: PUT_INSTANCE_CALLS.load(Ordering::SeqCst), + delete_instance_calls: DELETE_INSTANCE_CALLS.load(Ordering::SeqCst), + exec_method_calls: EXEC_METHOD_CALLS.load(Ordering::SeqCst), query_object_sink_calls: QUERY_OBJECT_SINK_CALLS.load(Ordering::SeqCst), last_flags: LAST_FLAGS.load(Ordering::SeqCst), current_ref_count: CURRENT_REF_COUNT.load(Ordering::SeqCst), @@ -263,16 +497,125 @@ pub fn generated_unsafe_com_stats() -> GeneratedUnsafeComStats { } #[napi] -pub fn set_generated_iwbem_services_open_namespace_mode(mode: i32) -> napi::Result<()> { +pub fn set_generated_iwbem_services_conditional_mode(mode: i32) -> napi::Result<()> { if !matches!(mode, -1..=1) { return Err(napi::Error::from_reason( - "IWbemServices::OpenNamespace test mode must be -1, 0, or 1", + "IWbemServices conditional test mode must be -1, 0, or 1", )); } - OPEN_NAMESPACE_MODE.store(mode, Ordering::SeqCst); + WMI_CONDITIONAL_MODE.store(mode, Ordering::SeqCst); Ok(()) } +#[repr(C)] +struct GeneratedThumbnailProviderVtbl { + base__: IUnknown_Vtbl, + get_thumbnail: unsafe extern "system" fn(*mut c_void, u32, *mut *mut c_void, *mut i32) -> HRESULT, +} + +#[repr(C)] +struct GeneratedThumbnailProviderFake { + vtable: *const GeneratedThumbnailProviderVtbl, + references: AtomicU32, +} + +unsafe extern "system" fn thumbnail_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_ITHUMBNAIL_PROVIDER { + return E_NOINTERFACE; + } + *result = this; + thumbnail_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn thumbnail_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + THUMBNAIL_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn thumbnail_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + THUMBNAIL_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn get_thumbnail( + _this: *mut c_void, + size: u32, + bitmap: *mut *mut c_void, + alpha_type: *mut i32, +) -> HRESULT { + THUMBNAIL_CALLS.fetch_add(1, Ordering::SeqCst); + if size == 0 || bitmap.is_null() || alpha_type.is_null() { + return E_POINTER; + } + if unsafe { !(*bitmap).is_null() } { + return E_POINTER; + } + let bitmap_value = unsafe { windows::Win32::Graphics::Gdi::CreateBitmap(1, 1, 1, 1, None) }; + if bitmap_value.is_invalid() { + return HRESULT(0x80004005u32 as i32); + } + unsafe { + *bitmap = bitmap_value.0; + *alpha_type = 2; + } + HRESULT(0) +} + +static THUMBNAIL_VTABLE: GeneratedThumbnailProviderVtbl = GeneratedThumbnailProviderVtbl { + base__: IUnknown_Vtbl { + QueryInterface: thumbnail_query_interface, + AddRef: thumbnail_add_ref, + Release: thumbnail_release, + }, + get_thumbnail, +}; + +#[napi(object)] +pub struct GeneratedThumbnailProviderStats { + pub calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_thumbnail_provider_fake() -> napi::Result { + THUMBNAIL_CALLS.store(0, Ordering::SeqCst); + THUMBNAIL_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedThumbnailProviderFake { + vtable: &THUMBNAIL_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_thumbnail_provider_stats() -> GeneratedThumbnailProviderStats { + GeneratedThumbnailProviderStats { + calls: THUMBNAIL_CALLS.load(Ordering::SeqCst), + current_ref_count: THUMBNAIL_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + #[repr(C)] struct GeneratedAudioClientVtbl { base__: IUnknown_Vtbl, diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index 0b3cd63e..ff595368 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -655,12 +655,21 @@ Required tests include: 9. x64 and i686 live raw calls; 10. ARM64 compile/gate behavior; 11. deterministic support manifest generation; and -12. complete safe COM and WinRT regression suites. +12. complete safe COM and WinRT regression suites; and +13. actual Node resolution of mixed WinRT, COM barrel, and unsafe canonical + package exports. The generated-artifact integration fixture combines safe WMI with unsafe Audio. -The WMI test-hook validates sync/semisync OptionalOut selection, native-null -context, failure cleanup, QueryInterface/AddRef/Release balance, CJS, ESM, and -emitted declarations without requiring a live WMI service. +The complete seven-method WMI conditional-output family executes through a +slot-accurate fake `IWbemServices` vtable. It validates sync/semisync +OptionalOut selection, no-output sync calls, `ExecMethod` multi-input calls, +native-null context, failure cleanup, QueryInterface/AddRef/Release balance, +CJS, ESM, and emitted declarations without requiring a live WMI service. + +The same fixture invokes generated `IThumbnailProvider.getThumbnail()` against +a fake COM object that returns a real HBITMAP. It validates transfer into +`DynComOwnedHandle`, explicit `DeleteObject` release, idempotence, and COM +reference balance; a Rust regression separately covers the Drop path. The unsafe portion uses official `IAudioClientUnsafe::isFormatSupported` and `getService` vtable slots. It covers diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 790e0461..b2c588c1 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -1348,6 +1348,7 @@ hardware, and whether it adds a distinct ABI shape. | `IMalloc` | COM task allocator | Complete generation is gated by exact IID/slot/shape evidence. Opaque values reject forged/stale addresses; destructive and size operations enforce allocator identity, while `DidAlloc` permits borrowed cross-allocator inspection. | | `IPersistFile` | Loading and saving persistent COM objects | Core tests query it from `IShellLinkW`; Node activates the Shell Link coclass directly as `IPersistFile` and verifies `GetClassID`. | | `IShellLinkW` | Shortcut creation and inspection | Core runtime tests cover strings, `u16`, enums, and scalar outputs; generated Node coverage round-trips `GetPath` with nested `FILETIME` and fixed WCHAR-array `WIN32_FIND_DATAW` POD storage. | +| `IThumbnailProvider` | Shell thumbnails | A generated-wrapper integration test receives a real HBITMAP from a fake COM vtable, transfers it into `DynComOwnedHandle`, and verifies explicit `DeleteObject` release plus best-effort Drop cleanup. | | `FileOpenDialog` | Desktop file selection | Node test covers coclass construction and option round-trip without showing UI. | | `FileOperation` | Shell copy/move/delete operations | Node test covers coclass construction, unsigned flags, and state without modifying files. | | `IWICImagingFactory` | Windows Imaging Component | Node test activates WIC and creates an interface-valued stream. | diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 179f38e6..e25b68b2 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -6175,11 +6175,13 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { eprintln!("Skipping: Windows.winmd not available"); return; }; - let output = std::env::temp_dir().join(format!( + let root = std::env::temp_dir().join(format!( "dynwinrt-codegen-mixed-unsafe-only-{}", std::process::id() )); - let _ = fs::remove_dir_all(&output); + let output = root.join("node_modules").join("@winapp").join("bindings"); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(output.parent().unwrap()).unwrap(); remove_com_generation_lock(&output); run_codegen_command( @@ -6204,8 +6206,27 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { assert!(package.contains("\"./com\":")); assert!(package.contains("\"./com/*\":")); - fs::remove_dir_all(&output).unwrap(); - remove_com_generation_lock(&output); + let resolved = Command::new("node") + .args([ + "-e", + "for (const id of [\ + '@winapp/bindings',\ + '@winapp/bindings/windows/foundation/Uri',\ + '@winapp/bindings/com',\ + '@winapp/bindings/com/unsafe/windows/win32/media/audio/IAudioClientUnsafe'\ + ]) console.log(require.resolve(id))", + ]) + .current_dir(&root) + .output() + .expect("resolve mixed generated package exports"); + assert!( + resolved.status.success(), + "generated package exports were not consumable:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&resolved.stdout), + String::from_utf8_lossy(&resolved.stderr) + ); + + fs::remove_dir_all(&root).unwrap(); } /// Requirement 8: multi-interface COM generation must be atomic enough that From d0794709264b55e4b59bbb2b563f72cce1c7a96f Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 4 Sep 2026 20:02:24 +0800 Subject: [PATCH 2/8] Add safe HGLOBAL data transfer support Model FORMATETC and STGMEDIUM as dedicated COM ABI values, generate a caller-owned IDataObject SetData projection, and validate real HGLOBAL cleanup paths. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 34 +- README.md | 12 +- .../generated-unsafe-companion.e2e.ts | 46 +- bindings/js/__test__/index.spec.ts | 20 + bindings/js/scripts/generate-entrypoints.mjs | 2 + bindings/js/src/com.rs | 146 +++++ .../js/src/generated_unsafe_test_hooks.rs | 371 ++++++++++++ bindings/js/src/lib.rs | 22 + crates/dynwinrt/Cargo.toml | 1 + crates/dynwinrt/src/call.rs | 112 ++++ crates/dynwinrt/src/com.rs | 559 +++++++++++++++++- crates/dynwinrt/src/native_call.rs | 99 +++- .../classic-com-contract-evidence-registry.md | 35 +- docs/architecture/classic-com-support.md | 50 +- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 54 +- .../classic-com-capability-summary.json | 167 +++--- .../classic-com-interface-support.csv | 22 +- .../src/codegen/com/capability.rs | 49 +- .../src/codegen/com/generated_unsafe.rs | 10 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 12 +- .../src/codegen/com/javascript/render.rs | 28 +- .../src/codegen/com/javascript/types.rs | 12 + .../src/codegen/com/model/abi.rs | 2 + .../src/codegen/com/model/metadata.rs | 76 +++ .../src/codegen/com/model/method.rs | 5 + .../src/codegen/com/model/ownership.rs | 6 + .../src/codegen/com/project/mod.rs | 34 +- tools/dynwinrt-codegen/src/com_metadata.rs | 142 ++++- .../dynwinrt-codegen/src/contract_registry.rs | 3 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 64 ++ 30 files changed, 1977 insertions(+), 218 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 44e6b1c7..a20d3899 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 5692) { 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 5692) { 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 5692 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2237 ) { throw "Classic COM compact interface support index changed" } $expected = @{ - x64 = @(412, 1446, 390) - i686 = @(411, 1423, 414) - arm64 = @(412, 1446, 390) + x64 = @(412, 1437, 388) + i686 = @(411, 1414, 412) + arm64 = @(412, 1437, 388) } 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 5692 -or + $result.safeEvidence.standardDerived -ne 5336 -or + $result.safeEvidence.exactRegistryDependent -ne 356 -or + $result.safeEvidence.metadataFactOccurrences -ne 5976 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26119 -or + $result.safeEvidence.registeredExactEntries -ne 496 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 496 -or + $result.safeEvidence.safeConsumedExactEntries -ne 405 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 656 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 405 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/README.md b/README.md index 3d258f4a..54aa8ff3 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,692 of 7,929 +eligible interfaces (71.79%)** 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 ed7e9188..6e1a4661 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.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider', + 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject', '--output', output, ] @@ -88,6 +88,7 @@ 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 thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') const runner = join(output, 'generated-companion-runner.cjs') @@ -98,10 +99,12 @@ 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 thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, @@ -120,18 +123,22 @@ 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 esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, ` 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 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.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(cjsBarrel.UnsafePointerOutput, UnsafePointerOutput)', ' assert.equal(esmWbem.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmDataObject.IDataObject, dataObject.IDataObject)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', @@ -246,6 +253,34 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' thumbnailWrapper?.release()', ' thumbnailFake?.release()', ' }', + ' const createDataObject = runtime.createGeneratedDataObjectFake', + ' const dataObjectStats = runtime.generatedDataObjectStats', + ' 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(dataObjectWrapper.queryGetData(format), 0)', + ' const [canonicalResult, canonical] = dataObjectWrapper.getCanonicalFormatEtc(format)', + ' assert.equal(canonicalResult, 0)', + ' assert.equal(canonical.clipboardFormat, 13)', + ' dataObjectWrapper.setData(format, DynComStgMedium.hglobal(Buffer.from([5, 6, 7, 8])))', + ' assert.deepEqual(dataObjectStats(), { getDataCalls: 1, getDataHereCalls: 1, queryGetDataCalls: 1, canonicalCalls: 1, setDataCalls: 1, lastSetRelease: 0, outputReleased: true, getDataHereInputReleased: true, setDataInputReleased: true, currentRefCount: 2 })', + ' dataObjectWrapper.release()', + ' dataObjectFake.release()', + ' assert.equal(dataObjectStats().currentRefCount, 0)', + ' dataObjectWrapper = undefined', + ' dataObjectFake = undefined', + ' } finally {', + ' dataObjectWrapper?.release()', + ' dataObjectFake?.release()', + ' }', ' const createAudio = runtime.createGeneratedAudioClientFake', ' const audioStats = runtime.generatedAudioClientStats', ' const setServiceMode = runtime.setGeneratedAudioClientGetServiceMode', @@ -642,15 +677,18 @@ 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 { 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', 'const direct: IWbemServices = IWbemServices._fromNative(native)', 'const barrel: FromBarrel = FromBarrel._fromNative(native)', "const namespaceOutput = direct.openNamespace('root', { mode: 'sync' })", @@ -660,6 +698,12 @@ 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()', + '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 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..5e143070 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); @@ -3067,6 +3095,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 +4898,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 +5740,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 +5821,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 083cd29f..c704bdc9 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -17,6 +17,7 @@ const IID_IWBEM_CONTEXT: GUID = GUID::from_u128(0x44aca674_e8fc_11d0_a07c_00c04f 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); @@ -53,6 +54,16 @@ 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_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); #[repr(C)] struct GeneratedIWbemServicesVtbl { @@ -616,6 +627,366 @@ 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) +} + +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; + } + 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) +} + +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_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 generated_data_object_stats() -> GeneratedDataObjectStats { + let handle_released = |address| { + address != 0 + && unsafe { + windows::Win32::System::Memory::GlobalSize(windows::Win32::Foundation::HGLOBAL( + std::ptr::with_exposed_provenance_mut(address), + )) + } == 0 + }; + 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: handle_released(DATA_OBJECT_LAST_OUTPUT_HANDLE.load(Ordering::SeqCst)), + get_data_here_input_released: handle_released( + DATA_OBJECT_LAST_GET_DATA_HERE_HANDLE.load(Ordering::SeqCst), + ), + set_data_input_released: 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 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..f76ab0a6 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,24 @@ where ) }, )?)); + } else if let Some(value) = format_etc_out_values.remove(&p.value_index) { + result_values.push(NativeCallValue::FormatEtc(value.into_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..3b4615f1 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -645,6 +645,261 @@ 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 + } + + fn free_target_device(&mut self) { + if self.raw.ptd.is_null() { + return; + } + unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(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 +1247,8 @@ pub enum Value { DispatchParams(DispatchParamsValue), ExcepInfo(ExcepInfoValue), StatStg(StatStgValue), + FormatEtc(FormatEtcValue), + StgMedium(StgMediumValue), Buffer(ComBufferValue), } @@ -1008,6 +1265,8 @@ fn is_null_input_value(value: &Value) -> bool { | Value::DispatchParams(_) | Value::ExcepInfo(_) | Value::StatStg(_) + | Value::FormatEtc(_) + | Value::StgMedium(_) | Value::Buffer(_) => false, } } @@ -1757,7 +2016,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 +2318,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 +3270,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 +3724,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 +4378,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 +4576,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( @@ -5795,6 +6082,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 +10789,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 +13764,131 @@ 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 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..2d6d7078 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(_) @@ -816,6 +853,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 @@ -1349,7 +1388,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 +1447,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 +1496,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 +1509,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 +2010,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 +2204,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 +2288,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..11cb958e 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -335,11 +335,12 @@ 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::SetData` caller-retained STGMEDIUM ownership; 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,692/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -400,19 +401,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,336 | +| `exact_registry_dependent` | 356 | +| **Total** | **5,692** | -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 **496 declared entries**, all 496 match the pinned +metadata, and 405 distinct entries are consumed by safe plans. Safe plans have +656 entry/interface dependencies and 405 family/interface dependencies. +Per-interface dependency-set totals also include 5,976 metadata-attribute +dependencies and 26,119 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 172 | +| `ownership` | 173 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 7 | @@ -435,7 +436,7 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 162 | 111 | 116 | +| `com.ownership.v1` | 163 | 112 | 117 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | | `com.semantic-hresult.v1` | 1 | 1 | 2 | @@ -453,11 +454,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,574 | +| `com.interface.input-borrow.v1` | 1,891 | +| `com.interface.typed-output-plus-one.v1` | 3,458 | +| `com.iunknown.identity-refcount.v1` | 5,692 | +| `com.query-interface.output-plus-one.v1` | 5,692 | | `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..4da6a117 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,692 complete safe +> interface projections out of 7,929 eligible interfaces (71.79%). 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`; `GetDataHere` preserves caller allocation; exact IID/slot/shape/fingerprint evidence pins `SetData.fRelease=FALSE` | `DVTARGETDEVICE`, non-HGLOBAL media, 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` fixes `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. | @@ -704,8 +707,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 +721,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 +1226,14 @@ 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 11 more interfaces, bringing +the current literal census to **5,692 / 7,929 = 71.787111%**. 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,692, or coverage falls below 70%. ## Public-code frequency snapshot @@ -1276,7 +1281,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 +1314,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 +1336,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 +1369,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 9f6c9624..30092ee1 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,692 | 71.79% | +| Rejected because at least one contract is incomplete | 2,237 | 28.21% | 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,692 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: @@ -341,31 +341,31 @@ 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,160 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,692 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,326 | -| `exact_registry_dependent` | 355 | +| `standard_derived` | 5,336 | +| `exact_registry_dependent` | 356 | -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 496 selector-specific entries; all 496 match pinned +metadata, 405 distinct entries are safe-consumed, and safe plans contain 656 +entry/interface plus 405 family/interface dependencies. They also consume +5,976 metadata-attribute and 26,119 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 173, 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, per-family rollups, and per-interface entry IDs are retained in the summary @@ -393,18 +393,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,692 of 7,929 interfaces. The separate outbound raw census +classifies the 2,237 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 | 388 | +| i686 | 411 | 1,414 | 412 | +| ARM64 | 412 | 1,437 | 388 | -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,104 +metadata-complete, 1,437 manual, and 388 blocked interfaces. i686 has 6,103 +metadata-complete, 1,414 manual, and 412 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 @@ -414,14 +414,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,692 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, @@ -508,7 +508,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,692 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..0bb19500 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": 5692, + "safe_incomplete": 2237, "safeEvidence": { - "safeComplete": 5681, - "standardDerived": 5326, - "exactRegistryDependent": 355, - "metadataFactOccurrences": 5974, - "comStandardFactOccurrences": 26076, - "registeredExactEntries": 495, - "metadataMatchedExactEntries": 495, - "safeConsumedExactEntries": 404, - "exactEntryInterfaceDependencies": 655, - "exactFamilyInterfaceDependencies": 404, + "safeComplete": 5692, + "standardDerived": 5336, + "exactRegistryDependent": 356, + "metadataFactOccurrences": 5976, + "comStandardFactOccurrences": 26119, + "registeredExactEntries": 496, + "metadataMatchedExactEntries": 496, + "safeConsumedExactEntries": 405, + "exactEntryInterfaceDependencies": 656, + "exactFamilyInterfaceDependencies": 405, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, @@ -102,7 +102,7 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 2, - "ownership": 172, + "ownership": 173, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 2 @@ -445,6 +445,7 @@ "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.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, @@ -519,7 +520,7 @@ "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, - "com.ownership.v1": 116, + "com.ownership.v1": 117, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 2, @@ -529,8 +530,8 @@ "wmi.conditional-output.v1": 1 }, "byMetadataAttribute": { - "CanReturnMultipleSuccessValuesAttribute": 42, - "ConstAttribute": 3327, + "CanReturnMultipleSuccessValuesAttribute": 43, + "ConstAttribute": 3328, "FreeWithAttribute": 3, "NativeArrayInfoAttribute": 2602 }, @@ -540,11 +541,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": 5574, + "com.interface.input-borrow.v1": 1891, + "com.interface.typed-output-plus-one.v1": 3458, + "com.iunknown.identity-refcount.v1": 5692, + "com.query-interface.output-plus-one.v1": 5692, "com.standard-cleanup.matching-allocator.v1": 1436 }, "exactEntryStatus": { @@ -4966,7 +4967,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 +8882,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 +8910,24 @@ "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 +8939,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 +8957,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 +8975,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 +8993,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 +9011,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 +9029,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 +9068,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, @@ -9925,7 +9944,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 +9962,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 +9980,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 +9998,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 +10016,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 +10034,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 +10052,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 +10070,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 +10670,37 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6093, - "raw_manual_contract": 1446, - "raw_runtime_blocked": 390, + "raw_metadata_complete": 6104, + "raw_manual_contract": 1437, + "raw_runtime_blocked": 388, "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": 388 }, "i686": { - "raw_metadata_complete": 6092, - "raw_manual_contract": 1423, - "raw_runtime_blocked": 414, + "raw_metadata_complete": 6103, + "raw_manual_contract": 1414, + "raw_runtime_blocked": 412, "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": 412 }, "x64": { - "raw_metadata_complete": 6093, - "raw_manual_contract": 1446, - "raw_runtime_blocked": 390, + "raw_metadata_complete": 6104, + "raw_manual_contract": 1437, + "raw_runtime_blocked": 388, "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": 388 } }, "blocker_reason_counts": { "arm64": { - "incomplete_pointee_layout_for_storage": 339, + "incomplete_pointee_layout_for_storage": 337, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 240, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10690,11 +10709,11 @@ "unsupported_layout_kind": 4 }, "i686": { - "incomplete_pointee_layout_for_storage": 363, + "incomplete_pointee_layout_for_storage": 361, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 240, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10703,11 +10722,11 @@ "unsupported_layout_kind": 4 }, "x64": { - "incomplete_pointee_layout_for_storage": 339, + "incomplete_pointee_layout_for_storage": 337, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 242, + "pointee_missing_layout": 240, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10718,52 +10737,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 +10838,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..5364de08 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -274,7 +274,7 @@ Windows.Win32.Devices.ImageAcquisition,IEnumWiaItem,5e8383fc-3391-11d2-9a33-00c0 Windows.Win32.Devices.ImageAcquisition,IEnumWiaItem2,59970af4-cd0d-44d9-ab24-52295630e582,true,exact_registry_dependent, Windows.Win32.Devices.ImageAcquisition,IWiaAppErrorHandler,6c16186c-d0a6-400c-80f4-d26986a0e734,true,exact_registry_dependent, Windows.Win32.Devices.ImageAcquisition,IWiaDataCallback,a558a866-a5b0-11d2-a08f-00c04f72dc3c,true,standard_derived, -Windows.Win32.Devices.ImageAcquisition,IWiaDataTransfer,a6cef998-a5b0-11d2-a08f-00c04f72dc3c,false,,incomplete_pointee_layout_for_storage +Windows.Win32.Devices.ImageAcquisition,IWiaDataTransfer,a6cef998-a5b0-11d2-a08f-00c04f72dc3c,true,standard_derived, Windows.Win32.Devices.ImageAcquisition,IWiaDevMgr,5eb2502a-8cf1-11d1-bf92-0060081ed811,false,,safe_projection_incomplete Windows.Win32.Devices.ImageAcquisition,IWiaDevMgr2,79c07cf1-cbdd-41ee-8ec3-f00080cada7a,false,,safe_projection_incomplete Windows.Win32.Devices.ImageAcquisition,IWiaDrvItem,1f02b5c5-b00c-11d2-a094-00c04f72dc3c,false,,missing_allocator @@ -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,standard_derived, +Windows.Win32.System.Ole,IOleCache2,00000128-0000-0000-c000-000000000046,true,standard_derived, 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..428b23af 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_692); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_692); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_336); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 356); 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_119 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 495); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 496); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 495 + 496 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 404 + 405 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 655 + 656 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 404 + 405 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4610,7 +4610,7 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 2), - ("ownership".into(), 172), + ("ownership".into(), 173), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 2), @@ -4618,7 +4618,7 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 116 + 117 ); 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(), 405); assert!( report .summary @@ -4677,7 +4677,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 404 + 405 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( @@ -4744,6 +4744,21 @@ 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_eq!( promoted_audio .exact_entry_ids @@ -4812,8 +4827,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), + 388 + 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..c964c32b 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_160); } #[test] diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index fe4dffe4..0cf90159 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,9 @@ pub(super) enum ProjectedComMethodKind { synchronous_flags: i32, semisynchronous_flags: i32, }, + DataObjectSetData { + release_param_index: usize, + }, } /// The JS runtime `typeof`/shape category a validated value uses at a call @@ -568,7 +575,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..b28f813d 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -408,7 +408,8 @@ fn render_js(meta: &ProjectedComInterface) -> String { match method.kind { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } - | ProjectedComMethodKind::OwningCallerOutput { .. } => { + | ProjectedComMethodKind::OwningCallerOutput { .. } + | ProjectedComMethodKind::DataObjectSetData { .. } => { emit_method_js(&mut out, method, &iface_var) } ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -887,6 +888,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 +1232,14 @@ fn emit_method_js_named( if matches!(param.typ, ComType::ExactNullPointer) { return Some("DynCom.exactNullPointer(null)".into()); } + if matches!( + method.kind, + ProjectedComMethodKind::DataObjectSetData { + 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 +2419,8 @@ fn render_dts(meta: &ProjectedComInterface) -> String { let (params, ret) = match method.kind { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } - | ProjectedComMethodKind::OwningCallerOutput { .. } => { + | ProjectedComMethodKind::OwningCallerOutput { .. } + | ProjectedComMethodKind::DataObjectSetData { .. } => { (dts_params(method), dts_return_type(method)) } ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -2624,6 +2636,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 +2738,8 @@ fn collect_native_pods(meta: &ProjectedComInterface) -> Vec {} @@ -2814,6 +2830,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 +2914,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/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..62b3fb6e 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -429,6 +429,16 @@ fn map_method( validation_flag: 6, }) } + Some(RawExactMethodContractKind::DataObjectSetData) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::DataObjectSetData { + release_param: ParamIndex::new( + contract + .ownership_transfer_param_index + .expect("validated SetData ownership-transfer parameter"), + ), + }) + } None => method, } }; @@ -501,6 +511,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 +1015,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 +1215,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 +1518,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 +1589,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 +1808,8 @@ fn buffer_element_ownership( | ComAbiType::DispatchParams | ComAbiType::ExcepInfo | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => BufferElementOwnership::Unknown, }; @@ -1884,6 +1946,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..abeed3ce 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -53,6 +53,9 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { synchronous_flags: i32, semisynchronous_flags: i32, }, + DataObjectSetData { + release_param: ParamIndex, + }, Malloc, } @@ -165,6 +168,8 @@ impl ComMethodContract { .. } | ComAbiType::StatStg + | ComAbiType::FormatEtc + | ComAbiType::StgMedium ) { return Err(ModelError::InvalidContract(format!( 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..b8a52195 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,11 @@ fn project_method( synchronous_flags, semisynchronous_flags, }, + Some(ComMethodSpecialContract::DataObjectSetData { release_param }) => { + ProjectedComMethodKind::DataObjectSetData { + release_param_index: release_param.index(), + } + } Some(ComMethodSpecialContract::Malloc) | None => project_dynamic_method_kind( method.name(), dynamic_iid.map(|contract| { @@ -983,7 +990,18 @@ fn project_method( ) { surface_input = false; } - if direction == ComParamDirection::InOut && !is_scalar_in_out(&typ) { + if matches!( + &kind, + ProjectedComMethodKind::DataObjectSetData { + release_param_index + } if *release_param_index == index + ) { + surface_input = false; + } + if direction == ComParamDirection::InOut + && !is_scalar_in_out(&typ) + && !matches!(typ, ComType::StgMedium) + { return Err(format!( "{}: unsupported [in, out] parameter `{}`", context(), @@ -1642,6 +1660,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 +2062,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 +2839,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..9b47f1c4 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -381,6 +381,7 @@ pub enum RawExactMethodContractKind { StatStg, Malloc, FlagSelectedString, + DataObjectSetData, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -396,6 +397,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,7 +412,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::UnsafePrivateData => { crate::contract_registry::ExactFamilyId::PrivateDataHazard } - RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc => { + RawExactMethodContractKind::StatStg + | RawExactMethodContractKind::Malloc + | RawExactMethodContractKind::DataObjectSetData => { crate::contract_registry::ExactFamilyId::Ownership } RawExactMethodContractKind::FlagSelectedString => { @@ -437,7 +442,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::UnsafePrivateData => { crate::contract_registry::ContractKind::Hazard } - RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc => { + RawExactMethodContractKind::StatStg + | RawExactMethodContractKind::Malloc + | RawExactMethodContractKind::DataObjectSetData => { crate::contract_registry::ContractKind::Ownership } RawExactMethodContractKind::FlagSelectedString => { @@ -1308,7 +1315,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 +2180,7 @@ fn apply_exact_method_contract( } RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} + RawExactMethodContractKind::DataObjectSetData => {} RawExactMethodContractKind::FlagSelectedString => { let buffer = contract.buffer_param_index; let capacity = contract.capacity_param_index; @@ -2315,6 +2326,14 @@ 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", "SetData") => ( + RawExactMethodContractKind::DataObjectSetData, + 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.Graphics.Dxgi", "IDXGIObject", "GetPrivateData") => ( RawExactMethodContractKind::UnsafePrivateData, 2, @@ -2382,7 +2401,7 @@ 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", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", "IContextMenu" => "Windows.Win32.UI.Shell", "IMalloc" => "Windows.Win32.System.Com", @@ -2401,6 +2420,7 @@ fn registered_exact_method_contract( "IStorage" => "IStorage", "IContextMenu" => "IContextMenu", "IMalloc" => "IMalloc", + "IDataObject" => "IDataObject", _ => unreachable!("matched exact method interface"), }, declaring_iid: match kind { @@ -2426,6 +2446,7 @@ fn registered_exact_method_contract( RawExactMethodContractKind::FlagSelectedString => { "000214e4-0000-0000-c000-000000000046" } + RawExactMethodContractKind::DataObjectSetData => "0000010e-0000-0000-c000-000000000046", }, method_name: match kind { RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", @@ -2441,6 +2462,7 @@ fn registered_exact_method_contract( _ => unreachable!("matched exact IMalloc method"), }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", + RawExactMethodContractKind::DataObjectSetData => "SetData", }, vtable_index: match (interface, method) { ("IMFAttributes", "GetBlob") => 15, @@ -2459,6 +2481,7 @@ fn registered_exact_method_contract( ("IMalloc", "GetSize") => 6, ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, + ("IDataObject", "SetData") => 7, _ => unreachable!("matched exact method identity"), }, buffer_param_index: buffer, @@ -2468,6 +2491,10 @@ fn registered_exact_method_contract( .then_some(1), reserved_null_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) .then_some(2), + ownership_transfer_param_index: (kind == RawExactMethodContractKind::DataObjectSetData) + .then_some(2), + source_fingerprint: (kind == RawExactMethodContractKind::DataObjectSetData) + .then_some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1"), citation, reason, }) @@ -2603,6 +2630,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 +2780,56 @@ pub(crate) fn validate_exact_method_contract( && raw_u32_scalar(&raw.params[capacity], RawParamDirection::In, false) && raw_hresult(&raw.return_type) } + RawExactMethodContractKind::DataObjectSetData => { + 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) + } }; let indices_valid = match contract.kind { RawExactMethodContractKind::FixedCapacityBytes @@ -2761,6 +2852,13 @@ pub(crate) fn validate_exact_method_contract( .is_some_and(|index| index < raw.params.len()) } RawExactMethodContractKind::Malloc => true, + RawExactMethodContractKind::DataObjectSetData => { + 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() + } }; if !valid_shape || raw.semantic_hresult.is_some() @@ -4543,6 +4641,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 +4964,40 @@ 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 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..426e3767 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -482,6 +482,7 @@ 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.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", @@ -1139,7 +1140,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(), 496); 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..903cecd0 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2126,6 +2126,70 @@ 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::DataObjectSetData + ); + 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)") + ); + + 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 high_value_exact_contracts_generate_complete_safe_interfaces() { if !win32_available() { From 4b8838970fa78893770e42030efd79610f890713 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 4 Sep 2026 21:56:46 +0800 Subject: [PATCH 3/8] Correct HGLOBAL support status Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 30092ee1..3fc60686 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -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. | From 54cf47ce14cc0bb39e9cf08c03e7ecc2064d224b Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 4 Sep 2026 21:58:02 +0800 Subject: [PATCH 4/8] Add safe variable-length audio formats Model WAVEFORMATEX and WAVEFORMATEXTENSIBLE as validated COM values, project IAudioClient format negotiation with exact conditional ownership, and retain generated unsafe coverage through a WinML fixture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 37 +- README.md | 9 +- .../generated-unsafe-companion.e2e.ts | 187 ++++--- bindings/js/__test__/index.spec.ts | 34 +- bindings/js/scripts/generate-entrypoints.mjs | 1 + bindings/js/src/com.rs | 145 ++++++ .../js/src/generated_unsafe_test_hooks.rs | 308 +++++++++++- bindings/js/src/lib.rs | 11 + crates/dynwinrt/src/call.rs | 46 ++ crates/dynwinrt/src/com.rs | 456 +++++++++++++++++- crates/dynwinrt/src/native_call.rs | 58 ++- .../classic-com-contract-evidence-registry.md | 35 +- .../classic-com-generated-unsafe.md | 58 +-- docs/architecture/classic-com-raw-unsafe.md | 9 +- docs/architecture/classic-com-support.md | 26 +- docs/guides/windows/classic-com-usage.md | 82 ++-- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 82 ++-- .../classic-com-capability-summary.json | 152 ++++-- .../classic-com-interface-support.csv | 10 +- .../src/codegen/com/capability.rs | 45 +- .../src/codegen/com/generated_unsafe.rs | 8 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 9 +- .../src/codegen/com/javascript/render.rs | 93 ++++ .../src/codegen/com/javascript/types.rs | 6 + .../src/codegen/com/model/abi.rs | 1 + .../src/codegen/com/model/metadata.rs | 65 ++- .../src/codegen/com/model/method.rs | 5 + .../src/codegen/com/model/ownership.rs | 3 + .../src/codegen/com/project/mod.rs | 70 +++ tools/dynwinrt-codegen/src/com_metadata.rs | 203 +++++++- .../dynwinrt-codegen/src/contract_registry.rs | 8 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 174 ++++--- 32 files changed, 2033 insertions(+), 403 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a20d3899..88b3bd32 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 5692) { + if ($result.complete_interfaces -lt 5697) { throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" } if ($result.coverage_percent -lt 70.0) { @@ -107,21 +107,21 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $result = Get-Content (Join-Path $output 'classic-com-capability-summary.json') -Raw | ConvertFrom-Json - if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5692) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5697) { throw "Classic COM safe totals changed in capability census" } $support = Import-Csv (Join-Path $output 'classic-com-interface-support.csv') if ( @($support).Count -ne 7929 -or - @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5692 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2237 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5697 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2232 ) { throw "Classic COM compact interface support index changed" } $expected = @{ - x64 = @(412, 1437, 388) - i686 = @(411, 1414, 412) - arm64 = @(412, 1437, 388) + x64 = @(412, 1432, 388) + i686 = @(411, 1409, 412) + arm64 = @(412, 1432, 388) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -134,16 +134,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5692 -or - $result.safeEvidence.standardDerived -ne 5336 -or - $result.safeEvidence.exactRegistryDependent -ne 356 -or - $result.safeEvidence.metadataFactOccurrences -ne 5976 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26119 -or - $result.safeEvidence.registeredExactEntries -ne 496 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 496 -or - $result.safeEvidence.safeConsumedExactEntries -ne 405 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 656 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 405 + $result.safeEvidence.safeComplete -ne 5697 -or + $result.safeEvidence.standardDerived -ne 5338 -or + $result.safeEvidence.exactRegistryDependent -ne 359 -or + $result.safeEvidence.metadataFactOccurrences -ne 5982 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26134 -or + $result.safeEvidence.registeredExactEntries -ne 499 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 499 -or + $result.safeEvidence.safeConsumedExactEntries -ne 408 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 663 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 411 ) { throw "Classic COM safe evidence dependency census changed" } @@ -151,7 +151,8 @@ jobs: if ( @($statuses | Where-Object { -not $_.registered -or -not $_.metadataMatched }).Count -ne 0 -or @($statuses | Where-Object { $_.familyId -eq 'windows.borrowed-hwnd-output.v1' }).Count -ne 22 -or - @($statuses | Where-Object { $_.familyId -eq 'com.enumerator-next-exception.v1' }).Count -ne 73 + @($statuses | Where-Object { $_.familyId -eq 'com.enumerator-next-exception.v1' }).Count -ne 73 -or + @($statuses | Where-Object { $_.familyId -eq 'audio.conditional-output.v1' }).Count -ne 1 ) { throw "Classic COM exact registry entry validation changed" } diff --git a/README.md b/README.md index 54aa8ff3..92734251 100644 --- a/README.md +++ b/README.md @@ -142,12 +142,13 @@ 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,692 of 7,929 -eligible interfaces (71.79%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,697 of 7,929 +eligible interfaces (71.85%)** with complete safe code generation. Supported contracts include generated coclass activation and QueryInterface views, managed interface ownership, native POD layouts, typed counted buffers, BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, the -target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, and +target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, +variable-length WAVEFORMATEX audio formats with exact CoTaskMem outputs, and synchronous JavaScript implementations of fully supported callback interfaces. Seventeen stock-Windows Node E2E runners exercise representative Shell, Automation, stream, callback, HWND, and WinRT interop scenarios. @@ -155,7 +156,7 @@ 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, non-HGLOBAL/device-specific clipboard and +common graphics, advanced audio, WMI, non-HGLOBAL/device-specific clipboard and drag-and-drop, derived Automation, union, BYREF/InOut, and output-ownership shapes. diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 6e1a4661..f97173a8 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -6,7 +6,7 @@ import { spawnSync } from 'node:child_process' import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs' import { basename, dirname, join, resolve } from 'node:path' -test.serial('generated safe WMI and unsafe Audio companions preserve exact contracts', (t) => { +test.serial('generated safe COM and unsafe WinML companions preserve exact contracts', (t) => { const winmd = process.env.DYNWINRT_WIN32_WINMD t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required') const packageRoot = resolve(process.cwd()) @@ -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.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject', + 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext', '--output', output, ] @@ -90,7 +90,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr const wbemBase = join(output, 'com', 'windows', 'win32', 'system', 'wmi', 'IWbemServices') const dataObjectBase = join(output, 'com', 'windows', 'win32', 'system', 'com', 'IDataObject') const thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') - const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') + const audioBase = join(output, 'com', 'windows', 'win32', 'media', 'audio', 'IAudioClient') + const evaluationBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'ai', 'machine-learning', 'win-ml', 'IWinMLEvaluationContextUnsafe') const runner = join(output, 'generated-companion-runner.cjs') writeFileSync( runner, @@ -99,7 +100,7 @@ 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 { DynComAudioFormat, 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', @@ -107,6 +108,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr `const dataObject = require(${JSON.stringify(`${dataObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, + `const evaluation = require(${JSON.stringify(`${evaluationBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, `const cjsBarrel = require(${JSON.stringify(join(output, 'com', 'unsafe', 'index.js'))})`, 'function finishTransaction(records) {', @@ -126,13 +128,17 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ` const esmDataObject = await import(pathToFileURL(${JSON.stringify(`${dataObjectBase}.js`)}).href)`, ` const esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, + ` const esmEvaluation = await import(pathToFileURL(${JSON.stringify(`${evaluationBase}.js`)}).href)`, ` 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 thumbnail.IThumbnailProvider, 'function')", - " assert.equal(typeof audio.IAudioClientUnsafe, 'function')", - ' assert.equal(esmAudio.IAudioClientUnsafe, audio.IAudioClientUnsafe)', + " assert.equal(typeof audio.IAudioClient, 'function')", + " assert.equal(typeof evaluation.IWinMLEvaluationContextUnsafe, 'function')", + ' assert.equal(esmAudio.IAudioClient, audio.IAudioClient)', + ' assert.equal(esmEvaluation.IWinMLEvaluationContextUnsafe, evaluation.IWinMLEvaluationContextUnsafe)', + ' assert.equal(safeBarrel.IAudioClient, audio.IAudioClient)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(safeBarrel.IDataObject, dataObject.IDataObject)', ' assert.equal(safeBarrel.IThumbnailProvider, thumbnail.IThumbnailProvider)', @@ -281,9 +287,49 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' dataObjectWrapper?.release()', ' dataObjectFake?.release()', ' }', - ' const createAudio = runtime.createGeneratedAudioClientFake', - ' const audioStats = runtime.generatedAudioClientStats', - ' const setServiceMode = runtime.setGeneratedAudioClientGetServiceMode', + ' const createSafeAudio = runtime.createGeneratedAudioClientFake', + ' const safeAudioStats = runtime.generatedAudioClientStats', + ' const setFormatSupportMode = runtime.setGeneratedAudioClientFormatSupportMode', + ' const setSafeAudioServiceMode = runtime.setGeneratedAudioClientGetServiceMode', + ' let safeAudioFake = createSafeAudio()', + ' let safeAudioWrapper', + ' try {', + ' safeAudioWrapper = audio.IAudioClient._fromNative(safeAudioFake)', + ' const pcm = DynComAudioFormat.pcm(2, 48000, 16)', + ' safeAudioWrapper.initialize(0, 0, 0n, 0n, pcm, null)', + ' setFormatSupportMode(0)', + ' assert.deepEqual(safeAudioWrapper.isFormatSupported(0, pcm), [0, null])', + ' setFormatSupportMode(1)', + ' const [closestStatus, closestFormat] = safeAudioWrapper.isFormatSupported(0, pcm)', + ' assert.equal(closestStatus, 1)', + ' assert.equal(closestFormat.channels, 1)', + ' assert.equal(closestFormat.samplesPerSecond, 44100)', + " assert.throws(() => safeAudioWrapper.isFormatSupported(1, pcm), /native call failed|HRESULT|0x88890008/i)", + ' setFormatSupportMode(-1)', + " assert.throws(() => safeAudioWrapper.isFormatSupported(0, pcm), /native call failed|HRESULT|0x80004005/i)", + ' const mix = safeAudioWrapper.getMixFormat()', + ' assert.equal(mix.channels, 2)', + ' assert.equal(mix.samplesPerSecond, 48000)', + ' setSafeAudioServiceMode(0)', + " const service = safeAudioWrapper.getService('1cb9ad4c-dbfa-4c32-b178-c2f568a703b2')", + ' service.release()', + ' assert.equal(safeAudioStats().initializeCalls, 1)', + ' assert.equal(safeAudioStats().isFormatSupportedCalls, 4)', + ' assert.equal(safeAudioStats().getMixFormatCalls, 1)', + ' assert.equal(safeAudioStats().getServiceCalls, 1)', + ' assert.equal(safeAudioStats().currentRefCount, 2)', + ' safeAudioWrapper.release()', + ' safeAudioFake.release()', + ' assert.equal(safeAudioStats().currentRefCount, 0)', + ' safeAudioWrapper = undefined', + ' safeAudioFake = undefined', + ' } finally {', + ' safeAudioWrapper?.release()', + ' safeAudioFake?.release()', + ' }', + ' const createAudio = runtime.createGeneratedEvaluationContextFake', + ' const audioStats = runtime.generatedEvaluationContextStats', + ' const setServiceMode = runtime.setGeneratedEvaluationContextOutputMode', ' const createCleanupResource = runtime.createGeneratedNativeCleanupResource', " assert.equal(typeof createAudio, 'function')", " assert.equal(typeof createCleanupResource, 'function')", @@ -297,7 +343,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' let audioFake = createAudio()', ' let audioWrapper', ' try {', - ' audioWrapper = audio.IAudioClientUnsafe.from(audioFake)', + ' audioWrapper = evaluation.IWinMLEvaluationContextUnsafe.from(audioFake)', ' const format = DynComRawMemory.allocate(22, 2)', ' format.writeU16(0, 1)', " const inPointeeContract = Object.freeze({ direction: 'in', nullable: false, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", @@ -306,11 +352,11 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " const unknownWritablePointeeContract = Object.freeze({ direction: 'inout', nullable: false, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", " const nullableWritablePointeeContract = Object.freeze({ direction: 'out', nullable: true, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", " assert.throws(() => UnsafePointerOutput.comOwned({}), /WinGUID|convert|class/i)", - " assert.throws(() => UnsafePointerOutput.comOwned(new Proxy(audio.IAudioClientUnsafe.iid, {})), /WinGUID|convert|class/i)", + " assert.throws(() => UnsafePointerOutput.comOwned(new Proxy(evaluation.IWinMLEvaluationContextUnsafe.iid, {})), /WinGUID|convert|class/i)", ' const invalidReplacementOwner = DynComRawOwnedComPointer.addRef(audioFake)', " assert.throws(() => UnsafeInterfaceReplacement.unchanged(invalidReplacementOwner, {}), /WinGUID|convert|class/i)", ' invalidReplacementOwner.release()', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const hardened = UnsafePointerOutput.coTaskMem()', " const opaqueRecord = __prepareStrategy(UnsafePointee.required(format), 'UnsafePointee', 'opaque', inPointeeContract)", ' assert.equal(Object.isFrozen(opaqueRecord), true)', @@ -327,20 +373,20 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.throws(() => { UnsafePointerOutput.prototype.prepare = () => null }, TypeError)', ' class ForgedOutput extends UnsafePointerOutput {}', ' assert.equal(Object.getPrototypeOf(ForgedOutput.coTaskMem()), UnsafePointerOutput.prototype)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), new Proxy(hardened, {})), /exact generated UnsafePointerOutput/)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), {}), /exact generated UnsafePointerOutput/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(DynComRawPointer.null()), UnsafePointerOutput.coTaskMem()), /non-null/)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(null), UnsafePointerOutput.coTaskMem()), /non-null/)', + ' assert.throws(() => audioWrapper.getValueByName(format, new Proxy(hardened, {})), /exact generated UnsafePointerOutput/)', + ' assert.throws(() => audioWrapper.getValueByName(format, {}), /exact generated UnsafePointerOutput/)', + ' assert.equal(audioStats().getValueCalls, 0)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(DynComRawPointer.null())), /non-null/)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(null)), /non-null/)', ' const releasedFormat = DynComRawMemory.allocate(22, 2)', ' releasedFormat.release()', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(releasedFormat), UnsafePointerOutput.coTaskMem()), /released/)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(releasedFormat)), /released/)', ' const releasedSlot = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const releasedOutput = UnsafePointerOutput.coTaskMem(releasedSlot)', ' releasedSlot.release()', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), releasedOutput), /released/)', + ' assert.throws(() => audioWrapper.getValueByName(format, releasedOutput), /released/)', ' assert.throws(() => DynComRawMemory.fromUnsafeAddress(0n, 8, 1), /non-null/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const spanBase = DynComRawMemory.allocate(DynComRaw.pointerSize() * 2, DynComRaw.pointerSize())', ' const spanA = DynComRawMemory.fromUnsafePointer(spanBase.pointer(), DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const spanB = DynComRawMemory.fromUnsafePointer(spanBase.pointer(Math.floor(DynComRaw.pointerSize() / 2)), DynComRaw.pointerSize(), 1)', @@ -356,7 +402,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " const partialExactSpan = __prepareStrategy(UnsafeCountedBuffer.required(spanB), 'UnsafeCountedBuffer', 'partialExactSpan')", ' assert.throws(() => __validateStrategySpans([exactSpan, partialExactSpan]), /overlap/)', ' for (const [kind, factory] of [', - " ['UnsafePointerOutput', slot => UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid, slot)],", + " ['UnsafePointerOutput', slot => UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid, slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.coTaskMem(slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.bstr(slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.localAlloc(slot)],", @@ -406,7 +452,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.ok(__strategyArgument(__prepareStrategy(UnsafePointee.nullable(DynComRawPointer.null()), 'UnsafePointee', 'nullableRawWritablePointee', nullableWritablePointeeContract)))", ' const replacementOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const replacementSlot = DynComRawMemory.fromUnsafePointer(spanBase.pointer(), DynComRaw.pointerSize(), 1)', - " const replacementRecord = __prepareStrategy(UnsafeInterfaceReplacement.unchanged(replacementOwner, audio.IAudioClientUnsafe.iid, replacementSlot), 'UnsafeInterfaceReplacement', 'replacementSpan')", + " const replacementRecord = __prepareStrategy(UnsafeInterfaceReplacement.unchanged(replacementOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, replacementSlot), 'UnsafeInterfaceReplacement', 'replacementSpan')", ' assert.throws(() => __validateStrategySpans([exactSpan, replacementRecord]), /overlap/)', " const replacementOutput = __prepareStrategy(UnsafePointerOutput.rawResponsibility(replacementSlot), 'UnsafePointerOutput', 'replacementOutput')", ' assert.throws(() => __validateStrategySpans([replacementRecord, replacementOutput]), /overlap/)', @@ -429,76 +475,74 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(finishError.unsafeOutputs.length, 3)', ' for (const slot of finishSlots) slot.release()', ' }', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const closest = UnsafePointerOutput.coTaskMem()', - ' const formatResult = audioWrapper.isFormatSupported(1, UnsafePointee.required(format), closest)', - ' assert.equal(formatResult[0], 1)', - ' assert.equal(audioStats().isFormatSupportedCalls, 1)', - ' assert.equal(audioStats().lastShareMode, 1)', - ' assert.equal(audioStats().lastFormatTag, 1)', - ' const closestOwner = formatResult[1]', + ' setServiceMode(6)', + ' const closestOwner = audioWrapper.getValueByName(format, closest)', + ' assert.equal(audioStats().getValueCalls, 1)', ' const closestView = closestOwner.view(16, 4)', ' assert.equal(closestView.readU32(0), 0xaabbccdd)', ' closestView.release()', ' assert.equal(__testRunOwnedFinalizer(closestOwner), true)', ' assert.equal(__testRunOwnedFinalizer(closestOwner), true)', ' assert.throws(() => closestOwner.view(16, 4), /released/)', - ' assert.throws(() => audioWrapper.isFormatSupported(2, UnsafePointee.required(format), UnsafePointerOutput.coTaskMem()), /native call failed|HRESULT|0x80004005/i)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), closest), /finished/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), UnsafePointee.required(format)), /UnsafePointerOutput/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', + ' setServiceMode(-6)', + ' assert.throws(() => audioWrapper.getValueByName(format, UnsafePointerOutput.coTaskMem()), /native call failed|HRESULT|0x80004005/i)', + ' assert.equal(audioStats().getValueCalls, 2)', + ' assert.throws(() => audioWrapper.getValueByName(format, closest), /finished/)', + ' assert.equal(audioStats().getValueCalls, 2)', + ' assert.throws(() => audioWrapper.getValueByName(format, UnsafePointee.required(format)), /UnsafePointerOutput/)', + ' assert.equal(audioStats().getValueCalls, 2)', ' const iidStorage = DynComRawMemory.allocate(16, 4)', ' setServiceMode(1)', ' const beforeFailureRefs = audioStats().currentRefCount', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid)), /native call failed|HRESULT|0x80004005/i)', - ' assert.equal(audioStats().getServiceCalls, 1)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid)), /native call failed|HRESULT|0x80004005/i)', + ' assert.equal(audioStats().getValueCalls, 3)', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' const rawFailure = UnsafePointerOutput.rawResponsibility()', ' let rawFailureError', - ' try { audioWrapper.getService(iidStorage, rawFailure) } catch (error) { rawFailureError = error }', + ' try { audioWrapper.getValueByName(iidStorage, rawFailure) } catch (error) { rawFailureError = error }', ' assert.equal(rawFailureError.unsafeOutputs.length, 1)', ' const dirtyPointer = rawFailure.takeFailurePointer()', ' assert.equal(dirtyPointer.address, rawFailureError.unsafeOutputs[0].pointer.address)', ' assert.throws(() => rawFailure.takeFailurePointer(), /No raw failure pointer/)', - ' DynComRawOwnedComPointer.assumeTransferred(dirtyPointer, audio.IAudioClientUnsafe.iid).release()', + ' DynComRawOwnedComPointer.assumeTransferred(dirtyPointer, evaluation.IWinMLEvaluationContextUnsafe.iid).release()', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' setServiceMode(-2)', ' const nullFailure = UnsafePointerOutput.rawResponsibility()', ' let nullFailureError', - ' try { audioWrapper.getService(iidStorage, nullFailure) } catch (error) { nullFailureError = error }', + ' try { audioWrapper.getValueByName(iidStorage, nullFailure) } catch (error) { nullFailureError = error }', ' assert.equal(nullFailureError.unsafeOutputs[0].pointer.isNull, true)', ' assert.equal(nullFailure.takeFailurePointer().isNull, true)', ' assert.throws(() => nullFailure.takeFailurePointer(), /No raw failure pointer/)', ' setServiceMode(0)', - ' const managedService = audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid))', + ' const managedService = audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid))', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs + 1)', ' managedService.release()', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', " const wrongIid = WinGuid.parse('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')", - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(wrongIid)), /interface|0x80004002/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(wrongIid)), /interface|0x80004002/i)', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' setServiceMode(2)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid)), /Required pointer output was null/)', - ' const nullable = audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid, null, true))', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid)), /Required pointer output was null/)', + ' const nullable = audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid, null, true))', ' assert.equal(nullable, null)', ' setServiceMode(3)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.bstr())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.bstr())), true)', ' setServiceMode(-3)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.bstr()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.bstr()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(4)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.localAlloc())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.localAlloc())), true)', ' setServiceMode(-4)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.localAlloc()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.localAlloc()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(5)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.globalAlloc())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.globalAlloc())), true)', ' setServiceMode(-5)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.globalAlloc()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.globalAlloc()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(2)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.borrowed(null, true)), null)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.unclassified(null, true)), null)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.rawResponsibility(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.borrowed(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.unclassified(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.rawResponsibility(null, true)), null)', ' const rawSlot = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const handle = UnsafeHandleOutput.rawResponsibility(rawSlot)', " const handleRecord = __prepareStrategy(handle, 'UnsafeHandleOutput', 'handle')", @@ -525,7 +569,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' nativeSlot.release()', ' }', ' const owner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const unchanged = UnsafeInterfaceReplacement.unchanged(owner, audio.IAudioClientUnsafe.iid)', + ' const unchanged = UnsafeInterfaceReplacement.unchanged(owner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const unchangedRecord = __prepareStrategy(unchanged, 'UnsafeInterfaceReplacement', 'unchanged')", ' __activateStrategies([unchangedRecord])', ' const unchangedResult = __finishStrategy(unchangedRecord)', @@ -534,7 +578,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' unchangedResult.release()', " assert.throws(() => __prepareStrategy(unchanged, 'UnsafeInterfaceReplacement', 'unchanged'), /finished/)", ' const preservesOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const preserves = UnsafeInterfaceReplacement.preservesOld(preservesOwner, audio.IAudioClientUnsafe.iid)', + ' const preserves = UnsafeInterfaceReplacement.preservesOld(preservesOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const preservesRecord = __prepareStrategy(preserves, 'UnsafeInterfaceReplacement', 'preserves')", ' __activateStrategies([preservesRecord])', ' const preservesResult = __finishStrategy(preservesRecord)', @@ -542,7 +586,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(preservesResult.current, preservesOwner)', ' preservesResult.release()', ' const reentrantOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const reentrant = UnsafeInterfaceReplacement.preservesOld(reentrantOwner, audio.IAudioClientUnsafe.iid)', + ' const reentrant = UnsafeInterfaceReplacement.preservesOld(reentrantOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const reentrantRecord = __prepareStrategy(reentrant, 'UnsafeInterfaceReplacement', 'reentrant')", ' __activateStrategies([reentrantRecord])', ' reentrantOwner.release()', @@ -552,7 +596,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(reentrantResult.current, reentrantResult.previous)', ' reentrantResult.release()', ' const consumesOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const consumes = UnsafeInterfaceReplacement.consumesOld(consumesOwner, audio.IAudioClientUnsafe.iid)', + ' const consumes = UnsafeInterfaceReplacement.consumesOld(consumesOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const consumesRecord = __prepareStrategy(consumes, 'UnsafeInterfaceReplacement', 'consumes')", ' __activateStrategies([consumesRecord])', ' const consumesResult = __finishStrategy(consumesRecord)', @@ -560,7 +604,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.ok(consumesResult.current)', ' consumesResult.release()', ' const preDispatchOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const preDispatchReplacement = UnsafeInterfaceReplacement.consumesOld(preDispatchOwner, audio.IAudioClientUnsafe.iid)', + ' const preDispatchReplacement = UnsafeInterfaceReplacement.consumesOld(preDispatchOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const preDispatchRecord = __prepareStrategy(preDispatchReplacement, 'UnsafeInterfaceReplacement', 'preDispatch')", ' __activateStrategies([preDispatchRecord])', ' __markDispatchEntered([preDispatchRecord], DynComRaw.__createDispatchState())', @@ -570,12 +614,12 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' const preDispatchResult = __finishStrategy(preDispatchRetry)', ' preDispatchResult.release()', " const replacementFactories = [UnsafeInterfaceReplacement.consumesOld, UnsafeInterfaceReplacement.preservesOld, UnsafeInterfaceReplacement.unchanged]", - ' const aliasCallCount = audioStats().isFormatSupportedCalls', + ' const aliasCallCount = audioStats().getValueCalls', ' for (let first = 0; first < replacementFactories.length; first++) {', ' for (let second = first; second < replacementFactories.length; second++) {', ' const sharedOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const slots = [0, 1].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const records = [first, second].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, audio.IAudioClientUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `pair${first}${second}${index}`))", + " const records = [first, second].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `pair${first}${second}${index}`))", ' assert.throws(() => __validateStrategySpans(records), /owner is used by multiple/)', ' assert.ok(sharedOwner.address > 0n)', ' sharedOwner.release()', @@ -587,7 +631,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' for (let third = second; third < replacementFactories.length; third++) {', ' const sharedOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const slots = [0, 1, 2].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const records = [first, second, third].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, audio.IAudioClientUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `triple${first}${second}${third}${index}`))", + " const records = [first, second, third].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `triple${first}${second}${third}${index}`))", ' assert.throws(() => __validateStrategySpans(records), /owner is used by multiple/)', ' assert.ok(sharedOwner.address > 0n)', ' sharedOwner.release()', @@ -597,19 +641,19 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' }', ' const independentOwners = [0, 1, 2].map(() => DynComRawOwnedComPointer.addRef(audioFake))', ' const independentSlots = [0, 1, 2].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const independentRecords = replacementFactories.map((factory, index) => __prepareStrategy(factory(independentOwners[index], audio.IAudioClientUnsafe.iid, independentSlots[index]), 'UnsafeInterfaceReplacement', `independent${index}`))", + " const independentRecords = replacementFactories.map((factory, index) => __prepareStrategy(factory(independentOwners[index], evaluation.IWinMLEvaluationContextUnsafe.iid, independentSlots[index]), 'UnsafeInterfaceReplacement', `independent${index}`))", ' __validateStrategySpans(independentRecords)', ' __activateStrategies(independentRecords)', ' const independentResults = independentRecords.map(record => __finishStrategy(record))', ' for (const result of independentResults) result.release()', ' for (const slot of independentSlots) slot.release()', - ' assert.equal(audioStats().isFormatSupportedCalls, aliasCallCount)', + ' assert.equal(audioStats().getValueCalls, aliasCallCount)', ' const rollbackOwnerA = DynComRawOwnedComPointer.addRef(audioFake)', ' const rollbackOwnerB = DynComRawOwnedComPointer.addRef(audioFake)', ' const rollbackSlotA = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const rollbackSlotB = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', - ' const rollbackA = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerA, audio.IAudioClientUnsafe.iid, rollbackSlotA)', - ' const rollbackB = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerB, audio.IAudioClientUnsafe.iid, rollbackSlotB)', + ' const rollbackA = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerA, evaluation.IWinMLEvaluationContextUnsafe.iid, rollbackSlotA)', + ' const rollbackB = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerB, evaluation.IWinMLEvaluationContextUnsafe.iid, rollbackSlotB)', " const rollbackRecordA = __prepareStrategy(rollbackA, 'UnsafeInterfaceReplacement', 'rollbackA')", " const rollbackRecordB = __prepareStrategy(rollbackB, 'UnsafeInterfaceReplacement', 'rollbackB')", ' __validateStrategySpans([rollbackRecordA, rollbackRecordB])', @@ -679,12 +723,13 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr "import { IWbemServices } from './com/windows/win32/system/wmi/IWbemServices.js'", "import { IDataObject } from './com/windows/win32/system/com/IDataObject.js'", "import { IThumbnailProvider } from './com/windows/win32/ui/shell/IThumbnailProvider.js'", - "import { IAudioClientUnsafe } from './com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js'", + "import { IAudioClient } from './com/windows/win32/media/audio/IAudioClient.js'", + "import { IWinMLEvaluationContextUnsafe } from './com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.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'", + "import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } from '@microsoft/dynwinrt/com'", 'declare const native: DynWinRtValue', 'declare const storage: DynComRawMemory', 'declare const thumbnails: IThumbnailProvider', @@ -704,13 +749,17 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '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 audio = IAudioClientUnsafe.from(native)', + 'const audio = IAudioClient._fromNative(native)', + 'audio.isFormatSupported(0, DynComAudioFormat.pcm(2, 48_000, 16))', + 'const unsafeEvaluation = IWinMLEvaluationContextUnsafe.from(native)', '// @ts-expect-error strategy result types are invariant', 'const wrongOutput: UnsafePointerOutput = UnsafePointerOutput.coTaskMem()', 'const ownedOutput: UnsafePointerOutput = UnsafePointerOutput.coTaskMem()', 'void wrongOutput', 'void ownedOutput', - 'audio.isFormatSupported(0, UnsafePointee.required(storage), UnsafePointerOutput.coTaskMem())', + 'unsafeEvaluation.bindValue(UnsafePointee.required(storage))', + 'unsafeEvaluation.getValueByName(storage, UnsafePointerOutput.coTaskMem())', + 'unsafeEvaluation.release()', 'audio.release()', 'barrel.release()', 'direct.release()', diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index bc724f88..848ef47f 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -23,7 +23,7 @@ import { unboxObject, } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' -import { DynComFormatEtc, DynComStgMedium } from '../dist/com.js' +import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } from '../dist/com.js' import * as comRuntime from '../dist/com.js' import { DynCom, @@ -149,6 +149,7 @@ test('package facades exactly partition native exports', (t) => { const safeComNames = new Set([ 'DynComDispatchParams', 'DynComAllocation', + 'DynComAudioFormat', 'DynComExcepInfo', 'DynComFormatEtc', 'DynComNativeStruct', @@ -231,6 +232,37 @@ test('FORMATETC and STGMEDIUM expose a closed HGLOBAL semantic subset', (t) => { t.throws(() => DynComStgMedium.hglobal(Buffer.alloc(0)), { message: /at least one byte/ }) }) +test('WAVEFORMATEX values preserve validated variable-length audio formats', (t) => { + const pcm = DynComAudioFormat.pcm(2, 48_000, 16) + t.is(pcm.formatTag, 1) + t.is(pcm.channels, 2) + t.is(pcm.samplesPerSecond, 48_000) + t.is(pcm.averageBytesPerSecond, 192_000) + t.is(pcm.blockAlign, 4) + t.is(pcm.bitsPerSample, 16) + t.deepEqual(pcm.extraData, Buffer.alloc(0)) + t.is(pcm.toBuffer().length, 18) + t.deepEqual(DynComAudioFormat.fromBuffer(pcm.toBuffer()).toBuffer(), pcm.toBuffer()) + + const extensible = DynComAudioFormat.waveFormatEx( + 0xfffe, + 2, + 48_000, + 192_000, + 4, + 16, + Buffer.alloc(22), + ) + t.is(extensible.formatTag, 0xfffe) + t.is(extensible.extraData.length, 22) + t.throws(() => DynComAudioFormat.pcm(2, 48_000, 12), { message: /multiple of eight/ }) + t.throws(() => DynComAudioFormat.fromBuffer(Buffer.alloc(17)), { message: /18-byte header/ }) + t.throws( + () => DynComAudioFormat.waveFormatEx(0xfffe, 2, 48_000, 192_000, 4, 16, Buffer.alloc(21)), + { message: /22 extension bytes/ }, + ) +}) + 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 6ec952e3..b73dedeb 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -19,6 +19,7 @@ if (nativeExports.length === 0) { const comExports = new Set([ 'DynComDispatchParams', 'DynComAllocation', + 'DynComAudioFormat', 'DynComExcepInfo', 'DynComFormatEtc', 'DynComNativeStruct', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 5e143070..47b687d8 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -42,6 +42,7 @@ enum AutomationValueKind { StatStg(dynwinrt::com::StatStgValue), FormatEtc(dynwinrt::com::FormatEtcValue), StgMedium(dynwinrt::com::StgMediumValue), + AudioFormat(dynwinrt::com::AudioFormatValue), } pub(super) struct AutomationValue { @@ -62,6 +63,7 @@ impl AutomationValue { dynwinrt::com::Value::StatStg(value) => AutomationValueKind::StatStg(value), dynwinrt::com::Value::FormatEtc(value) => AutomationValueKind::FormatEtc(value), dynwinrt::com::Value::StgMedium(value) => AutomationValueKind::StgMedium(value), + dynwinrt::com::Value::AudioFormat(value) => AutomationValueKind::AudioFormat(value), _ => unreachable!("AutomationValue requires an automation COM value"), }; Self { @@ -101,6 +103,7 @@ impl AutomationValue { 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()), + AutomationValueKind::AudioFormat(value) => dynwinrt::com::Value::AudioFormat(value.clone()), }) } @@ -181,6 +184,17 @@ impl AutomationValue { } } + pub(super) fn take_audio_format(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::AudioFormat(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not a COM WAVEFORMATEX")) + } + } + } + pub(super) fn leak_for_shutdown(&mut self) { if let Some(value) = self.value.take() { std::mem::forget(value); @@ -3165,6 +3179,103 @@ impl DynComStgMedium { } } +#[napi] +pub struct DynComAudioFormat { + value: dynwinrt::com::AudioFormatValue, +} + +#[napi] +impl DynComAudioFormat { + #[napi(factory)] + pub fn pcm(channels: u32, samples_per_second: u32, bits_per_sample: u32) -> napi::Result { + let channels = + u16::try_from(channels).map_err(|_| napi::Error::from_reason("channels must fit in u16"))?; + let bits_per_sample = u16::try_from(bits_per_sample) + .map_err(|_| napi::Error::from_reason("bitsPerSample must fit in u16"))?; + dynwinrt::com::AudioFormatValue::pcm(channels, samples_per_second, bits_per_sample) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(factory)] + pub fn wave_format_ex( + format_tag: u32, + channels: u32, + samples_per_second: u32, + average_bytes_per_second: u32, + block_align: u32, + bits_per_sample: u32, + extra_data: Option, + ) -> napi::Result { + let format_tag = u16::try_from(format_tag) + .map_err(|_| napi::Error::from_reason("formatTag must fit in u16"))?; + let channels = + u16::try_from(channels).map_err(|_| napi::Error::from_reason("channels must fit in u16"))?; + let block_align = u16::try_from(block_align) + .map_err(|_| napi::Error::from_reason("blockAlign must fit in u16"))?; + let bits_per_sample = u16::try_from(bits_per_sample) + .map_err(|_| napi::Error::from_reason("bitsPerSample must fit in u16"))?; + dynwinrt::com::AudioFormatValue::wave_format_ex( + format_tag, + channels, + samples_per_second, + average_bytes_per_second, + block_align, + bits_per_sample, + extra_data.map_or_else(Vec::new, |bytes| bytes.to_vec()), + ) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(factory)] + pub fn from_buffer(bytes: Buffer) -> napi::Result { + dynwinrt::com::AudioFormatValue::from_wave_format_ex(bytes.to_vec()) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(getter)] + pub fn format_tag(&self) -> u32 { + u32::from(self.value.format_tag()) + } + + #[napi(getter)] + pub fn channels(&self) -> u32 { + u32::from(self.value.channels()) + } + + #[napi(getter)] + pub fn samples_per_second(&self) -> u32 { + self.value.samples_per_second() + } + + #[napi(getter)] + pub fn average_bytes_per_second(&self) -> u32 { + self.value.average_bytes_per_second() + } + + #[napi(getter)] + pub fn block_align(&self) -> u32 { + u32::from(self.value.block_align()) + } + + #[napi(getter)] + pub fn bits_per_sample(&self) -> u32 { + u32::from(self.value.bits_per_sample()) + } + + #[napi(getter)] + pub fn extra_data(&self) -> Buffer { + Buffer::from(self.value.extra_data().to_vec()) + } + + #[napi] + pub fn to_buffer(&self) -> Buffer { + Buffer::from(self.value.bytes().to_vec()) + } +} + #[napi] #[derive(Debug)] pub struct DynComOwnedHandle { @@ -4908,6 +5019,11 @@ impl DynCom { DynComType(dynwinrt::com::Type::stg_medium()) } + #[napi] + pub fn audio_format_type() -> DynComType { + DynComType(dynwinrt::com::Type::audio_format()) + } + #[napi] pub fn interface_type(iid: &WinGUID) -> DynComType { DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) @@ -5756,6 +5872,14 @@ impl DynCom { ) } + #[napi] + pub fn audio_format(value: &DynComAudioFormat) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::AudioFormat(value.value.clone()), + dynwinrt::com::PointerOutputKind::None, + ) + } + #[napi] pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { let result = value @@ -5843,6 +5967,27 @@ impl DynCom { Ok(DynComStgMedium { value: result }) } + #[napi] + pub fn take_audio_format(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM WAVEFORMATEX"))? + .take_audio_format()?; + value.5 = None; + Ok(DynComAudioFormat { value: result }) + } + + #[napi] + pub fn take_nullable_audio_format( + value: &mut DynWinRTValue, + ) -> napi::Result> { + if value.5.is_none() && value.0.is_null_object() { + return Ok(None); + } + Self::take_audio_format(value).map(Some) + } + #[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 c704bdc9..8bc2a607 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -19,6 +19,7 @@ const IID_IWBEM_CLASS_OBJECT: GUID = GUID::from_u128(0xdc12a681_737f_11cf_884d_0 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 IID_IWINML_EVALUATION_CONTEXT: GUID = GUID::from_u128(0x95848f9e_583d_4054_af12_916387cd8426); const E_NOINTERFACE: HRESULT = HRESULT(0x80004002u32 as i32); const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); const E_NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); @@ -45,13 +46,20 @@ static LAST_FLAGS: AtomicI32 = AtomicI32::new(0); static CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); static LAST_OUTPUT_ADDRESS: AtomicUsize = AtomicUsize::new(0); static AUDIO_IS_FORMAT_SUPPORTED_CALLS: AtomicU32 = AtomicU32::new(0); +static AUDIO_INITIALIZE_CALLS: AtomicU32 = AtomicU32::new(0); +static AUDIO_GET_MIX_FORMAT_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_GET_SERVICE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_LAST_SHARE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_LAST_FORMAT_TAG: AtomicU32 = AtomicU32::new(0); +static AUDIO_FORMAT_SUPPORT_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_GET_SERVICE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static EVALUATION_BIND_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); +static EVALUATION_GET_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); +static EVALUATION_OUTPUT_MODE: AtomicI32 = AtomicI32::new(0); +static EVALUATION_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); @@ -1052,16 +1060,62 @@ unsafe extern "system" fn audio_release(this: *mut c_void) -> u32 { count } +fn valid_audio_format(format: *const c_void) -> bool { + if format.is_null() { + return false; + } + let bytes = unsafe { std::slice::from_raw_parts(format.cast::(), 18) }; + u16::from_le_bytes([bytes[0], bytes[1]]) != 0 + && u16::from_le_bytes([bytes[2], bytes[3]]) != 0 + && u32::from_le_bytes(bytes[4..8].try_into().unwrap()) != 0 + && u32::from_le_bytes(bytes[8..12].try_into().unwrap()) != 0 + && u16::from_le_bytes([bytes[12], bytes[13]]) != 0 +} + +unsafe fn write_audio_format( + output: *mut *mut c_void, + channels: u16, + samples_per_second: u32, + bits_per_sample: u16, +) -> HRESULT { + if output.is_null() { + return E_POINTER; + } + let block_align = channels * (bits_per_sample / 8); + let average_bytes_per_second = samples_per_second * u32::from(block_align); + let mut bytes = Vec::with_capacity(18); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&channels.to_le_bytes()); + bytes.extend_from_slice(&samples_per_second.to_le_bytes()); + bytes.extend_from_slice(&average_bytes_per_second.to_le_bytes()); + bytes.extend_from_slice(&block_align.to_le_bytes()); + bytes.extend_from_slice(&bits_per_sample.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + let allocation = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), allocation.cast(), bytes.len()); + output.write(allocation); + } + HRESULT(0) +} + unsafe extern "system" fn audio_initialize( _this: *mut c_void, _share_mode: i32, _stream_flags: u32, _buffer_duration: i64, _periodicity: i64, - _format: *mut c_void, + format: *mut c_void, _session: *const GUID, ) -> HRESULT { - E_NOTIMPL + if !valid_audio_format(format.cast_const()) { + return HRESULT(0x80070057u32 as i32); + } + AUDIO_INITIALIZE_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) } unsafe extern "system" fn audio_get_u32(_this: *mut c_void, _value: *mut u32) -> HRESULT { @@ -1078,35 +1132,47 @@ unsafe extern "system" fn audio_is_format_supported( format: *mut c_void, closest: *mut *mut c_void, ) -> HRESULT { - if format.is_null() || closest.is_null() { + if !valid_audio_format(format.cast_const()) { + return HRESULT(0x80070057u32 as i32); + } + if (share_mode == 0 && closest.is_null()) || (share_mode == 1 && !closest.is_null()) { return E_POINTER; } + if !matches!(share_mode, 0 | 1) { + return HRESULT(0x80070057u32 as i32); + } AUDIO_IS_FORMAT_SUPPORTED_CALLS.fetch_add(1, Ordering::SeqCst); AUDIO_LAST_SHARE_MODE.store(share_mode, Ordering::SeqCst); AUDIO_LAST_FORMAT_TAG.store( unsafe { u32::from(*format.cast::()) }, Ordering::SeqCst, ); - let allocation = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(16) }; - if allocation.is_null() { - return HRESULT(0x8007000eu32 as i32); - } - unsafe { - allocation.cast::().write(0xaabb_ccdd); - *closest = allocation; + if !closest.is_null() { + unsafe { + *closest = std::ptr::null_mut(); + } } - if share_mode == 2 { - HRESULT(0x80004005u32 as i32) - } else { - HRESULT(1) + match AUDIO_FORMAT_SUPPORT_MODE.load(Ordering::SeqCst) { + 0 => HRESULT(0), + 1 if share_mode == 0 => { + let result = unsafe { write_audio_format(closest, 1, 44_100, 16) }; + if result.is_ok() { + HRESULT(1) + } else { + result + } + } + 1 => HRESULT(0x88890008u32 as i32), + _ => HRESULT(0x80004005u32 as i32), } } unsafe extern "system" fn audio_get_mix_format( _this: *mut c_void, - _format: *mut *mut c_void, + format: *mut *mut c_void, ) -> HRESULT { - E_NOTIMPL + AUDIO_GET_MIX_FORMAT_CALLS.fetch_add(1, Ordering::SeqCst); + unsafe { write_audio_format(format, 2, 48_000, 16) } } unsafe extern "system" fn audio_get_device_period( @@ -1209,7 +1275,9 @@ static AUDIO_VTABLE: GeneratedAudioClientVtbl = GeneratedAudioClientVtbl { #[napi(object)] pub struct GeneratedAudioClientStats { + pub initialize_calls: u32, pub is_format_supported_calls: u32, + pub get_mix_format_calls: u32, pub get_service_calls: u32, pub last_share_mode: i32, pub last_format_tag: u32, @@ -1220,10 +1288,13 @@ pub struct GeneratedAudioClientStats { #[napi] pub fn create_generated_audio_client_fake() -> napi::Result { + AUDIO_INITIALIZE_CALLS.store(0, Ordering::SeqCst); AUDIO_IS_FORMAT_SUPPORTED_CALLS.store(0, Ordering::SeqCst); + AUDIO_GET_MIX_FORMAT_CALLS.store(0, Ordering::SeqCst); AUDIO_GET_SERVICE_CALLS.store(0, Ordering::SeqCst); AUDIO_LAST_SHARE_MODE.store(0, Ordering::SeqCst); AUDIO_LAST_FORMAT_TAG.store(0, Ordering::SeqCst); + AUDIO_FORMAT_SUPPORT_MODE.store(0, Ordering::SeqCst); AUDIO_GET_SERVICE_MODE.store(0, Ordering::SeqCst); AUDIO_ADD_REF_CALLS.store(0, Ordering::SeqCst); AUDIO_RELEASE_CALLS.store(0, Ordering::SeqCst); @@ -1236,6 +1307,17 @@ pub fn create_generated_audio_client_fake() -> napi::Result { crate::com::apartment_bound_com_object(unknown) } +#[napi] +pub fn set_generated_audio_client_format_support_mode(mode: i32) -> napi::Result<()> { + if !(-1..=1).contains(&mode) { + return Err(napi::Error::from_reason( + "generated audio format-support mode must be -1, 0, or 1", + )); + } + AUDIO_FORMAT_SUPPORT_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + #[napi] pub fn set_generated_audio_client_get_service_mode(mode: i32) -> napi::Result<()> { if !(-5..=5).contains(&mode) { @@ -1250,7 +1332,9 @@ pub fn set_generated_audio_client_get_service_mode(mode: i32) -> napi::Result<() #[napi] pub fn generated_audio_client_stats() -> GeneratedAudioClientStats { GeneratedAudioClientStats { + initialize_calls: AUDIO_INITIALIZE_CALLS.load(Ordering::SeqCst), is_format_supported_calls: AUDIO_IS_FORMAT_SUPPORTED_CALLS.load(Ordering::SeqCst), + get_mix_format_calls: AUDIO_GET_MIX_FORMAT_CALLS.load(Ordering::SeqCst), get_service_calls: AUDIO_GET_SERVICE_CALLS.load(Ordering::SeqCst), last_share_mode: AUDIO_LAST_SHARE_MODE.load(Ordering::SeqCst), last_format_tag: AUDIO_LAST_FORMAT_TAG.load(Ordering::SeqCst), @@ -1260,6 +1344,198 @@ pub fn generated_audio_client_stats() -> GeneratedAudioClientStats { } } +#[repr(C)] +struct GeneratedEvaluationContextVtbl { + base__: IUnknown_Vtbl, + bind_value: unsafe extern "system" fn(*mut c_void, *const c_void) -> HRESULT, + get_value_by_name: + unsafe extern "system" fn(*mut c_void, *const u16, *mut *mut c_void) -> HRESULT, + clear: unsafe extern "system" fn(*mut c_void) -> HRESULT, +} + +#[repr(C)] +struct GeneratedEvaluationContextFake { + vtable: *const GeneratedEvaluationContextVtbl, + references: AtomicU32, +} + +unsafe extern "system" fn evaluation_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_IWINML_EVALUATION_CONTEXT { + return E_NOINTERFACE; + } + *result = this; + evaluation_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn evaluation_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + EVALUATION_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn evaluation_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + EVALUATION_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn evaluation_bind_value( + _this: *mut c_void, + descriptor: *const c_void, +) -> HRESULT { + if descriptor.is_null() { + return E_POINTER; + } + EVALUATION_BIND_VALUE_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn evaluation_get_value_by_name( + this: *mut c_void, + name: *const u16, + result: *mut *mut c_void, +) -> HRESULT { + if name.is_null() || result.is_null() { + return E_POINTER; + } + EVALUATION_GET_VALUE_CALLS.fetch_add(1, Ordering::SeqCst); + let mode = EVALUATION_OUTPUT_MODE.load(Ordering::SeqCst); + unsafe { + *result = std::ptr::null_mut(); + if mode == 2 { + return HRESULT(0); + } + if mode == -2 { + return HRESULT(0x80004005u32 as i32); + } + if mode.abs() == 3 { + *result = windows::core::BSTR::from("stage2-bstr") + .into_raw() + .cast_mut() + .cast(); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 4 { + *result = + windows::Win32::System::Memory::LocalAlloc(windows::Win32::System::Memory::LMEM_FIXED, 32) + .map_or(std::ptr::null_mut(), |value| value.0); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 5 { + *result = + windows::Win32::System::Memory::GlobalAlloc(windows::Win32::System::Memory::GMEM_FIXED, 32) + .map_or(std::ptr::null_mut(), |value| value.0); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 6 { + *result = windows::Win32::System::Com::CoTaskMemAlloc(16); + if !(*result).is_null() { + (*result).cast::().write(0xaabb_ccdd); + } + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else if (*result).is_null() { + HRESULT(0x8007000eu32 as i32) + } else { + HRESULT(0) + }; + } + evaluation_add_ref(this); + *result = this; + } + if mode == 1 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + } +} + +unsafe extern "system" fn evaluation_clear(_this: *mut c_void) -> HRESULT { + HRESULT(0) +} + +static EVALUATION_VTABLE: GeneratedEvaluationContextVtbl = GeneratedEvaluationContextVtbl { + base__: IUnknown_Vtbl { + QueryInterface: evaluation_query_interface, + AddRef: evaluation_add_ref, + Release: evaluation_release, + }, + bind_value: evaluation_bind_value, + get_value_by_name: evaluation_get_value_by_name, + clear: evaluation_clear, +}; + +#[napi(object)] +pub struct GeneratedEvaluationContextStats { + pub bind_value_calls: u32, + pub get_value_calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_evaluation_context_fake() -> napi::Result { + EVALUATION_BIND_VALUE_CALLS.store(0, Ordering::SeqCst); + EVALUATION_GET_VALUE_CALLS.store(0, Ordering::SeqCst); + EVALUATION_OUTPUT_MODE.store(0, Ordering::SeqCst); + EVALUATION_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedEvaluationContextFake { + vtable: &EVALUATION_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_evaluation_context_output_mode(mode: i32) -> napi::Result<()> { + if !(-6..=6).contains(&mode) { + return Err(napi::Error::from_reason( + "generated evaluation output mode must be between -6 and 6", + )); + } + EVALUATION_OUTPUT_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + +#[napi] +pub fn generated_evaluation_context_stats() -> GeneratedEvaluationContextStats { + GeneratedEvaluationContextStats { + bind_value_calls: EVALUATION_BIND_VALUE_CALLS.load(Ordering::SeqCst), + get_value_calls: EVALUATION_GET_VALUE_CALLS.load(Ordering::SeqCst), + current_ref_count: EVALUATION_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + #[napi] pub fn create_generated_native_cleanup_resource(kind: u32) -> napi::Result { let address = match kind { diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 725da524..e502de76 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -1228,6 +1228,17 @@ impl DynWinRTValue { ))), None, ), + dynwinrt::com::Value::AudioFormat(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new( + dynwinrt::com::Value::AudioFormat(value), + )), + None, + ), dynwinrt::com::Value::Buffer(value) => Self( dynwinrt::WinRTValue::Null, None, diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index f76ab0a6..892ca9b8 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -414,6 +414,10 @@ pub(crate) trait ArgumentList { fn get_stg_medium(&self, _index: usize) -> Option<&crate::com::StgMediumValue> { None } + + fn get_audio_format(&self, _index: usize) -> Option<&crate::com::AudioFormatValue> { + None + } } impl ArgumentList for [WinRTValue] { @@ -736,6 +740,8 @@ where std::collections::BTreeMap::::new(); let mut stg_medium_out_values = std::collections::BTreeMap::::new(); + let mut audio_format_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) @@ -754,6 +760,7 @@ where 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(); + let mut audio_format_in_ptrs: Vec<*const c_void> = Vec::new(); // FillArray storage: caller-allocated buffers let mut fill_array_slots: Vec> = Vec::new(); @@ -1069,6 +1076,25 @@ where stg_medium_out_values.insert(p.value_index, value); array_out_map.push(None); fill_array_map.push(None); + } else if p.typ.is_audio_format() { + if p.is_in_out() { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "WAVEFORMATEX in/out is not supported", + )); + } + let mut value = crate::com::AudioFormatOutput::new(); + out_ptrs.push(value.as_mut_ptr().cast_const()); + 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); + audio_format_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")) @@ -1188,6 +1214,12 @@ where ) })?, ); + } else if p.is_input() && !p.is_out() && p.typ.is_audio_format() { + audio_format_in_ptrs.push( + args.get_audio_format(p.input_index.expect("WAVEFORMATEX input index")) + .expect("validated WAVEFORMATEX input") + .as_ptr(), + ); } } let native_struct_in_ptrs = native_struct_in_slots @@ -1300,6 +1332,7 @@ where let mut dispatch_params_in_idx = 0usize; let mut format_etc_in_idx = 0usize; let mut stg_medium_in_idx = 0usize; + let mut audio_format_in_idx = 0usize; for p in parameters { if p.is_out() { if let Some(slot_idx) = fill_array_map[p.value_index] { @@ -1353,6 +1386,9 @@ where } 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_audio_format() { + ffi_args.push(arg(&audio_format_in_ptrs[audio_format_in_idx])); + audio_format_in_idx += 1; } else if p.typ.is_variant() { ffi_args.push(arg(&variant_in_ptrs[variant_in_idx])); variant_in_idx += 1; @@ -1735,6 +1771,16 @@ where ) }, )?)); + } else if let Some(value) = audio_format_out_values.remove(&p.value_index) { + match value.into_value(p.is_optional_out()).map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })? { + Some(value) => result_values.push(NativeCallValue::AudioFormat(value)), + None => result_values.push(NativeCallValue::WinRt(WinRTValue::Null)), + } } 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 3b4615f1..bf7e77eb 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -900,6 +900,198 @@ impl Drop for StgMediumStorage { } } +const WAVEFORMATEX_SIZE: usize = 18; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AudioFormatValue { + bytes: Arc<[u8]>, +} + +impl AudioFormatValue { + pub fn from_wave_format_ex(bytes: Vec) -> result::Result { + if bytes.len() < WAVEFORMATEX_SIZE { + return Err(invalid_argument( + "WAVEFORMATEX storage is smaller than its 18-byte header", + )); + } + let extra_size = u16::from_le_bytes([bytes[16], bytes[17]]) as usize; + if bytes.len() != WAVEFORMATEX_SIZE + extra_size { + return Err(invalid_argument(&format!( + "WAVEFORMATEX storage length {} does not match cbSize {}", + bytes.len(), + extra_size + ))); + } + let value = Self { + bytes: bytes.into(), + }; + if value.format_tag() == 0xfffe && extra_size < 22 { + return Err(invalid_argument( + "WAVEFORMATEXTENSIBLE storage requires at least 22 extension bytes", + )); + } + Ok(value) + } + + pub fn wave_format_ex( + format_tag: u16, + channels: u16, + samples_per_second: u32, + average_bytes_per_second: u32, + block_align: u16, + bits_per_sample: u16, + extra_data: Vec, + ) -> result::Result { + let extra_size = u16::try_from(extra_data.len()) + .map_err(|_| invalid_argument("WAVEFORMATEX extra data exceeds u16::MAX bytes"))?; + let mut bytes = Vec::with_capacity(WAVEFORMATEX_SIZE + extra_data.len()); + bytes.extend_from_slice(&format_tag.to_le_bytes()); + bytes.extend_from_slice(&channels.to_le_bytes()); + bytes.extend_from_slice(&samples_per_second.to_le_bytes()); + bytes.extend_from_slice(&average_bytes_per_second.to_le_bytes()); + bytes.extend_from_slice(&block_align.to_le_bytes()); + bytes.extend_from_slice(&bits_per_sample.to_le_bytes()); + bytes.extend_from_slice(&extra_size.to_le_bytes()); + bytes.extend_from_slice(&extra_data); + Self::from_wave_format_ex(bytes) + } + + pub fn pcm( + channels: u16, + samples_per_second: u32, + bits_per_sample: u16, + ) -> result::Result { + if channels == 0 || samples_per_second == 0 { + return Err(invalid_argument( + "PCM channel count and sample rate must be non-zero", + )); + } + if bits_per_sample == 0 || bits_per_sample % 8 != 0 { + return Err(invalid_argument( + "PCM bits per sample must be a non-zero multiple of eight", + )); + } + let block_align = u32::from(channels) + .checked_mul(u32::from(bits_per_sample / 8)) + .and_then(|value| u16::try_from(value).ok()) + .ok_or_else(|| invalid_argument("PCM block alignment exceeds u16::MAX"))?; + let average_bytes_per_second = samples_per_second + .checked_mul(u32::from(block_align)) + .ok_or_else(|| invalid_argument("PCM average byte rate exceeds u32::MAX"))?; + Self::wave_format_ex( + 1, + channels, + samples_per_second, + average_bytes_per_second, + block_align, + bits_per_sample, + Vec::new(), + ) + } + + pub fn format_tag(&self) -> u16 { + u16::from_le_bytes([self.bytes[0], self.bytes[1]]) + } + + pub fn channels(&self) -> u16 { + u16::from_le_bytes([self.bytes[2], self.bytes[3]]) + } + + pub fn samples_per_second(&self) -> u32 { + u32::from_le_bytes(self.bytes[4..8].try_into().unwrap()) + } + + pub fn average_bytes_per_second(&self) -> u32 { + u32::from_le_bytes(self.bytes[8..12].try_into().unwrap()) + } + + pub fn block_align(&self) -> u16 { + u16::from_le_bytes([self.bytes[12], self.bytes[13]]) + } + + pub fn bits_per_sample(&self) -> u16 { + u16::from_le_bytes([self.bytes[14], self.bytes[15]]) + } + + pub fn extra_data(&self) -> &[u8] { + &self.bytes[WAVEFORMATEX_SIZE..] + } + + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + + pub(crate) fn as_ptr(&self) -> *const c_void { + self.bytes.as_ptr().cast() + } + + unsafe fn copy_from_native(value: *const c_void) -> result::Result { + if value.is_null() { + return Err(invalid_argument("WAVEFORMATEX output was null")); + } + let header = unsafe { std::slice::from_raw_parts(value.cast::(), WAVEFORMATEX_SIZE) }; + let format_tag = u16::from_le_bytes([header[0], header[1]]); + let extra_size = if format_tag == 1 { + 0 + } else { + u16::from_le_bytes([header[16], header[17]]) as usize + }; + let mut bytes = unsafe { + std::slice::from_raw_parts(value.cast::(), WAVEFORMATEX_SIZE + extra_size) + } + .to_vec(); + if format_tag == 1 { + bytes[16..18].copy_from_slice(&0u16.to_le_bytes()); + } + Self::from_wave_format_ex(bytes) + } +} + +pub(crate) struct AudioFormatOutput { + raw: Box<*mut c_void>, +} + +impl AudioFormatOutput { + pub(crate) fn new() -> Self { + Self { + raw: Box::new(std::ptr::null_mut()), + } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut c_void { + (&mut *self.raw as *mut *mut c_void).cast() + } + + pub(crate) fn into_value(mut self, nullable: bool) -> result::Result> { + if self.raw.is_null() { + return if nullable { + Ok(None) + } else { + Err(invalid_argument("required WAVEFORMATEX output was null")) + }; + } + let value = unsafe { AudioFormatValue::copy_from_native(*self.raw) }; + self.free(); + value.map(Some) + } + + fn free(&mut self) { + if self.raw.is_null() { + return; + } + unsafe { + crate::native_call::OutputCleanup::CoTaskMemFree.cleanup(*self.raw); + } + *self.raw = std::ptr::null_mut(); + } +} + +impl Drop for AudioFormatOutput { + fn drop(&mut self) { + self.free(); + } +} + #[cfg(test)] static STATSTG_TEST_FREES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -1249,6 +1441,7 @@ pub enum Value { StatStg(StatStgValue), FormatEtc(FormatEtcValue), StgMedium(StgMediumValue), + AudioFormat(AudioFormatValue), Buffer(ComBufferValue), } @@ -1267,6 +1460,7 @@ fn is_null_input_value(value: &Value) -> bool { | Value::StatStg(_) | Value::FormatEtc(_) | Value::StgMedium(_) + | Value::AudioFormat(_) | Value::Buffer(_) => false, } } @@ -2018,7 +2212,8 @@ impl BufferElementPlan { | ParameterType::ExcepInfo | ParameterType::StatStg | ParameterType::FormatEtc - | ParameterType::StgMedium => { + | ParameterType::StgMedium + | ParameterType::AudioFormat => { return Err(invalid_argument( "Automation buffer elements require dedicated ownership and cleanup plans", )); @@ -2336,6 +2531,15 @@ impl Type { } } + pub fn audio_format() -> Self { + Self { + abi: ParameterType::audio_format(), + pointer_output: PointerOutputKind::None, + allow_direct_aggregate_return: false, + aggregate_capability: None, + } + } + fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { Self { abi: ParameterType::pointer(), @@ -3270,7 +3474,9 @@ impl CallbackMethodPlan { | ParameterType::DispatchParams | ParameterType::ExcepInfo | ParameterType::StatStg => Some(crate::native_callback::CallbackAbiType::Pointer), - ParameterType::FormatEtc | ParameterType::StgMedium => None, + ParameterType::FormatEtc | ParameterType::StgMedium | ParameterType::AudioFormat => { + None + } ParameterType::NativeStruct(layout) => { Some(crate::native_callback::CallbackAbiType::NativeStruct( format!("{layout:?}"), @@ -3727,7 +3933,8 @@ impl CallbackMethodPlan { ParameterType::NativeUnion(_) | ParameterType::VariantByValue | ParameterType::FormatEtc - | ParameterType::StgMedium => Err(SINK_E_FAIL), + | ParameterType::StgMedium + | ParameterType::AudioFormat => Err(SINK_E_FAIL), } } @@ -4380,7 +4587,8 @@ impl ComCallPlan { | Value::ExcepInfo(_) | Value::StatStg(_) | Value::FormatEtc(_) - | Value::StgMedium(_) => Err(invalid_argument( + | Value::StgMedium(_) + | Value::AudioFormat(_) => Err(invalid_argument( "COM-local result requires the COM value invocation path", )), Value::Buffer(_) => Err(invalid_argument( @@ -4578,7 +4786,8 @@ impl ComCallPlan { | Value::ExcepInfo(_) | Value::StatStg(_) | Value::FormatEtc(_) - | Value::StgMedium(_) => Err(invalid_argument( + | Value::StgMedium(_) + | Value::AudioFormat(_) => Err(invalid_argument( "COM-local value passed to a scalar COM method", )), Value::Buffer(_) => Err(invalid_argument( @@ -6092,7 +6301,9 @@ fn validate_automation_contracts( { return Err(invalid_argument("FORMATETC does not support in/out")); } - if (parameter.typ.abi.is_format_etc() || parameter.typ.abi.is_stg_medium()) + if (parameter.typ.abi.is_format_etc() + || parameter.typ.abi.is_stg_medium() + || parameter.typ.abi.is_audio_format()) && parameter.direction != ComParameterDirection::In && !matches!( return_plan, @@ -6100,9 +6311,14 @@ fn validate_automation_contracts( ) { return Err(invalid_argument( - "FORMATETC/STGMEDIUM outputs require an HRESULT return convention", + "FORMATETC/STGMEDIUM/WAVEFORMATEX outputs require an HRESULT return convention", )); } + if parameter.typ.abi.is_audio_format() + && parameter.direction == ComParameterDirection::InOut + { + return Err(invalid_argument("WAVEFORMATEX does not support in/out")); + } if parameter.typ.abi.is_excep_info() && !matches!( return_plan, @@ -10907,6 +11123,126 @@ mod tests { HRESULT(0) } + unsafe extern "system" fn inspect_audio_format( + _this: *mut c_void, + format: *const c_void, + ) -> HRESULT { + if format.is_null() { + return HRESULT(0x80070057u32 as i32); + } + let header = unsafe { std::slice::from_raw_parts(format.cast::(), WAVEFORMATEX_SIZE) }; + if u16::from_le_bytes([header[0], header[1]]) != 1 + || u16::from_le_bytes([header[2], header[3]]) != 2 + || u32::from_le_bytes(header[4..8].try_into().unwrap()) != 48_000 + || u16::from_le_bytes([header[16], header[17]]) != 0 + { + return HRESULT(0x80070057u32 as i32); + } + HRESULT(0) + } + + unsafe extern "system" fn write_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + let bytes = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.bytes().len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping( + bytes.bytes().as_ptr(), + allocation.cast(), + bytes.bytes().len(), + ); + output.write(allocation); + } + HRESULT(0) + } + + unsafe extern "system" fn write_audio_format_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + let result = unsafe { write_audio_format(this, output) }; + if result.is_err() { + result + } else { + HRESULT(0x80004005u32 as i32) + } + } + + unsafe extern "system" fn write_invalid_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + let bytes = + AudioFormatValue::wave_format_ex(2, 2, 48_000, 192_000, 4, 16, vec![0; 21]).unwrap(); + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.bytes().len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping( + bytes.bytes().as_ptr(), + allocation.cast(), + bytes.bytes().len(), + ); + allocation.cast::().write(0xfffe); + output.write(allocation); + } + HRESULT(0) + } + + unsafe extern "system" fn write_pcm_with_ignored_extra_size( + this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + let result = unsafe { write_audio_format(this, output) }; + if result.is_ok() { + unsafe { + (*output) + .cast::() + .add(16) + .cast::() + .write_unaligned(u16::MAX); + } + } + result + } + + unsafe extern "system" fn write_null_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if !output.is_null() { + unsafe { + output.write(std::ptr::null_mut()); + } + } + HRESULT(0) + } + + unsafe extern "system" fn require_null_audio_format_output( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + HRESULT(0) + } else { + HRESULT(0x80004005u32 as i32) + } + } + fn invoke_test_stat_stg(function: *mut c_void, flags: u32) -> result::Result> { let table = MetadataTable::new(); invoke_test_pod( @@ -13889,6 +14225,112 @@ mod tests { ); } + #[test] + fn audio_format_calls_validate_variable_storage_and_cotaskmem_ownership() { + let table = MetadataTable::new(); + let format = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + assert_eq!(format.format_tag(), 1); + assert_eq!(format.channels(), 2); + assert_eq!(format.samples_per_second(), 48_000); + assert_eq!(format.average_bytes_per_second(), 192_000); + assert_eq!(format.block_align(), 4); + assert_eq!(format.bits_per_sample(), 16); + assert!(format.extra_data().is_empty()); + assert_eq!(format.bytes().len(), WAVEFORMATEX_SIZE); + assert!(AudioFormatValue::pcm(2, 48_000, 12).is_err()); + assert!(AudioFormatValue::from_wave_format_ex(vec![0; 17]).is_err()); + let mut wrong_size = format.bytes().to_vec(); + wrong_size[16..18].copy_from_slice(&1u16.to_le_bytes()); + assert!(AudioFormatValue::from_wave_format_ex(wrong_size).is_err()); + + invoke_test_pod( + inspect_audio_format as *mut c_void, + MethodSignature::new(&table).add_in(Type::audio_format()), + &[Value::AudioFormat(format.clone())], + ) + .unwrap(); + + crate::native_call::reset_co_task_mem_test_frees(); + let output = invoke_test_pod( + write_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap(); + let Value::AudioFormat(output) = &output[0] else { + panic!("expected WAVEFORMATEX output"); + }; + assert_eq!(output, &format); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let output = invoke_test_pod( + write_pcm_with_ignored_extra_size as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap(); + let Value::AudioFormat(output) = &output[0] else { + panic!("expected normalized PCM WAVEFORMATEX output"); + }; + assert_eq!(output, &format); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let error = invoke_test_pod( + write_invalid_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("at least 22 extension bytes")); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let error = invoke_test_pod( + write_audio_format_then_fail as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + let output = invoke_test_pod( + write_null_audio_format as *mut c_void, + MethodSignature::new(&table).add_optional_out(Type::audio_format()), + &[Value::WinRt(WinRTValue::Bool(true))], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::Null)] + )); + + let output = invoke_test_pod( + require_null_audio_format_output as *mut c_void, + MethodSignature::new(&table).add_optional_out(Type::audio_format()), + &[Value::WinRt(WinRTValue::Bool(false))], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::Null)] + )); + + let error = invoke_test_pod( + write_null_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!( + error + .message() + .contains("required WAVEFORMATEX output was null") + ); + } + #[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 2d6d7078..8256627e 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -38,6 +38,7 @@ pub(crate) enum NativeCallValue { StatStg(crate::com::StatStgValue), FormatEtc(crate::com::FormatEtcValue), StgMedium(crate::com::StgMediumValue), + AudioFormat(crate::com::AudioFormatValue), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -78,6 +79,7 @@ pub(crate) enum ParameterType { StatStg, FormatEtc, StgMedium, + AudioFormat, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -240,6 +242,10 @@ impl ParameterType { Self::StgMedium } + pub(crate) fn audio_format() -> Self { + Self::AudioFormat + } + pub(crate) fn as_winrt(&self) -> Option<&TypeHandle> { match self { Self::WinRT(typ) => Some(typ), @@ -258,7 +264,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => None, + | Self::StgMedium + | Self::AudioFormat => None, } } @@ -279,7 +286,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => None, + | Self::StgMedium + | Self::AudioFormat => None, } } @@ -372,6 +380,10 @@ impl ParameterType { matches!(self, Self::StgMedium) } + pub(crate) fn is_audio_format(&self) -> bool { + matches!(self, Self::AudioFormat) + } + pub(crate) fn is_array(&self) -> bool { self.as_winrt().is_some_and(TypeHandle::is_array) } @@ -440,7 +452,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => AbiType::Ptr, + | Self::StgMedium + | Self::AudioFormat => AbiType::Ptr, Self::NativeStruct(_) | Self::NativeUnion(_) | Self::VariantByValue => { panic!("aggregate values do not have a scalar AbiType") } @@ -462,7 +475,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => libffi::middle::Type::pointer(), + | Self::StgMedium + | Self::AudioFormat => libffi::middle::Type::pointer(), Self::NativeStruct(layout) => layout.libffi_type(), Self::NativeUnion(layout) => layout.libffi_type(), Self::VariantByValue => variant_by_value_libffi_type(), @@ -499,7 +513,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => { + | Self::StgMedium + | Self::AudioFormat => { panic!("native POD storage is allocated by the dynamic executor") } } @@ -523,7 +538,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => { + | Self::StgMedium + | Self::AudioFormat => { unreachable!("native POD output conversion uses NativeStructValue") } } @@ -562,7 +578,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium, + | Self::StgMedium + | Self::AudioFormat, _, ) => { unreachable!("native POD output conversion uses NativeStructValue") @@ -583,6 +600,7 @@ impl ParameterType { Self::StatStg => OutputCleanup::None, Self::FormatEtc => OutputCleanup::None, Self::StgMedium => OutputCleanup::None, + Self::AudioFormat => OutputCleanup::None, Self::Bstr { .. } => OutputCleanup::BstrFree, Self::CoTaskMemWideString => OutputCleanup::CoTaskMemFree, Self::WinRT(_) @@ -855,6 +873,7 @@ impl AbiMethodSignature { || p.typ.is_stat_stg() || p.typ.is_format_etc() || p.typ.is_stg_medium() + || p.typ.is_audio_format() }); // Check if the single in-param (if any) is a simple non-HString, non-Struct type @@ -1390,7 +1409,8 @@ impl call::ArgumentList for ComInvocationArgs<'_> { | crate::com::Value::ExcepInfo(_) | crate::com::Value::StatStg(_) | crate::com::Value::FormatEtc(_) - | crate::com::Value::StgMedium(_) => { + | crate::com::Value::StgMedium(_) + | crate::com::Value::AudioFormat(_) => { panic!("COM-local argument requested as a WinRT value") } crate::com::Value::Buffer(_) => { @@ -1461,6 +1481,13 @@ impl call::ArgumentList for ComInvocationArgs<'_> { _ => None, } } + + fn get_audio_format(&self, index: usize) -> Option<&crate::com::AudioFormatValue> { + match &self.original[index] { + crate::com::Value::AudioFormat(value) => Some(value), + _ => None, + } + } } impl Method { @@ -1498,6 +1525,7 @@ impl Method { || parameter.typ.is_stat_stg() || parameter.typ.is_format_etc() || parameter.typ.is_stg_medium() + || parameter.typ.is_audio_format() }) || self.direct_return_type().is_some_and(|typ| { typ.native_struct_layout().is_some() || typ.native_union_layout().is_some() @@ -1511,6 +1539,7 @@ impl Method { || typ.is_stat_stg() || typ.is_format_etc() || typ.is_stg_medium() + || typ.is_audio_format() }) } @@ -2012,7 +2041,8 @@ impl Method { | NativeCallValue::ExcepInfo(_) | NativeCallValue::StatStg(_) | NativeCallValue::FormatEtc(_) - | NativeCallValue::StgMedium(_) => Err(invalid_argument( + | NativeCallValue::StgMedium(_) + | NativeCallValue::AudioFormat(_) => Err(invalid_argument( "COM-local result reached the WinRT invocation path", )), }) @@ -2222,6 +2252,15 @@ impl Method { continue; } + if parameter.typ.is_audio_format() { + if !matches!(&args[input_index], crate::com::Value::AudioFormat(_)) { + return Err(invalid_argument( + "Argument type mismatch: expected WAVEFORMATEX", + )); + } + 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", @@ -2290,6 +2329,7 @@ impl Method { NativeCallValue::StatStg(value) => crate::com::Value::StatStg(value), NativeCallValue::FormatEtc(value) => crate::com::Value::FormatEtc(value), NativeCallValue::StgMedium(value) => crate::com::Value::StgMedium(value), + NativeCallValue::AudioFormat(value) => crate::com::Value::AudioFormat(value), }) .collect() }) diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 11cb958e..7999349c 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -336,11 +336,13 @@ Current code registries are migrated without changing behavior: - `IWbemServices::OpenNamespace`; - `IDispatch::Invoke` compound behavior; - `STATSTG` and allocator-specific outputs; -- `IDataObject::SetData` caller-retained STGMEDIUM ownership; and +- `IDataObject::SetData` caller-retained STGMEDIUM ownership; +- `IAudioClient` shared/exclusive format negotiation and CoTaskMem format + outputs; and - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,692/7,929 safe census, generated unsafe manifests, and all live tests agree +5,697/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -401,22 +403,22 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,336 | -| `exact_registry_dependent` | 356 | -| **Total** | **5,692** | +| `standard_derived` | 5,338 | +| `exact_registry_dependent` | 359 | +| **Total** | **5,697** | -The registry contains **496 declared entries**, all 496 match the pinned -metadata, and 405 distinct entries are consumed by safe plans. Safe plans have -656 entry/interface dependencies and 405 family/interface dependencies. -Per-interface dependency-set totals also include 5,976 metadata-attribute -dependencies and 26,119 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 +663 entry/interface dependencies and 411 family/interface dependencies. +Per-interface dependency-set totals also include 5,982 metadata-attribute +dependencies and 26,134 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 173 | +| `ownership` | 177 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | -| `conditional-output` | 7 | +| `conditional-output` | 10 | | `flag-selected-buffer` | 3 | | `null-input` | 2 | | `safearray` | 263 | @@ -436,7 +438,7 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 163 | 112 | 117 | +| `com.ownership.v1` | 165 | 114 | 120 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | | `com.semantic-hresult.v1` | 1 | 1 | 2 | @@ -444,6 +446,7 @@ Family rollups deliberately count each interface once per family: | `graphics.private-data-hazard.v1` | 7 | 0 | 0 | | `shell.flag-selected-string.v1` | 1 | 1 | 3 | | `wmi.conditional-output.v1` | 7 | 7 | 1 | +| `audio.conditional-output.v1` | 1 | 1 | 3 | Universal rule dependencies are: @@ -454,11 +457,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,574 | +| `com.hresult.failure.v1` | 5,579 | | `com.interface.input-borrow.v1` | 1,891 | | `com.interface.typed-output-plus-one.v1` | 3,458 | -| `com.iunknown.identity-refcount.v1` | 5,692 | -| `com.query-interface.output-plus-one.v1` | 5,692 | +| `com.iunknown.identity-refcount.v1` | 5,697 | +| `com.query-interface.output-plus-one.v1` | 5,697 | | `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-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index ff595368..a7e62822 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -49,9 +49,9 @@ generated/ │ ├── ITaskbarList3.js │ └── ITaskbarList3.d.ts └── unsafe/ - ├── windows/win32/media/audio/ - │ ├── IAudioClientUnsafe.js - │ └── IAudioClientUnsafe.d.ts + ├── windows/win32/ai/machine-learning/win-ml/ + │ ├── IWinMLEvaluationContextUnsafe.js + │ └── IWinMLEvaluationContextUnsafe.d.ts ├── index.js ├── index.mjs ├── index.d.ts @@ -83,16 +83,16 @@ Rules: The unsafe boundary is carried by the module path and class suffix: ```js -import { IAudioClientUnsafe } from "./generated/com/unsafe/index.js"; +import { IWinMLEvaluationContextUnsafe } from "./generated/com/unsafe/index.js"; ``` Methods keep their natural projected names: ```js -audio.isFormatSupported(...); +context.getValueByName(...); ``` -Do not emit a class named `IAudioClient` for an unsafe projection. Method names +Do not emit a class without the `Unsafe` suffix for an unsafe projection. Method names need an `Unsafe` suffix only if safe and unsafe methods are ever placed on the same class; the preferred design keeps them in separate companion classes. @@ -199,12 +199,12 @@ Generated unsafe companions do not add raw callback implementation. An unsafe companion wraps an existing managed native value: ```ts -export declare class IAudioClientUnsafe { +export declare class IWinMLEvaluationContextUnsafe { private constructor(); static from( value: DynWinRtValue | { readonly nativeValue: DynWinRtValue }, - ): IAudioClientUnsafe; + ): IWinMLEvaluationContextUnsafe; static readonly iid: WinGuid; static readonly support: UnsafeInterfaceSupport; readonly nativeValue: DynWinRtValue; @@ -212,11 +212,11 @@ export declare class IAudioClientUnsafe { /** * @unsafe Metadata-complete outbound ABI. */ - isFormatSupported( - shareMode: number, - format: UnsafePointee, - closestMatch: UnsafePointerOutput, - ): readonly [number, UnsafeOwnedPointer | null]; + bindValue(descriptor: UnsafePointee): void; + getValueByName( + name: DynComRawMemory | DynComRawPointer, + descriptor: UnsafePointerOutput, + ): UnsafeOwnedPointer; release(): void; } @@ -459,18 +459,18 @@ Generation emits `generated/com/unsafe/support.json`: "sha256": "..." } }, - "interfaceName": "Windows.Win32.Media.Audio.IAudioClient", - "interfaceIid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "interfaceName": "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", + "interfaceIid": "95848f9e-583d-4054-af12-916387cd8426", "root": "IUnknown", "baseIids": [], - "unsafeClass": "IAudioClientUnsafe", - "modulePath": "windows/win32/media/audio/IAudioClientUnsafe", + "unsafeClass": "IWinMLEvaluationContextUnsafe", + "modulePath": "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe", "methods": [ { - "name": "Initialize", - "projectedName": "initialize", - "declaringIid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", - "absoluteSlot": 4, + "name": "BindValue", + "projectedName": "bindValue", + "declaringIid": "95848f9e-583d-4054-af12-916387cd8426", + "absoluteSlot": 3, "signatureFingerprint": "...", "status": "manual_contract_required", "reasons": ["..."], @@ -521,7 +521,7 @@ also returns nonzero. Example output: ```text -[dry-run] Would generate IAudioClientUnsafe (metadata-complete: 8, manual: 4, blocked: 0) +[dry-run] Would generate IWinMLEvaluationContextUnsafe (metadata-complete: 1, manual: 2, blocked: 0) [dry-run] Report-only MFASYNCRESULTUnsafe {"metadataComplete":0,"manual":0,"blocked":5,"reasons":["missing_interface_iid"]} ``` @@ -659,7 +659,8 @@ Required tests include: 13. actual Node resolution of mixed WinRT, COM barrel, and unsafe canonical package exports. -The generated-artifact integration fixture combines safe WMI with unsafe Audio. +The generated-artifact integration fixture combines safe WMI, IDataObject, and +IAudioClient projections with an unsafe WinML companion. The complete seven-method WMI conditional-output family executes through a slot-accurate fake `IWbemServices` vtable. It validates sync/semisync OptionalOut selection, no-output sync calls, `ExecMethod` multi-input calls, @@ -671,12 +672,11 @@ a fake COM object that returns a real HBITMAP. It validates transfer into `DynComOwnedHandle`, explicit `DeleteObject` release, idempotence, and COM reference balance; a Rust regression separately covers the Drop path. -The unsafe portion uses official `IAudioClientUnsafe::isFormatSupported` and -`getService` vtable slots. It covers -CoTaskMem closest-format success/failure cleanup, BSTR/Local/Global dirty -failure cleanup, COM-owned output cleanup, required/nullable output, strategy -mismatch before dispatch, one-shot reuse, handle/raw/count strategies, and all -three interface-replacement modes. +The unsafe portion uses official +`IWinMLEvaluationContextUnsafe::bindValue` and `getValueByName` vtable slots. +It covers CoTaskMem/BSTR/Local/Global dirty failure cleanup, COM-owned output +cleanup, required/nullable output, strategy mismatch before dispatch, one-shot +reuse, handle/raw/count strategies, and all three interface-replacement modes. ## Rollout plan diff --git a/docs/architecture/classic-com-raw-unsafe.md b/docs/architecture/classic-com-raw-unsafe.md index 9718f424..07102aae 100644 --- a/docs/architecture/classic-com-raw-unsafe.md +++ b/docs/architecture/classic-com-raw-unsafe.md @@ -606,8 +606,8 @@ does not mutate persistent system state. ### Final Phase 1 outbound matrix The matrix uses real synchronous fake vtables and the exact Windows -`extern "system"` ABI. It proves raw reach; none of these interfaces become -safe-generated: +`extern "system"` ABI. It proves raw reach independently of later safe +promotion: | Scenario | Verified raw contract | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -632,8 +632,9 @@ runtime gate. Public consumption examples live in `bindings/js/__test__/raw-phase1.spec.ts`. This provides broad in-process, current-apartment, outbound raw COM coverage -for completed scalar, pointer, memory, and struct contracts. It does not make -`IDataObject`, `IAudioClient`, private-data APIs, or WMI safe-generated. +for completed scalar, pointer, memory, and struct contracts. Later dedicated +semantic models make `IDataObject`, `IAudioClient`, and WMI safe-generated; +private-data APIs remain unsafe because their payload ownership is ambiguous. Phase 1 can be called complete for the documented in-process, current-apartment, outbound raw ABI subset on x64 and i686. The precise ABI diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 4da6a117..6434b039 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,692 complete safe -> interface projections out of 7,929 eligible interfaces (71.79%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,697 complete safe +> interface projections out of 7,929 eligible interfaces (71.85%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -614,6 +614,7 @@ and `@microsoft/dynwinrt/com`. | 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`; `GetDataHere` preserves caller allocation; exact IID/slot/shape/fingerprint evidence pins `SetData.fRelease=FALSE` | `DVTARGETDEVICE`, non-HGLOBAL media, JavaScript callback implementation, and ownership-transfer input | +| Audio formats | Variable-length WAVEFORMATEX/WAVEFORMATEXTENSIBLE bytes with validated `cbSize`; PCM factory; exact shared/exclusive `IsFormatSupported` output selection; CoTaskMem-owned format outputs | Format-specific codec payload interpretation and JavaScript callback implementation | | 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 | @@ -659,6 +660,7 @@ and `@microsoft/dynwinrt/com`. | 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` fixes `fRelease` to `FALSE`. | +| WAVEFORMATEX / WAVEFORMATEXTENSIBLE | Supported | `DynComAudioFormat` validates the packed 18-byte header plus exact `cbSize` extension, provides a PCM factory and field accessors, and preserves unknown codec extension bytes. Exact contracts pass `IsFormatSupported.ppClosestMatch` only in shared mode and free GetMixFormat/current-engine-format outputs with `CoTaskMemFree`. | | 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. | @@ -714,7 +716,7 @@ of every type in the 24 MB metadata file. | 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 | | Caller-owned ANSI output buffers | `PSTR` output-buffer APIs | Safe sizing and decoding are not yet projected. | Win32 winmd signature + projection limitation | | Private-data bytes or interface pointer | `IDXGIObject`, `ID3D10DeviceChild`, `ID3D10Device`, `ID3D11DeviceChild`, `ID3D11Device`, `ID3D12Object`, and `IDMLObject` `GetPrivateData` | The same GUID-keyed method may return ordinary bytes or an AddRef'd interface pointer. A `Buffer` projection would lose the interface ownership transfer; Direct3D 10 NULL calls are destructive, and DXGI's data parameter is required. | Exact Win32 winmd identities + Microsoft method documentation | -| Untyped output pointers without allocator/ownership | `IAudioClient::IsFormatSupported` and unrelated `void*` outputs | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. | Win32 winmd + codegen diagnostics | +| Untyped output pointers without allocator/ownership | Unrelated `void*` outputs | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. Audio-format outputs are supported only for exact pinned methods. | Win32 winmd + codegen diagnostics | | Interface `[in, out]` ownership | Generic typed `IFoo**` InOut parameters | Replacing an existing interface pointer requires explicit release/AddRef transfer semantics. `IWbemServices::OpenNamespace` is not in this category: exact SDK evidence corrects its two flags to Out. | Win32 winmd + codegen diagnostic | | Callback methods outside the validated implementation subset | Automation providers, custom marshaling, and resource-owning callbacks | The dynamic backend supports broad scalar/string/POD/buffer ABI shapes and multi-interface inheritance, but VARIANT/SAFEARRAY/PROPVARIANT callbacks, untagged unions, unknown pointers/allocators, interface replacement, and custom marshal contracts still fail the whole interface closed. | Runtime/codegen validation boundary | | COM aggregation | `IClassFactory::CreateInstance` with `pUnkOuter` | The public activation helper always creates a non-aggregated in-process object. | Runtime/public-API boundary | @@ -1228,12 +1230,14 @@ exact CoTaskMem output-ownership, parameter-direction, and null-input registries subsequently promote 114 additional complete interfaces, bringing that census to 5,681. The dedicated target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM model promotes 11 more interfaces, bringing -the current literal census to **5,692 / 7,929 = 71.787111%**. The result remains -above the 70% target without admitting any unmodeled target-device, storage -medium, ownership-transfer, or callback shape. +that census to 5,692. The variable-length WAVEFORMATEX model and three pinned +audio method contracts promote five more interfaces, bringing the current +literal census to **5,697 / 7,929 = 71.850170%**. The result remains above the +70% target without admitting any unmodeled target-device, storage-medium, +audio-output ownership, ownership-transfer, or callback shape. CI reproduces this number with `dynwinrt-codegen com-census --json` and fails -if the denominator changes, complete generation drops below 5,692, or coverage +if the denominator changes, complete generation drops below 5,697, or coverage falls below 70%. ## Public-code frequency snapshot @@ -1302,7 +1306,7 @@ against the resolved namespace. | 21 | `IBindCtx` | 2,660 | 42 | Yes | Generates with exact `BIND_OPTS.cbStruct = sizeof(BIND_OPTS)` initialization and live `CreateBindCtx` coverage | | 22 | `IFileOpenDialog` | 2,536 | 92 | Yes | Generates and live-tested without showing UI | | 23 | `IRunningObjectTable` | 2,532 | 50 | Yes | Generates with POD `FILETIME`; acquisition/live test still needed | -| 24 | `IAudioClient` | 2,500 | 82 | Yes | Fail closed: format pointer/output ownership | +| 24 | `IAudioClient` | 2,500 | 82 | Yes | Generates completely with typed variable-length audio formats and exact IsFormatSupported/GetMixFormat ownership | | 25 | `IShellLinkW` | 2,128 | 67 | Yes | Generates and is live-tested with nested/fixed-array POD `WIN32_FIND_DATAW` | | 26 | `ITaskbarList3` / `TaskbarList` | 1,672 | 87 | Yes | Interface and newable coclass generate and are live-tested | | 27 | `ICoreWebView2` | 1,608 | 35 | **No** | Defined in WebView2 metadata, not Windows.Win32.winmd | @@ -1324,7 +1328,7 @@ against the resolved namespace. 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); + - explicit output ownership (notably DXGI/private-data APIs); - remaining interface in/out replacement semantics; and - unsupported PROPVARIANT alternatives in Property System APIs beyond `IPropertyStore`. @@ -1336,7 +1340,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, -graphics interfaces, audio, non-HGLOBAL data transfer, and live real-object +graphics interfaces, advanced audio, non-HGLOBAL data transfer, and live real-object `IDispatch::Invoke` coverage remain material gaps. ## Engineering priority map @@ -1366,7 +1370,7 @@ hardware, and whether it adds a distinct ABI shape. | `ICreateErrorInfo` / `IErrorInfo` | COM rich error information | Complete generation and acquisition are live-tested for GUID, wide strings, owned BSTR output, thread-local storage, and one-shot consumption. | | `IMMDeviceEnumerator` | Audio endpoint discovery | Generates today, but live behavior depends on available audio endpoints. | | `IWbemServices` | WMI queries and method invocation | Complete generation uses exact sync/semisync output selection; selected outputs are owned COM references and `pCtx` is native null in the closed safe overloads. | -| `IAudioClient` | Low-level audio streaming | Fails closed because its format and output-pointer shapes are not fully modeled. | +| `IAudioClient` / `IAudioClient2` / `IAudioClient3` | Low-level audio streaming | Complete safe generation uses `DynComAudioFormat`; exact fingerprinted contracts model shared/exclusive closest-format selection and CoTaskMem-owned format outputs. Generated fake-vtable coverage is hardware-independent. | | `IDispatch` | Automation and scripting | Complete inherited real-metadata generation passes. `GetIDsOfNames` projects as `string[] -> number[]`; `Invoke` accepts `DynComDispatchParams` and explicit result/excepInfo/argErr request options, returning dedicated owning wrappers. Derived Automation interfaces remain independently validated. | | `IPropertyStore` | Shell/property metadata | Complete generation and live ShellLink `SetValue`/`GetValue`/`Commit` coverage pass with dedicated PROPVARIANT ownership. | | `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. | diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index a3a1b6d8..377f4a21 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -144,52 +144,43 @@ remain intact. The ordinary command has no unsafe opt-in flag. If complete safe projection fails but one or more methods are `raw_metadata_complete`, codegen writes an isolated namespace-qualified companion such as -`generated/com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js` and +`generated/com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js` +and records every method in `support.json`. Safe-complete interfaces use matching canonical namespace directories under `generated/com/`. ```powershell npx dynwinrt-codegen generate ` --winmd $winmd ` - --namespace Windows.Win32.Media.Audio ` - --class-name IAudioClient ` + --namespace Windows.Win32.AI.MachineLearning.WinML ` + --class-name IWinMLEvaluationContext ` --output .\generated ``` -`IAudioClientUnsafe` hides IID registration, inheritance, absolute slots, and -signature wiring while keeping unknown format/storage ownership explicit: +`IWinMLEvaluationContextUnsafe` hides IID registration, inheritance, absolute +slots, and signature wiring while keeping unknown descriptor layout and +ownership explicit: ```js +import { DynComRawMemory } from "@microsoft/dynwinrt/com/unsafe/raw"; import { - DynComRawMemory, -} from "@microsoft/dynwinrt/com/unsafe/raw"; -import { - IAudioClientUnsafe, + IWinMLEvaluationContextUnsafe, UnsafePointee, - UnsafePointerOutput, } from "./generated/com/unsafe/index.js"; -const audio = IAudioClientUnsafe.from(existingAudioClientValue); -const format = DynComRawMemory.allocate(18, 2); +const context = IWinMLEvaluationContextUnsafe.from(existingContextValue); +const descriptor = DynComRawMemory.allocate(descriptorSize, descriptorAlignment); try { - const [hresult, closest] = audio.isFormatSupported( - 1, - UnsafePointee.required(format), - UnsafePointerOutput.coTaskMem(), - ); - try { - // Inspect the explicitly owned closest-format result. - } finally { - closest?.release(); - } + context.bindValue(UnsafePointee.required(descriptor)); } finally { - format.release(); - audio.release(); + descriptor.release(); + context.release(); } ``` -The short barrel export is available only while `IAudioClientUnsafe` is -globally unique. If two namespaces contain `IFoo`, import their deep modules: +The short barrel export is available only while +`IWinMLEvaluationContextUnsafe` is globally unique. If two namespaces contain +`IFoo`, import their deep modules: ```js import { IFooUnsafe as FooA } from "./generated/com/unsafe/contoso/a/IFooUnsafe.js"; @@ -203,36 +194,43 @@ and cleanup rules against the native contract. A failing HRESULT may throw after native code has mutated caller-owned slots; inspect and reconcile such storage according to the API contract. See the [complete generated unsafe examples](generated-com-unsafe-example.zh-CN.md) for -synchronous/semisynchronous WMI and manual-contract audio calls. +synchronous/semisynchronous WMI and manual-contract raw calls. Stage 2 also emits `raw_manual_contract` methods with required strategies from -`generated/com/unsafe/runtime.js`. For audio format negotiation: +`generated/com/unsafe/runtime.js`. A pointer output with unknown ownership +remains caller-selected and explicit: ```js import { - IAudioClientUnsafe, - UnsafePointee, + IWinMLEvaluationContextUnsafe, UnsafePointerOutput, } from "./generated/com/unsafe/index.mjs"; -const format = DynComRawMemory.allocate(22, 2); -// Fill the exact WAVEFORMATEX bytes first. -const [status, closest] = audio.isFormatSupported( - shareMode, - UnsafePointee.required(format), - // S_OK leaves ppClosestMatch null; S_FALSE may return CoTaskMem storage. - UnsafePointerOutput.coTaskMem(null, true), +const context = IWinMLEvaluationContextUnsafe.from(existingContextValue); +const output = context.getValueByName( + nameStorage, + UnsafePointerOutput.rawResponsibility(), ); try { - const closestView = closest?.view(closestByteLength, closestAlignment); - // Interpret only the layout guaranteed by the selected audio contract. - closestView?.release(); + // Reconcile and clean up `output` only according to the application's + // authoritative contract. The unsafe wrapper does not guess an allocator. } finally { - closest?.release(); - format.release(); + context.release(); } ``` +Audio format negotiation is now on the safe surface: + +```js +import { DynComAudioFormat } from "@microsoft/dynwinrt/com"; +import { IAudioClient } from "./generated/com/windows/win32/media/audio/IAudioClient.js"; + +const audio = IAudioClient._fromNative(existingAudioClientValue); +const pcm = DynComAudioFormat.pcm(2, 48_000, 16); +const [status, closest] = audio.isFormatSupported(0, pcm); +const mixFormat = audio.getMixFormat(); +``` + `IDXGIObjectUnsafe.getPrivateData` keeps its exact caller-storage API because metadata proves the ABI but not whether the payload is bytes or an AddRef'd interface. Pass ordinary bounded memory for bytes. For an interface payload, diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 30092ee1..05d6b651 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,692 | 71.79% | -| Rejected because at least one contract is incomplete | 2,237 | 28.21% | +| Complete safe generation | 5,697 | 71.85% | +| Rejected because at least one contract is incomplete | 2,232 | 28.15% | The denominator contains addressable COM interface identities, not flat Win32 DLL exports. A complete interface means that its full inherited vtable can be generated without guessing ABI, layout, count relationships, ownership, or cleanup. -The 5,692 figure is semantic codegen coverage, not a claim that every interface +The 5,697 figure is semantic codegen coverage, not a claim that every interface has a dedicated live Windows test or can be activated on every machine. Reproduce the census with: @@ -128,8 +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. | -| `IAudioClient` format negotiation | Variable audio-format layouts and untyped CoTaskMem output. | Raw format memory plus pointer output; later add a typed audio-format value. | +| 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. | | 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. | | Advanced Automation | BYREF VARIANTs, additional alternatives, replacement arrays, and nested ownership are incomplete. | Raw storage can expose ABI reach; safe support still requires dedicated value and cleanup models. | @@ -279,10 +278,11 @@ conflicts, transaction-residue names, and unsupported reparse tags fail closed. Safe and unsafe modules use the canonical lowercase/kebab namespace layout, for example `com/windows/win32/ui/shell/ITaskbarList3.js` and -`com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js`. The short class -name remains `IAudioClientUnsafe`. A short barrel export is emitted only when -globally unique; ambiguous names are available only through deep modules, and -incremental order does not affect the resulting barrel. +`com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js`. +The short class name remains `IWinMLEvaluationContextUnsafe`. A short barrel +export is emitted only when globally unique; ambiguous names are available only +through deep modules, and incremental order does not affect the resulting +barrel. Generated and retained paths share an ASCII case-folded Windows identity. Traversal, rooted/drive paths, trailing dots/spaces, reserved device names, and @@ -290,12 +290,12 @@ case-only namespace/type collisions fail closed. Existing cross-root shared ownership additionally requires the staged file to exist and exactly match the planned bytes before overwrite. -CI also generates the real official safe `IWbemServices` wrapper and -`IAudioClientUnsafe` companion, then invokes `queryObjectSink` at absolute slot -5 against a test-hook IUnknown implementation with measured -QueryInterface/AddRef/Release and pointer-slot mutation. This avoids requiring -a live WMI service while testing the actual generated CJS, ESM, and declaration -artifacts. +CI also generates real official safe `IWbemServices`, `IDataObject`, and +`IAudioClient` wrappers plus an `IWinMLEvaluationContextUnsafe` companion. The +test-hook COM implementations measure QueryInterface/AddRef/Release, +conditional output selection, owned storage cleanup, and raw pointer-slot +mutation without requiring live WMI or audio hardware while testing the actual +generated CJS, ESM, and declaration artifacts. Generated companions are outbound only. They do not infer output ownership, provide callbacks or `implement()`, solve acquisition or apartment transfer, or @@ -341,11 +341,11 @@ versus 16 (`WBEM_FLAG_RETURN_IMMEDIATELY`), adopt the requested non-null `+1`, a release dirty failure output. Generic interface InOut parameters remain manual replacement contracts. -**1,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 +**1,428 of 1,432** x64 manual-contract interfaces now have at least one portable +executable generated high-level method. **1,427** have an executable manual 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,067 executable +target. Across the portable generated surface there are **6,048 executable manual methods**, **0 remaining portable manual-classified methods omitted**, and **1,160 runtime-blocked methods** still omitted. @@ -353,20 +353,20 @@ and **1,160 runtime-blocked methods** still omitted. Stage 1 of the [Classic COM contract evidence registry](../architecture/classic-com-contract-evidence-registry.md) -classifies all 5,692 safe-complete interfaces exactly once: +classifies all 5,697 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,336 | -| `exact_registry_dependent` | 356 | +| `standard_derived` | 5,338 | +| `exact_registry_dependent` | 359 | -The registry declares 496 selector-specific entries; all 496 match pinned -metadata, 405 distinct entries are safe-consumed, and safe plans contain 656 -entry/interface plus 405 family/interface dependencies. They also consume -5,976 metadata-attribute and 26,119 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 663 +entry/interface plus 411 family/interface dependencies. They also consume +5,982 metadata-attribute and 26,134 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 173, parameter-direction 45, bounded-two-call 16, -counted-buffer 16, conditional-output 7, flag-selected-buffer 3, null-input 2, +borrowed-handle 54, ownership 177, parameter-direction 45, bounded-two-call 16, +counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 2, semantic-HRESULT 2, and compound-dispatch 1. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. @@ -377,6 +377,10 @@ 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. +`IAudioClient::IsFormatSupported` adds an exact shared/exclusive conditional +output contract, while `GetMixFormat` and +`IAudioClient3::GetCurrentSharedModeEnginePeriod` add exact CoTaskMem-owned +variable-format outputs. The strict embedded registry lives in `tools/dynwinrt-codegen/contracts/classic-com/`. JSON is the sole source for @@ -393,18 +397,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,692 of 7,929 interfaces. The separate outbound raw census -classifies the 2,237 safe-incomplete interfaces as: +the safe census is 5,697 of 7,929 interfaces. The separate outbound raw census +classifies the 2,232 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,437 | 388 | -| i686 | 411 | 1,414 | 412 | -| ARM64 | 412 | 1,437 | 388 | +| x64 | 412 | 1,432 | 388 | +| i686 | 411 | 1,409 | 412 | +| ARM64 | 412 | 1,432 | 388 | -Including safe-complete interfaces, x64 and ARM64 have 6,104 -metadata-complete, 1,437 manual, and 388 blocked interfaces. i686 has 6,103 -metadata-complete, 1,414 manual, and 412 blocked interfaces. +Including safe-complete interfaces, x64 and ARM64 have 6,109 +metadata-complete, 1,432 manual, and 388 blocked interfaces. i686 has 6,108 +metadata-complete, 1,409 manual, and 412 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 @@ -414,14 +418,14 @@ writable/readable `T*` caller-storage contract is runtime-blocked. Thus layout is complete. Cleanup availability is no longer represented by ambiguous booleans. Per -target, 2,237 interfaces require no cleanup, 4,530 use a Phase 1 standard -cleanup, none use a known external cleanup, and 1,162 have unknown cleanup. +target, 2,237 interfaces require no cleanup, 4,533 use a Phase 1 standard +cleanup, none use a known external cleanup, and 1,159 have unknown cleanup. 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,692 safe-complete interfaces, cleanup is derived from the validated +For all 5,697 safe-complete interfaces, cleanup is derived from the validated projected result conversions rather than the raw analyzer. Pure values, borrowed handles, caller buffers, and plain arrays are `none_required`. Managed COM/dynamic-IID adoption, BSTR, HSTRING, CoTaskMem, VARIANT, @@ -508,7 +512,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,692 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,697 of 7,929 addressable COM > interfaces pass complete safe generation. Safe symbols never fall back to an > unsafe implementation; ordinary generation may instead emit an explicitly > named `*Unsafe` outbound companion containing only metadata-complete methods. diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 0bb19500..2f6b70b0 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -80,34 +80,35 @@ "parsed_interface_identities": 7944, "eligible_interfaces": 7929, "not_addressable": 15, - "safe_complete": 5692, - "safe_incomplete": 2237, + "safe_complete": 5697, + "safe_incomplete": 2232, "safeEvidence": { - "safeComplete": 5692, - "standardDerived": 5336, - "exactRegistryDependent": 356, - "metadataFactOccurrences": 5976, - "comStandardFactOccurrences": 26119, - "registeredExactEntries": 496, - "metadataMatchedExactEntries": 496, - "safeConsumedExactEntries": 405, - "exactEntryInterfaceDependencies": 656, - "exactFamilyInterfaceDependencies": 405, + "safeComplete": 5697, + "standardDerived": 5338, + "exactRegistryDependent": 359, + "metadataFactOccurrences": 5982, + "comStandardFactOccurrences": 26134, + "registeredExactEntries": 499, + "metadataMatchedExactEntries": 499, + "safeConsumedExactEntries": 408, + "exactEntryInterfaceDependencies": 663, + "exactFamilyInterfaceDependencies": 411, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, "compound-dispatch": 1, - "conditional-output": 7, + "conditional-output": 10, "counted-buffer": 16, "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 2, - "ownership": 173, + "ownership": 177, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 2 }, "byEntryId": { + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": 3, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.iesisdbcasresponseevent.2017cb03dc0f4c2483ca36307b2cd19f.getresponsedata.slot-11.param-0-pbdata.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.ieslicenserenewalresultevent.d5a48ef5a81b4df0acaa5e35e7ea45d4.getentitlementtoken.slot-17.param-0-pbdata.v1": 1, @@ -372,6 +373,8 @@ "com.ownership.entry.windows-win32-graphics-direct3d-dxc.idxcversioninfo2.fb6904c442f04b629c46983af7da7c83.getcommitinfo.slot-5.param-1-pcommithash.v1": 1, "com.ownership.entry.windows-win32-graphics-direct3d-dxc.idxcversioninfo3.5e13e8439d25473c9ad203b2d0b44b1e.getcustomversionstring.slot-3.param-0-pversionstring.v1": 1, "com.ownership.entry.windows-win32-media-audio-apo.iaudiosystemeffectscustomformats.b1176e34bb7f4f05bebd1b18a534e097.getformatrepresentation.slot-5.param-1-ppwstrformatrep.v1": 1, + "com.ownership.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1": 3, + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudioeffectsmanager.4460b3ae4b44452786767548a8acd260.getaudioeffects.slot-5.param-0-effects.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.getdisplayname.slot-4.param-0-pretval.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.geticonpath.slot-6.param-0-pretval.v1": 1, @@ -515,12 +518,13 @@ "wmi.conditional-output.entry.windows-win32-system-wmi.iwbemservices.9556dc99828c11cfa37e00aa003240c7.putinstance.slot-14.v1": 1 }, "byFamilyId": { + "audio.conditional-output.v1": 3, "automation.idispatch-invoke.v1": 1, "automation.safearray.v1": 121, "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, - "com.ownership.v1": 117, + "com.ownership.v1": 120, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 2, @@ -530,8 +534,8 @@ "wmi.conditional-output.v1": 1 }, "byMetadataAttribute": { - "CanReturnMultipleSuccessValuesAttribute": 43, - "ConstAttribute": 3328, + "CanReturnMultipleSuccessValuesAttribute": 46, + "ConstAttribute": 3331, "FreeWithAttribute": 3, "NativeArrayInfoAttribute": 2602 }, @@ -541,14 +545,32 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5574, + "com.hresult.failure.v1": 5579, "com.interface.input-borrow.v1": 1891, "com.interface.typed-output-plus-one.v1": 3458, - "com.iunknown.identity-refcount.v1": 5692, - "com.query-interface.output-plus-one.v1": 5692, + "com.iunknown.identity-refcount.v1": 5697, + "com.query-interface.output-plus-one.v1": 5697, "com.standard-cleanup.matching-allocator.v1": 1436 }, "exactEntryStatus": { + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": { + "familyId": "audio.conditional-output.v1", + "contractKind": "conditional-output", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "IsFormatSupported", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "8C96A1A91E80657C730E2729DEBC3B708E7B94CC8CF9BAF2F3FD0348237CB186", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-isformatsupported", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": { "familyId": "automation.idispatch-invoke.v1", "contractKind": "compound-dispatch", @@ -6540,6 +6562,42 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.ownership.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetMixFormat", + "slot": 8, + "parameter": null + }, + "sourceFingerprint": "2B32209119D444096A58A1E60C27D3056FACCDC9CD36A3411FBA3CA993537EC4", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getmixformat", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient3", + "iid": "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42", + "method": "GetCurrentSharedModeEnginePeriod", + "slot": 19, + "parameter": null + }, + "sourceFingerprint": "5566DB7A948DDA6FD355EFC15B60BB90F5A932891255E32143C6554DFF920CAF", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-getcurrentsharedmodeengineperiod", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-media-audio.iaudioeffectsmanager.4460b3ae4b44452786767548a8acd260.getaudioeffects.slot-5.param-0-effects.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -10670,27 +10728,27 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6104, - "raw_manual_contract": 1437, + "raw_metadata_complete": 6109, + "raw_manual_contract": 1432, "raw_runtime_blocked": 388, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_manual_contract": 1432, "safe_incomplete_raw_runtime_blocked": 388 }, "i686": { - "raw_metadata_complete": 6103, - "raw_manual_contract": 1414, + "raw_metadata_complete": 6108, + "raw_manual_contract": 1409, "raw_runtime_blocked": 412, "safe_incomplete_raw_metadata_complete": 411, - "safe_incomplete_raw_manual_contract": 1414, + "safe_incomplete_raw_manual_contract": 1409, "safe_incomplete_raw_runtime_blocked": 412 }, "x64": { - "raw_metadata_complete": 6104, - "raw_manual_contract": 1437, + "raw_metadata_complete": 6109, + "raw_manual_contract": 1432, "raw_runtime_blocked": 388, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_manual_contract": 1432, "safe_incomplete_raw_runtime_blocked": 388 } }, @@ -10737,12 +10795,12 @@ }, "manual_reason_counts": { "arm64": { - "external_pointee_storage": 976, - "missing_allocator": 1044, + "external_pointee_storage": 971, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10750,16 +10808,16 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 110, + "pointee_unsupported_packing": 105, "variant_safearray_element_contract": 2 }, "i686": { - "external_pointee_storage": 977, - "missing_allocator": 1044, + "external_pointee_storage": 972, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 534, "opaque_pointee_contract": 289, "pointee_missing_layout": 391, @@ -10767,16 +10825,16 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 146, + "pointee_unsupported_packing": 141, "variant_safearray_element_contract": 2 }, "x64": { - "external_pointee_storage": 976, - "missing_allocator": 1044, + "external_pointee_storage": 971, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10784,7 +10842,7 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 110, + "pointee_unsupported_packing": 105, "variant_safearray_element_contract": 2 } }, @@ -10792,8 +10850,8 @@ "arm64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 @@ -10801,8 +10859,8 @@ "i686": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1090 @@ -10810,8 +10868,8 @@ "x64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 5364de08..f82ed097 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -1414,9 +1414,9 @@ Windows.Win32.Media.Audio,IAudioAutoGainControl,85401fd4-6de4-4b9d-9869-2d6753a8 Windows.Win32.Media.Audio,IAudioBass,a2b1a1d9-4db3-425d-a2b2-bd335cb3e2e5,true,standard_derived, Windows.Win32.Media.Audio,IAudioCaptureClient,c8adbd64-e71e-48a0-a4de-185c395cd317,false,,missing_allocator Windows.Win32.Media.Audio,IAudioChannelConfig,bb11c46f-ec28-493c-b88a-5db88062ce98,true,standard_derived, -Windows.Win32.Media.Audio,IAudioClient,1cb9ad4c-dbfa-4c32-b178-c2f568a703b2,false,,external_pointee_storage -Windows.Win32.Media.Audio,IAudioClient2,726778cd-f60a-4eda-82de-e47610cd78aa,false,,external_pointee_storage -Windows.Win32.Media.Audio,IAudioClient3,7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42,false,,external_pointee_storage +Windows.Win32.Media.Audio,IAudioClient,1cb9ad4c-dbfa-4c32-b178-c2f568a703b2,true,exact_registry_dependent, +Windows.Win32.Media.Audio,IAudioClient2,726778cd-f60a-4eda-82de-e47610cd78aa,true,exact_registry_dependent, +Windows.Win32.Media.Audio,IAudioClient3,7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42,true,exact_registry_dependent, Windows.Win32.Media.Audio,IAudioClientDuckingControl,c789d381-a28c-4168-b28f-d3a837924dc3,true,standard_derived, Windows.Win32.Media.Audio,IAudioClock,cd63314f-3fba-4a1b-812c-ef96358728e7,true,standard_derived, Windows.Win32.Media.Audio,IAudioClock2,6f49ff73-6727-49ac-a008-d98cf5e70048,true,standard_derived, @@ -1491,7 +1491,7 @@ Windows.Win32.Media.DeviceManager,IComponentAuthenticate,a9889c00-6d2b-11d3-8496 Windows.Win32.Media.DeviceManager,IMDSPDevice,1dcb3a12-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice2,420d16ad-c97d-4e00-82aa-00e9f4335ddd,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice3,1a839845-fc55-487c-976f-ee38ac0e8c4e,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage +Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPDirectTransfer,c2fe57a8-9304-478c-9ee4-47e397b912d7,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumDevice,1dcb3a11-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumStorage,1dcb3a15-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, @@ -1519,7 +1519,7 @@ Windows.Win32.Media.DeviceManager,ISCPSession,88a3e6ed-eee4-4619-bbb3-fd4fb62715 Windows.Win32.Media.DeviceManager,IWMDMDevice,1dcb3a02-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice2,e34f3d37-9d67-4fc1-9252-62d28b2f8b55,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice3,6c03e4fe-05db-4dda-9e3c-06233a6d5d65,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage +Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMDeviceSession,82af0a65-9d96-412c-83e5-3c43e4b06cc7,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumDevice,1dcb3a01-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumStorage,1dcb3a05-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 428b23af..144325bf 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_692); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_692); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_336); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 356); + assert_eq!(report.summary.safe_complete, 5_697); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_697); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_338); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 359); 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_976 + 5_982 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_119 + 26_134 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 496); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 499); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 496 + 499 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 405 + 408 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 656 + 663 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 405 + 411 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4605,12 +4605,12 @@ mod tests { ("borrowed-handle".into(), 54), ("bounded-two-call".into(), 16), ("compound-dispatch".into(), 1), - ("conditional-output".into(), 7), + ("conditional-output".into(), 10), ("counted-buffer".into(), 16), ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 2), - ("ownership".into(), 173), + ("ownership".into(), 177), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 2), @@ -4618,7 +4618,11 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 117 + 120 + ); + assert_eq!( + report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], + 3 ); assert_eq!( report.summary.safe_evidence.by_family_id["windows.borrowed-hwnd-output.v1"], @@ -4632,7 +4636,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(), 405); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 408); assert!( report .summary @@ -4677,7 +4681,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 405 + 408 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( @@ -4708,6 +4712,13 @@ mod tests { .count(), 1 ); + assert_eq!( + status + .values() + .filter(|entry| entry.family_id == "audio.conditional-output.v1") + .count(), + 1 + ); assert!(status.values().all(|entry| { entry.source_fingerprint.len() == 64 && entry @@ -4827,7 +4838,7 @@ mod tests { ), ( 412 - usize::from(target == CensusTarget::I686), - 1_437 - 23 * usize::from(target == CensusTarget::I686), + 1_432 - 23 * usize::from(target == CensusTarget::I686), 388 + 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 c964c32b..c878c952 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -2319,13 +2319,13 @@ mod tests { }; let coverage = measure_stage2_coverage(&winmd).unwrap(); println!("{}", serde_json::to_string(&coverage).unwrap()); - assert_eq!(coverage.x64_manual_interfaces, 1_437); - assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_433); + assert_eq!(coverage.x64_manual_interfaces, 1_432); + assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_428); assert_eq!( coverage.x64_manual_interfaces_with_executable_manual_method, - 1_432 + 1_427 ); - assert_eq!(coverage.executable_manual_methods, 6_067); + assert_eq!(coverage.executable_manual_methods, 6_048); assert_eq!(coverage.remaining_manual_methods, 0); assert_eq!(coverage.runtime_blocked_methods, 1_160); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 0cf90159..804343ef 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -215,6 +215,7 @@ pub(super) enum ComType { StatStg, FormatEtc, StgMedium, + AudioFormat, ManagedInterface { iid: String, }, @@ -314,6 +315,7 @@ pub(super) enum ResultConversion { StatStg, FormatEtc, StgMedium, + AudioFormat, MallocAllocation, MallocReallocation, } @@ -459,6 +461,10 @@ pub(super) enum ProjectedComMethodKind { DataObjectSetData { release_param_index: usize, }, + AudioFormatSupport { + share_mode_param_index: usize, + closest_match_param_index: usize, + }, } /// The JS runtime `typeof`/shape category a validated value uses at a call @@ -578,7 +584,8 @@ pub(super) fn dispatch_shape(typ: &ComType) -> Option { ComType::ManagedInterface { .. } | ComType::DispatchParams | ComType::FormatEtc - | ComType::StgMedium => Some(DispatchShape::Object), + | ComType::StgMedium + | ComType::AudioFormat => 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 b28f813d..5be8b430 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -456,6 +456,9 @@ fn render_js(meta: &ProjectedComInterface) -> String { ProjectedComMethodKind::ConditionalInterfaceOutput { .. } => { emit_conditional_interface_output_method_js(&mut out, method, &iface_var) } + ProjectedComMethodKind::AudioFormatSupport { .. } => { + emit_audio_format_support_method_js(&mut out, method, &iface_var) + } } } out.push_str("}\n"); @@ -890,6 +893,7 @@ fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComTyp | ResultConversion::StatStg | ResultConversion::FormatEtc | ResultConversion::StgMedium + | ResultConversion::AudioFormat | ResultConversion::MallocAllocation | ResultConversion::MallocReallocation, ) @@ -911,6 +915,85 @@ fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str emit_method_js_named(out, method, iface_var, &method.camel_name); } +fn emit_audio_format_support_method_js( + out: &mut String, + method: &ProjectedComMethod, + iface_var: &str, +) { + let ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index, + closest_match_param_index, + } = method.kind + else { + unreachable!("audio format support emitter requires exact method semantics") + }; + let inputs = input_params(method); + let params = inputs + .iter() + .enumerate() + .map(|(surface, (_, param))| js_param_name(¶m.name, surface)) + .collect::>(); + let share_mode_surface = inputs + .iter() + .position(|(index, _)| *index == share_mode_param_index) + .expect("audio share mode must be a visible input"); + let share_mode_name = ¶ms[share_mode_surface]; + emit_method_doc_js(out, &method.doc); + out.push_str(&format!( + " {}({}) {{\n", + method.camel_name, + params.join(", ") + )); + out.push_str(&format!( + " if ({share_mode_name} !== 0 && {share_mode_name} !== 1) throw new RangeError('AUDCLNT_SHAREMODE must be 0 (shared) or 1 (exclusive)');\n" + )); + out.push_str(&format!( + " const _requestClosest = {share_mode_name} === 0;\n" + )); + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == closest_match_param_index { + return Some("DynCom.boolValue(_requestClosest)".into()); + } + if !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible audio input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + out.push_str(&format!( + " const _r = {iface_var}.method({}).invokeAll(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + let status = unwrap_method_result_js(method, &method.results[0], "_r[0]"); + out.push_str(&format!(" const _status = {status};\n")); + out.push_str( + " const _closest = _requestClosest ? DynCom.takeNullableAudioFormat(_r[1]) : null;\n", + ); + out.push_str( + " if (_status !== 0 && _status !== 1) throw new Error(`Unexpected IsFormatSupported success HRESULT ${_status}`);\n", + ); + out.push_str( + " if (_status === 1 && _closest === null) throw new Error('IsFormatSupported returned S_FALSE without a closest shared-mode format');\n", + ); + out.push_str( + " if (_status === 0 && _closest !== null) throw new Error('IsFormatSupported returned S_OK with an unexpected closest format');\n", + ); + out.push_str(" return [_status, _closest];\n"); + out.push_str(" }\n"); +} + fn emit_dispatch_invoke_method_js( out: &mut String, method: &ProjectedComMethod, @@ -2423,6 +2506,10 @@ fn render_dts(meta: &ProjectedComInterface) -> String { | ProjectedComMethodKind::DataObjectSetData { .. } => { (dts_params(method), dts_return_type(method)) } + ProjectedComMethodKind::AudioFormatSupport { .. } => ( + dts_params(method), + "readonly [number, DynComAudioFormat | null]".into(), + ), ProjectedComMethodKind::CallerSuppliedDynamicIid { iid_param_index, .. } => ( @@ -2638,6 +2725,7 @@ fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, Pointer | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } @@ -2740,6 +2828,7 @@ fn collect_native_pods(meta: &ProjectedComInterface) -> Vec {} @@ -2836,6 +2925,9 @@ fn collect_runtime_types(meta: &ProjectedComInterface) -> Vec<&'static str> { ComType::StgMedium => { types.insert("DynComStgMedium"); } + ComType::AudioFormat => { + types.insert("DynComAudioFormat"); + } ComType::AllocatorPointer | ComType::ConsumedAllocatorPointer | ComType::InspectedAllocatorPointer => { @@ -2916,6 +3008,7 @@ fn collect_scalar_alias( | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs index b5f2d095..4efe660a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -62,6 +62,7 @@ pub(super) fn abi_type_js(typ: &ComType) -> String { ComType::StatStg => "DynCom.statStgType()".into(), ComType::FormatEtc => "DynCom.formatEtcType()".into(), ComType::StgMedium => "DynCom.stgMediumType()".into(), + ComType::AudioFormat => "DynCom.audioFormatType()".into(), ComType::ManagedInterface { iid } => { format!("DynCom.interfaceType(WinGuid.parse('{iid}'))") } @@ -162,6 +163,7 @@ pub(super) fn type_dts(typ: &ComType) -> String { ComType::StatStg => "DynComStatStg".into(), ComType::FormatEtc => "DynComFormatEtc".into(), ComType::StgMedium => "DynComStgMedium".into(), + ComType::AudioFormat => "DynComAudioFormat".into(), ComType::ManagedInterface { .. } => "DynWinRtValue".into(), ComType::CoTaskMemWideString => "string".into(), ComType::StringArray { .. } => "string[]".into(), @@ -214,6 +216,7 @@ pub(super) fn result_type_dts(result: &ProjectedComResult) -> String { ResultConversion::StatStg => "DynComStatStg".into(), ResultConversion::FormatEtc => "DynComFormatEtc".into(), ResultConversion::StgMedium => "DynComStgMedium".into(), + ResultConversion::AudioFormat => "DynComAudioFormat".into(), ResultConversion::MallocAllocation | ResultConversion::MallocReallocation => { "DynComAllocation | null".into() } @@ -297,6 +300,7 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { ComType::StatStg => unreachable!("STATSTG is output-only"), ComType::FormatEtc => format!("DynCom.formatEtc({variable})"), ComType::StgMedium => format!("DynCom.stgMedium({variable})"), + ComType::AudioFormat => format!("DynCom.audioFormat({variable})"), ComType::ManagedInterface { .. } => variable.to_string(), ComType::CoTaskMemWideString => { unreachable!("CoTaskMem string elements are output-only") @@ -384,6 +388,7 @@ pub(super) fn unwrap_result_js(result: &ProjectedComResult, expression: &str) -> ResultConversion::StatStg => format!("DynCom.takeStatStg({expression})"), ResultConversion::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), ResultConversion::StgMedium => format!("DynCom.takeStgMedium({expression})"), + ResultConversion::AudioFormat => format!("DynCom.takeAudioFormat({expression})"), ResultConversion::MallocAllocation => { format!("DynCom.takeMallocAllocation(this._obj, {expression})") } @@ -479,6 +484,7 @@ fn unwrap_value_js(typ: &ComType, expression: &str) -> String { ComType::StatStg => format!("DynCom.takeStatStg({expression})"), ComType::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), ComType::StgMedium => format!("DynCom.takeStgMedium({expression})"), + ComType::AudioFormat => format!("DynCom.takeAudioFormat({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 1f25b57e..4c0a8c58 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs @@ -167,6 +167,7 @@ pub(in crate::codegen::com) enum ComAbiType { StatStg, FormatEtc, StgMedium, + AudioFormat, 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 62b3fb6e..d0a59532 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -439,6 +439,18 @@ fn map_method( ), }) } + Some(RawExactMethodContractKind::AudioFormatOwnedOutput) => method, + Some(RawExactMethodContractKind::AudioFormatSupport) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::AudioFormatSupport { + share_mode_param: ParamIndex::new( + contract + .discriminator_param_index + .expect("validated audio share-mode discriminator"), + ), + closest_match_param: ParamIndex::new(contract.buffer_param_index), + }) + } None => method, } }; @@ -511,6 +523,28 @@ fn map_param( )?, None, ) + } else if matches!( + &raw.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Media.Audio" + && name == "WAVEFORMATEX" + && matches!(raw.typ.pointer_depth, 1 | 2) + ) { + ( + insert_abi( + model, + Some(QualifiedName::new( + "Windows.Win32.Media.Audio", + "WAVEFORMATEX", + )?), + None, + ComAbiType::AudioFormat, + )?, + None, + ) } else if matches!( &raw.typ.native_type, RawNativeType::Named { @@ -1017,6 +1051,7 @@ pub(in crate::codegen::com) fn census_raw_base_category(raw: &RawComType) -> &'s ComAbiType::StatStg => "StatStg", ComAbiType::FormatEtc => "FormatEtc", ComAbiType::StgMedium => "StgMedium", + ComAbiType::AudioFormat => "AudioFormat", ComAbiType::FunctionPointer(_) => "FunctionPointer", ComAbiType::Unknown(_) => "Unknown", }; @@ -1520,6 +1555,7 @@ fn validate_pod_field_type( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)), } @@ -1591,6 +1627,7 @@ fn abi_size_alignment( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::Unknown(_) => { return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); } @@ -1810,6 +1847,7 @@ fn buffer_element_ownership( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => BufferElementOwnership::Unknown, }; @@ -1952,12 +1990,37 @@ fn map_ownership( ComAbiType::StgMedium if direction == Direction::Out => { Ok((ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium)) } + ComAbiType::AudioFormat + if direction == Direction::Out + && raw_method.exact_contract.as_ref().is_some_and(|contract| { + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) && contract.buffer_param_index == param_index + }) => + { + Ok(( + ComOwnership::AudioFormatOwned, + Cleanup::CoTaskMemAudioFormat, + )) + } + ComAbiType::AudioFormat if direction == Direction::Out => Err(ModelError::Unsupported( + UnsupportedReason::Other( + "WAVEFORMATEX output requires exact CoTaskMem ownership evidence".into(), + ), + )), ComAbiType::FormatEtc if direction == Direction::InOut => Err( ModelError::Unsupported(UnsupportedReason::Other( "FORMATETC in/out requires a dedicated replacement contract".into(), )), ), - ComAbiType::FormatEtc | ComAbiType::StgMedium => { + ComAbiType::AudioFormat if direction == Direction::InOut => Err( + ModelError::Unsupported(UnsupportedReason::Other( + "WAVEFORMATEX in/out requires a dedicated replacement contract".into(), + )), + ), + ComAbiType::FormatEtc | ComAbiType::StgMedium | ComAbiType::AudioFormat => { Ok((ComOwnership::Borrowed, Cleanup::None)) } ComAbiType::DispatchParams if direction == Direction::Out => Err( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index abeed3ce..4e941f40 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -56,6 +56,10 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { DataObjectSetData { release_param: ParamIndex, }, + AudioFormatSupport { + share_mode_param: ParamIndex, + closest_match_param: ParamIndex, + }, Malloc, } @@ -170,6 +174,7 @@ impl ComMethodContract { | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat ) { return Err(ModelError::InvalidContract(format!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs index 8cf5b0f6..29f48c29 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs @@ -35,6 +35,7 @@ pub(in crate::codegen::com) enum ComOwnership { StatStgOwned, FormatEtcOwned, StgMediumOwned, + AudioFormatOwned, LocalOwned, HandleOwned(HandleCleanup), CustomOwned(CleanupId), @@ -55,6 +56,7 @@ pub(in crate::codegen::com) enum Cleanup { StatStgClear, FormatEtcClear, ReleaseStgMedium, + CoTaskMemAudioFormat, LocalFree, Handle(HandleCleanup), Custom(CleanupId), @@ -117,6 +119,7 @@ pub(super) fn validate_ownership_cleanup( | (ComOwnership::StatStgOwned, Cleanup::StatStgClear) | (ComOwnership::FormatEtcOwned, Cleanup::FormatEtcClear) | (ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium) + | (ComOwnership::AudioFormatOwned, Cleanup::CoTaskMemAudioFormat) | (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 b8a52195..c5f35c4c 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -509,6 +509,7 @@ fn validate_projected_surface_names(meta: &ProjectedComInterface) -> Result<(), | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} @@ -695,6 +696,13 @@ fn project_method( release_param_index: release_param.index(), } } + Some(ComMethodSpecialContract::AudioFormatSupport { + share_mode_param, + closest_match_param, + }) => ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index: share_mode_param.index(), + closest_match_param_index: closest_match_param.index(), + }, Some(ComMethodSpecialContract::Malloc) | None => project_dynamic_method_kind( method.name(), dynamic_iid.map(|contract| { @@ -856,6 +864,13 @@ fn project_method( fetched_param_index, .. } if *fetched_param_index == index + ) + || matches!( + &kind, + ProjectedComMethodKind::AudioFormatSupport { + closest_match_param_index, + .. + } if *closest_match_param_index == index )) => { ComParamDirection::OptionalOut @@ -1066,6 +1081,17 @@ fn project_method( ProjectedComMethodKind::ConditionalInterfaceOutput { .. } ) { // The exact mode contract controls which optional output is requested. + } else if let ProjectedComMethodKind::AudioFormatSupport { + closest_match_param_index, + .. + } = kind + { + if optional_outputs != [closest_match_param_index] { + return Err(format!( + "{}: audio format support requires exactly its closest-match optional output", + context() + )); + } } else { if interface_namespace != "Windows.Win32.System.Com" || interface_name != "IDispatch" @@ -1277,6 +1303,43 @@ fn project_method( } } + if let ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index, + closest_match_param_index, + } = kind + && (return_convention != ComReturnConvention::SemanticHResult + || !matches!( + params.get(share_mode_param_index), + Some(ProjectedComParam { + typ: ComType::Enum { + underlying: ComEnumUnderlying::I32, + .. + }, + direction: ComParamDirection::In, + surface_input: true, + .. + }) + ) + || !matches!( + params.get(closest_match_param_index), + Some(ProjectedComParam { + typ: ComType::AudioFormat, + direction: ComParamDirection::OptionalOut, + surface_result: true, + .. + }) + ) + || results.len() != 2 + || results[0].source != ResultSource::DirectReturn + || results[1].source != ResultSource::Param(closest_match_param_index) + || results[1].conversion != ResultConversion::AudioFormat) + { + return Err(format!( + "{}: audio format support no longer matches its exact projected result contract", + context() + )); + } + Ok(ProjectedComMethod { name: method.name().into(), camel_name: camel_case(method.name()), @@ -1662,6 +1725,7 @@ fn project_value_type( ComAbiType::StatStg => Ok(ComType::StatStg), ComAbiType::FormatEtc => Ok(ComType::FormatEtc), ComAbiType::StgMedium => Ok(ComType::StgMedium), + ComAbiType::AudioFormat => Ok(ComType::AudioFormat), ComAbiType::NativeUnion(_) | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => { Err(format!( "unsupported Classic-COM semantic type {}", @@ -2064,6 +2128,7 @@ fn project_native_pod_field_type( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(format!( "unsupported nested native POD field {}", @@ -2849,6 +2914,11 @@ fn result_conversion( { Ok(ResultConversion::StgMedium) } + (ComOwnership::AudioFormatOwned, Cleanup::CoTaskMemAudioFormat) + if matches!(typ, ComType::AudioFormat) => + { + Ok(ResultConversion::AudioFormat) + } (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 9b47f1c4..118d32ca 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -382,6 +382,8 @@ pub enum RawExactMethodContractKind { Malloc, FlagSelectedString, DataObjectSetData, + AudioFormatOwnedOutput, + AudioFormatSupport, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -414,9 +416,13 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::DataObjectSetData => { + | RawExactMethodContractKind::DataObjectSetData + | RawExactMethodContractKind::AudioFormatOwnedOutput => { crate::contract_registry::ExactFamilyId::Ownership } + RawExactMethodContractKind::AudioFormatSupport => { + crate::contract_registry::ExactFamilyId::AudioConditionalOutput + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ExactFamilyId::ShellCommandString } @@ -444,9 +450,13 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::DataObjectSetData => { + | RawExactMethodContractKind::DataObjectSetData + | RawExactMethodContractKind::AudioFormatOwnedOutput => { crate::contract_registry::ContractKind::Ownership } + RawExactMethodContractKind::AudioFormatSupport => { + crate::contract_registry::ContractKind::ConditionalOutput + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ContractKind::FlagSelectedBuffer } @@ -2181,6 +2191,8 @@ fn apply_exact_method_contract( RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} RawExactMethodContractKind::DataObjectSetData => {} + RawExactMethodContractKind::AudioFormatOwnedOutput => {} + RawExactMethodContractKind::AudioFormatSupport => {} RawExactMethodContractKind::FlagSelectedString => { let buffer = contract.buffer_param_index; let capacity = contract.capacity_param_index; @@ -2334,6 +2346,30 @@ fn registered_exact_method_contract( "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.Media.Audio", "IAudioClient", "IsFormatSupported") => ( + RawExactMethodContractKind::AudioFormatSupport, + 2, + 0, + None, + "IAudioClient::IsFormatSupported requests a closest-match output only for shared mode and returns that format with CoTaskMem ownership", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-isformatsupported", + ), + ("Windows.Win32.Media.Audio", "IAudioClient", "GetMixFormat") => ( + RawExactMethodContractKind::AudioFormatOwnedOutput, + 0, + 0, + None, + "IAudioClient::GetMixFormat returns variable-length WAVEFORMATEX storage allocated with CoTaskMem", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getmixformat", + ), + ("Windows.Win32.Media.Audio", "IAudioClient3", "GetCurrentSharedModeEnginePeriod") => ( + RawExactMethodContractKind::AudioFormatOwnedOutput, + 0, + 0, + None, + "IAudioClient3::GetCurrentSharedModeEnginePeriod returns variable-length WAVEFORMATEX storage allocated with CoTaskMem", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-getcurrentsharedmodeengineperiod", + ), ("Windows.Win32.Graphics.Dxgi", "IDXGIObject", "GetPrivateData") => ( RawExactMethodContractKind::UnsafePrivateData, 2, @@ -2402,6 +2438,7 @@ fn registered_exact_method_contract( "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", "IStream" | "IDataObject" => "Windows.Win32.System.Com", + "IAudioClient" | "IAudioClient3" => "Windows.Win32.Media.Audio", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", "IContextMenu" => "Windows.Win32.UI.Shell", "IMalloc" => "Windows.Win32.System.Com", @@ -2421,6 +2458,8 @@ fn registered_exact_method_contract( "IContextMenu" => "IContextMenu", "IMalloc" => "IMalloc", "IDataObject" => "IDataObject", + "IAudioClient" => "IAudioClient", + "IAudioClient3" => "IAudioClient3", _ => unreachable!("matched exact method interface"), }, declaring_iid: match kind { @@ -2447,6 +2486,18 @@ fn registered_exact_method_contract( "000214e4-0000-0000-c000-000000000046" } RawExactMethodContractKind::DataObjectSetData => "0000010e-0000-0000-c000-000000000046", + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + if interface == "IAudioClient" => + { + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2" + } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42" + } + RawExactMethodContractKind::AudioFormatSupport => { + unreachable!("audio format support belongs to IAudioClient") + } }, method_name: match kind { RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", @@ -2463,6 +2514,12 @@ fn registered_exact_method_contract( }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", RawExactMethodContractKind::DataObjectSetData => "SetData", + RawExactMethodContractKind::AudioFormatOwnedOutput => match method { + "GetMixFormat" => "GetMixFormat", + "GetCurrentSharedModeEnginePeriod" => "GetCurrentSharedModeEnginePeriod", + _ => unreachable!("matched exact audio format output"), + }, + RawExactMethodContractKind::AudioFormatSupport => "IsFormatSupported", }, vtable_index: match (interface, method) { ("IMFAttributes", "GetBlob") => 15, @@ -2482,19 +2539,38 @@ fn registered_exact_method_contract( ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, ("IDataObject", "SetData") => 7, + ("IAudioClient", "IsFormatSupported") => 7, + ("IAudioClient", "GetMixFormat") => 8, + ("IAudioClient3", "GetCurrentSharedModeEnginePeriod") => 19, _ => unreachable!("matched exact method identity"), }, buffer_param_index: buffer, capacity_param_index: capacity, actual_length_param_index: actual, - discriminator_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) - .then_some(1), + discriminator_param_index: match kind { + RawExactMethodContractKind::FlagSelectedString => Some(1), + RawExactMethodContractKind::AudioFormatSupport => Some(0), + _ => None, + }, reserved_null_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) .then_some(2), ownership_transfer_param_index: (kind == RawExactMethodContractKind::DataObjectSetData) .then_some(2), - source_fingerprint: (kind == RawExactMethodContractKind::DataObjectSetData) - .then_some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1"), + source_fingerprint: match (interface, method) { + ("IDataObject", "SetData") => { + Some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1") + } + ("IAudioClient", "IsFormatSupported") => { + Some("8C96A1A91E80657C730E2729DEBC3B708E7B94CC8CF9BAF2F3FD0348237CB186") + } + ("IAudioClient", "GetMixFormat") => { + Some("2B32209119D444096A58A1E60C27D3056FACCDC9CD36A3411FBA3CA993537EC4") + } + ("IAudioClient3", "GetCurrentSharedModeEnginePeriod") => { + Some("5566DB7A948DDA6FD355EFC15B60BB90F5A932891255E32143C6554DFF920CAF") + } + _ => None, + }, citation, reason, }) @@ -2830,6 +2906,19 @@ pub(crate) fn validate_exact_method_contract( }) && raw_hresult(&raw.return_type) } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + if contract.method_name == "GetMixFormat" { + raw_method_shape(raw) + == "GetMixFormat@8(ppDeviceFormat:out:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } else { + raw_method_shape(raw) + == "GetCurrentSharedModeEnginePeriod@19(ppFormat:out:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/Mutable,pCurrentPeriodInFrames:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } + } + RawExactMethodContractKind::AudioFormatSupport => { + raw_method_shape(raw) + == "IsFormatSupported@7(ShareMode:in:required:noconstattr:Windows.Win32.Media.Audio.AUDCLNT_SHAREMODE[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,pFormat:in:required:constattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr1/Mutable,ppClosestMatch:out:optional:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/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 @@ -2859,9 +2948,20 @@ pub(crate) fn validate_exact_method_contract( && contract.discriminator_param_index.is_none() && contract.reserved_null_param_index.is_none() } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + contract.buffer_param_index == 0 + && contract.discriminator_param_index.is_none() + && contract.ownership_transfer_param_index.is_none() + } + RawExactMethodContractKind::AudioFormatSupport => { + contract.buffer_param_index == 2 + && contract.discriminator_param_index == Some(0) + && contract.ownership_transfer_param_index.is_none() + } }; if !valid_shape - || raw.semantic_hresult.is_some() + || (raw.semantic_hresult.is_some() + && contract.kind != RawExactMethodContractKind::AudioFormatSupport) || raw.enumerator_next.is_some() || !indices_valid { @@ -4998,6 +5098,95 @@ mod tests { .unwrap(); } + #[test] + fn audio_format_exact_contracts_are_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.Media.Audio", "IAudioClient3").unwrap(); + let actual = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter_map(|raw| { + let contract = raw.exact_contract.as_ref()?; + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) + .then(|| { + let mut source = raw.clone(); + source.exact_contract = None; + ( + raw.metadata_name.clone(), + raw_method_fingerprint(&source), + contract.source_fingerprint.unwrap().to_string(), + ) + }) + }) + .collect::>(); + assert_eq!( + actual + .iter() + .map(|(name, _, _)| name.as_str()) + .collect::>(), + [ + "IsFormatSupported", + "GetMixFormat", + "GetCurrentSharedModeEnginePeriod" + ] + ); + for (_, fingerprint, expected) in actual { + assert_eq!(fingerprint, expected); + } + for raw in interface.raw_methods.as_ref().unwrap() { + let Some(contract) = raw.exact_contract.as_ref().filter(|contract| { + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) + }) else { + continue; + }; + if let Err(error) = validate_exact_method_contract( + contract.declaring_namespace, + contract.declaring_interface, + contract.declaring_iid, + raw, + contract, + ) { + panic!("{error}: {}", raw_method_shape(raw)); + } + } + let mut drift = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|raw| raw.metadata_name == "IsFormatSupported") + .unwrap() + .clone(); + drift.params[2].optional = false; + let contract = drift.exact_contract.clone().unwrap(); + assert!( + validate_exact_method_contract( + contract.declaring_namespace, + contract.declaring_interface, + contract.declaring_iid, + &drift, + &contract, + ) + .is_err() + ); + } + #[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 426e3767..a87b8e99 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -94,6 +94,7 @@ pub enum ExactFamilyId { ReservedNullInput, ParameterDirection, ShellCommandString, + AudioConditionalOutput, } impl ExactFamilyId { @@ -113,6 +114,7 @@ impl ExactFamilyId { Self::ReservedNullInput => "com.reserved-null-input.v1", Self::ParameterDirection => "com.parameter-direction.v1", Self::ShellCommandString => "shell.flag-selected-string.v1", + Self::AudioConditionalOutput => "audio.conditional-output.v1", } } @@ -132,6 +134,7 @@ impl ExactFamilyId { Self::ReservedNullInput, Self::ParameterDirection, Self::ShellCommandString, + Self::AudioConditionalOutput, ] .into_iter() .find(|family| family.id() == value) @@ -475,12 +478,15 @@ pub(crate) fn statically_declared_exact_entry_ids() -> Result, } const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1", "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1", "buffers.bounded-two-call.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getblob.slot-15.v1", "buffers.bounded-two-call.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.getrecorderguid.slot-4.param-0-pbyuniqueid.v1", "buffers.counted-buffer.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.init.slot-3.param-0-pbyuniqueid.v1", "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-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1", + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.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.setdata.slot-7.v1", "com.ownership.entry.windows-win32-system-com.imalloc.0000000200000000c000000000000046.alloc.slot-3.v1", @@ -1140,7 +1146,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(), 496); + 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 903cecd0..049f2557 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2190,6 +2190,39 @@ fn data_object_projects_hglobal_format_and_medium_values() { assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); } +#[test] +fn audio_clients_project_variable_wave_formats_and_exact_ownership() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + for name in ["IAudioClient", "IAudioClient2", "IAudioClient3"] { + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.Media.Audio", name) + .unwrap_or_else(|| panic!("{name} must exist")); + let output = com::generate_com_interface_files(&interface, &win32_winmd()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert!(output.dts.contains("DynComAudioFormat")); + assert!(!output.js.contains("UnsafePointee")); + assert!(!output.js.contains("UnsafePointerOutput")); + assert!(output.js.contains("DynCom.audioFormatType()")); + assert!(output.js.contains("DynCom.takeAudioFormat")); + assert!(!output.js.contains("static implementation(handlers)")); + assert!(output.dts.contains( + "isFormatSupported(shareMode: AUDCLNT_SHAREMODE, pFormat: DynComAudioFormat): readonly [number, DynComAudioFormat | null];" + )); + assert!(output.js.contains("DynCom.boolValue(_requestClosest)")); + assert!(output.js.contains("DynCom.takeNullableAudioFormat(_r[1])")); + if name == "IAudioClient3" { + assert!( + output + .dts + .contains("getCurrentSharedModeEnginePeriod(): [DynComAudioFormat, number];") + ); + } + } +} + #[test] fn high_value_exact_contracts_generate_complete_safe_interfaces() { if !win32_available() { @@ -4997,9 +5030,9 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { "--winmd", &win32_winmd(), "--namespace", - "Windows.Win32.Media.Audio", + "Windows.Win32.AI.MachineLearning.WinML", "--class-name", - "IAudioClient", + "IWinMLEvaluationContext", "--output", output.to_str().unwrap(), ]); @@ -5019,13 +5052,15 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { "{}", String::from_utf8_lossy(&first.stderr) ); - assert!(String::from_utf8_lossy(&first.stdout).contains("Generated IAudioClientUnsafe")); + assert!( + String::from_utf8_lossy(&first.stdout).contains("Generated IWinMLEvaluationContextUnsafe") + ); let unsafe_dir = output_dir.join("com").join("unsafe"); - let class_module = "windows/win32/media/audio/IAudioClientUnsafe"; + let class_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe"; let retained = [ - "windows/win32/media/audio/IAudioClientUnsafe.js", - "windows/win32/media/audio/IAudioClientUnsafe.d.ts", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.d.ts", "index.js", "index.mjs", "index.d.ts", @@ -5043,8 +5078,8 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { let js = fs::read_to_string(unsafe_dir.join(format!("{class_module}.js"))).unwrap(); let dts = fs::read_to_string(unsafe_dir.join(format!("{class_module}.d.ts"))).unwrap(); - assert!(js.contains("class IAudioClientUnsafe")); - assert!(js.contains("isFormatSupported(")); + assert!(js.contains("class IWinMLEvaluationContextUnsafe")); + assert!(js.contains("getValueByName(")); assert!(!js.contains("implement(") && !js.contains("implementation")); assert!(dts.contains("private constructor()")); assert!(dts.contains("static from(value: DynWinRtValue")); @@ -5056,7 +5091,7 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { assert_eq!(support["interfaces"][0]["modulePath"], class_module); let methods = support["interfaces"][0]["methods"].as_array().unwrap(); assert!(methods.iter().any(|method| { - method["name"] == "IsFormatSupported" && method["status"] == "raw_manual_contract" + method["name"] == "GetValueByName" && method["status"] == "raw_manual_contract" })); assert!(!output_dir.join("index.js").exists()); @@ -5069,7 +5104,7 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { assert!( !fs::read_to_string(path) .unwrap() - .contains("IAudioClientUnsafe") + .contains("IWinMLEvaluationContextUnsafe") ); } @@ -5117,10 +5152,10 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { remove_com_generation_lock(&output); let cases = [ ( - "Windows.Win32.Media.Audio", - "IAudioClient", - "windows/win32/media/audio/IAudioClientUnsafe", - "isFormatSupported(ShareMode: number, pFormat: UnsafePointee, ppClosestMatch: UnsafePointerOutput): readonly [number, T0]", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe", + "getValueByName(Name: DynComRawMemory | DynComRawPointer, pDescriptor: UnsafePointerOutput): T0", ), ( "Windows.Win32.Graphics.Dxgi", @@ -5177,21 +5212,24 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { ) .unwrap(); assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); - let audio = support["interfaces"] + let evaluation = support["interfaces"] .as_array() .unwrap() .iter() - .find(|interface| interface["interfaceName"] == "Windows.Win32.Media.Audio.IAudioClient") + .find(|interface| { + interface["interfaceName"] + == "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext" + }) .unwrap(); - let format = audio["methods"] + let output_method = evaluation["methods"] .as_array() .unwrap() .iter() - .find(|method| method["name"] == "IsFormatSupported") + .find(|method| method["name"] == "GetValueByName") .unwrap(); - assert_eq!(format["status"], "raw_manual_contract"); + assert_eq!(output_method["status"], "raw_manual_contract"); assert_eq!( - format["strategyRequirements"] + output_method["strategyRequirements"] .as_array() .unwrap() .iter() @@ -5200,15 +5238,22 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { requirement["strategy"].as_str().unwrap() )) .collect::>(), - vec![ - ("pFormat", "UnsafePointee"), - ("ppClosestMatch", "UnsafePointerOutput") - ] + vec![("pDescriptor", "UnsafePointerOutput")] ); - assert_eq!(format["strategyRequirements"][0]["direction"], "in"); - assert_eq!(format["strategyRequirements"][0]["nullable"], false); + let input_method = evaluation["methods"] + .as_array() + .unwrap() + .iter() + .find(|method| method["name"] == "BindValue") + .unwrap(); + assert_eq!( + input_method["strategyRequirements"][0]["strategy"], + "UnsafePointee" + ); + assert_eq!(input_method["strategyRequirements"][0]["direction"], "in"); + assert_eq!(input_method["strategyRequirements"][0]["nullable"], false); assert_eq!( - format["strategyRequirements"][0]["pointeeLayouts"], + input_method["strategyRequirements"][0]["pointeeLayouts"], serde_json::json!({"arm64": null, "i686": null, "x64": null}) ); assert!( @@ -5230,7 +5275,7 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { ) .unwrap(); for root in [ - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Graphics.Dxgi.IDXGIObject", "Windows.Win32.System.ClrHosting.IHostMalloc", "Windows.Win32.Devices.Fax.IStiDeviceControl", @@ -5339,7 +5384,7 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { ); let unsafe_dir = output_dir.join("com").join("unsafe"); let mf_module = "windows/win32/media/media-foundation/MFASYNCRESULTUnsafe"; - let unsafe_module = "windows/win32/media/audio/IAudioClientUnsafe"; + let unsafe_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe"; assert!(unsafe_dir.join("support.json").is_file()); assert!(!unsafe_dir.join(format!("{mf_module}.js")).exists()); assert!(!unsafe_dir.join(format!("{mf_module}.d.ts")).exists()); @@ -5380,8 +5425,8 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { let unsafe_success = run( &output_dir, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", false, ); assert!( @@ -5401,7 +5446,7 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { assert_eq!( merged_names, std::collections::BTreeSet::from([ - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT", ]) ); @@ -5493,7 +5538,10 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { }; let safe = spawn("Windows.Win32.UI.Shell", "ITaskbarList3"); - let unsafe_companion = spawn("Windows.Win32.Media.Audio", "IAudioClient"); + let unsafe_companion = spawn( + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + ); let safe = safe.wait_with_output().unwrap(); let unsafe_companion = unsafe_companion.wait_with_output().unwrap(); assert!( @@ -5509,7 +5557,7 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { let com_dir = output_dir.join("com"); let unsafe_dir = com_dir.join("unsafe"); - let unsafe_module = "windows/win32/media/audio/IAudioClientUnsafe.js"; + let unsafe_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js"; assert!( generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") .is_file() @@ -5518,14 +5566,17 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { let safe_barrel = fs::read_to_string(com_dir.join("index.js")).unwrap(); let unsafe_barrel = fs::read_to_string(unsafe_dir.join("index.js")).unwrap(); assert!(safe_barrel.contains("ITaskbarList3")); - assert!(!safe_barrel.contains("IAudioClientUnsafe")); - assert!(unsafe_barrel.contains("IAudioClientUnsafe")); + assert!(!safe_barrel.contains("IWinMLEvaluationContextUnsafe")); + assert!(unsafe_barrel.contains("IWinMLEvaluationContextUnsafe")); let manifest: serde_json::Value = serde_json::from_str( &fs::read_to_string(com_dir.join(".dynwinrt-com-manifest.json")).unwrap(), ) .unwrap(); assert!(manifest["roots"]["Windows.Win32.UI.Shell.ITaskbarList3"].is_array()); - assert!(manifest["roots"]["Windows.Win32.Media.Audio.IAudioClient"].is_array()); + assert!( + manifest["roots"]["Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext"] + .is_array() + ); let safe_second = spawn("Windows.Win32.UI.Shell", "IShellLinkW"); let report_only = spawn("Windows.Win32.Media.MediaFoundation", "MFASYNCRESULT"); @@ -5556,7 +5607,7 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { for root in [ "Windows.Win32.UI.Shell.ITaskbarList3", "Windows.Win32.UI.Shell.IShellLinkW", - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT", ] { assert!( @@ -5686,8 +5737,8 @@ fn concurrent_com_and_winrt_writers_share_one_output_lock_in_both_orders() { let baseline_unsafe = spawn( &output, &win32_metadata, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", None, None, ) @@ -5748,22 +5799,30 @@ fn concurrent_com_and_winrt_writers_share_one_output_lock_in_both_orders() { ); assert!(generated_com_module(&output, "Windows.Win32.UI.Shell", "IShellLinkW", "js").is_file()); assert!( - generated_unsafe_module(&output, "Windows.Win32.Media.Audio", "IAudioClient", "js") - .is_file() + generated_unsafe_module( + &output, + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "js" + ) + .is_file() ); let manifest: serde_json::Value = serde_json::from_str( &fs::read_to_string(output.join("com").join(".dynwinrt-com-manifest.json")).unwrap(), ) .unwrap(); assert!(manifest["roots"]["Windows.Win32.UI.Shell.IShellLinkW"].is_array()); - assert!(manifest["roots"]["Windows.Win32.Media.Audio.IAudioClient"].is_array()); + assert!( + manifest["roots"]["Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext"] + .is_array() + ); let root_barrel = fs::read_to_string(output.join("index.d.ts")).unwrap(); let com_barrel = fs::read_to_string(output.join("com").join("index.d.ts")).unwrap(); let unsafe_barrel = fs::read_to_string(output.join("com").join("unsafe").join("index.d.ts")).unwrap(); assert!(root_barrel.contains("Uri") && !root_barrel.contains("Calendar")); assert!(com_barrel.contains("IShellLinkW")); - assert!(unsafe_barrel.contains("IAudioClientUnsafe")); + assert!(unsafe_barrel.contains("IWinMLEvaluationContextUnsafe")); let support: serde_json::Value = serde_json::from_str( &fs::read_to_string(output.join("com").join("unsafe").join("support.json")).unwrap(), ) @@ -5808,9 +5867,9 @@ fn generated_unsafe_fingerprint_includes_sibling_and_reference_metadata() { "--winmd", winmd.to_str().unwrap(), "--namespace", - "Windows.Win32.Media.Audio", + "Windows.Win32.AI.MachineLearning.WinML", "--class-name", - "IAudioClient", + "IWinMLEvaluationContext", "--output", output.to_str().unwrap(), ]); @@ -5941,7 +6000,7 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { ); let before = snapshot_tree(&output_dir); let incremental_failure = run( - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", Some("after_backup_rename"), ); assert!(!incremental_failure.status.success()); @@ -5963,7 +6022,7 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { "--winmd", &metadata, "--class-name", - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "--output", output_dir.to_str().unwrap(), ]) @@ -5992,8 +6051,8 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { assert!( generated_unsafe_module( &output_dir, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", "js" ) .is_file() @@ -6250,8 +6309,8 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { run_codegen_command( &win32_winmd(), - Some("Windows.Win32.Media.Audio"), - "IAudioClient", + Some("Windows.Win32.AI.MachineLearning.WinML"), + "IWinMLEvaluationContext", &output, ); run_codegen_command( @@ -6262,8 +6321,13 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { ); assert!( - generated_unsafe_module(&output, "Windows.Win32.Media.Audio", "IAudioClient", "js") - .is_file() + generated_unsafe_module( + &output, + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "js" + ) + .is_file() ); let package = fs::read_to_string(output.join("package.json")).unwrap(); assert!(package.contains("\".\":")); @@ -6277,7 +6341,7 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { '@winapp/bindings',\ '@winapp/bindings/windows/foundation/Uri',\ '@winapp/bindings/com',\ - '@winapp/bindings/com/unsafe/windows/win32/media/audio/IAudioClientUnsafe'\ + '@winapp/bindings/com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe'\ ]) console.log(require.resolve(id))", ]) .current_dir(&root) From 58b1f42ecd9936cd1254b889aa4baed9275ecdb6 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 4 Sep 2026 22:29:24 +0800 Subject: [PATCH 5/8] Fix generated WMI test object ABI Use the official IWbemServices vtable through ExecMethodAsync and return ABI-correct IWbemClassObject and IWbemCallResult tear-offs with canonical identity and shared reference counting. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- bindings/js/Cargo.toml | 2 +- .../generated-unsafe-companion.e2e.ts | 45 +- .../js/src/generated_unsafe_test_hooks.rs | 686 ++++++++++++++---- .../classic-com-generated-unsafe.md | 11 +- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 9 +- 5 files changed, 576 insertions(+), 177 deletions(-) diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index de260fbd..69d4771b 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = [] +test-hooks = ["windows/Win32_System_Wmi"] [dependencies] napi = { version = "3", features = ["napi7"] } diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index ed7e9188..e9a36d74 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.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', '--output', output, ] @@ -88,6 +88,8 @@ 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 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') const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') const runner = join(output, 'generated-companion-runner.cjs') @@ -102,6 +104,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr `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 wbemCallResult = require(${JSON.stringify(`${wbemCallResultBase}.js`)})`, + `const wbemClassObject = require(${JSON.stringify(`${wbemClassObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, @@ -120,18 +124,26 @@ 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 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)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, ` 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 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.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(esmWbemCallResult.IWbemCallResult, wbemCallResult.IWbemCallResult)', + ' assert.equal(esmWbemClassObject.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', @@ -142,6 +154,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.equal(typeof readStats, 'function')", ' runtime.initializeCom(1)', ' let fake = createFake()', + ' runtime.probeGeneratedIwbemServicesUnimplementedSlots(fake)', + " assert.throws(() => fake.cast(WinGuid.parse('44aca674-e8fc-11d0-a07c-00c04fb68820')), /interface|0x80004002/i)", ' let wrapper', ' try {', ' assert.equal(readStats().currentRefCount, 1)', @@ -174,6 +188,9 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(readStats().openNamespaceContextArgumentNull, true)', ' assert.equal(readStats().openNamespaceLastFlags, 0x10)', ' assert.equal(readStats().currentRefCount, asyncBefore.currentRefCount + 1)', + ' const callResultView = wbemCallResult.IWbemCallResult._fromNative(callResult)', + ' assert.equal(callResultView.getCallStatus(0), 0)', + ' callResultView.release()', ' callResult.release()', ' assert.equal(readStats().currentRefCount, asyncBefore.currentRefCount)', ' setConditionalMode(-1)', @@ -186,20 +203,28 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(readStats().openNamespaceCalls, 4)', ' setConditionalMode(0)', " const object = wrapper.getObject('root', { mode: 'sync' })", - ' object.release()', - " wrapper.putClass(fake, { mode: 'sync' })", + ' const classObject = wbemClassObject.IWbemClassObjectUnsafe.from(object)', + ' classObject.endEnumeration()', + " wrapper.putClass(object, { mode: 'sync' })", " wrapper.deleteClass('Class', { mode: 'sync' })", - " wrapper.putInstance(fake, { mode: 'sync' })", + " wrapper.putInstance(object, { mode: 'sync' })", " wrapper.deleteInstance('root', { mode: 'sync' })", - " const methodOutput = wrapper.execMethod('root', 'Method', fake, { mode: 'sync' })", + " const methodOutput = wrapper.execMethod('root', 'Method', object, { mode: 'sync' })", + ' const methodClassObject = wbemClassObject.IWbemClassObjectUnsafe.from(methodOutput)', + ' methodClassObject.endEnumeration()', + ' methodClassObject.release()', ' methodOutput.release()', ' setConditionalMode(1)', - " for (const result of [wrapper.getObject('root', { mode: 'semisync' }), wrapper.putClass(fake, { mode: 'semisync' }), wrapper.deleteClass('Class', { mode: 'semisync' }), wrapper.putInstance(fake, { mode: 'semisync' }), wrapper.deleteInstance('root', { mode: 'semisync' }), wrapper.execMethod('root', 'Method', fake, { mode: 'semisync' })]) result.release()", + " const pendingResults = [wrapper.getObject('root', { mode: 'semisync' }), wrapper.putClass(object, { mode: 'semisync' }), wrapper.deleteClass('Class', { mode: 'semisync' }), wrapper.putInstance(object, { mode: 'semisync' }), wrapper.deleteInstance('root', { mode: 'semisync' }), wrapper.execMethod('root', 'Method', object, { mode: 'semisync' })]", + ' const pendingView = wbemCallResult.IWbemCallResult._fromNative(pendingResults[0])', + ' assert.equal(pendingView.getCallStatus(0), 0)', + ' pendingView.release()', + ' for (const result of pendingResults) result.release()', ' setConditionalMode(-1)', ' const conditionalFailureBefore = readStats().currentRefCount', " assert.throws(() => wrapper.getObject('root', { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", - " assert.throws(() => wrapper.putClass(fake, { mode: 'semisync' }), /native call failed|HRESULT|0x80004005/i)", - " assert.throws(() => wrapper.execMethod('root', 'Method', fake, { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", + " assert.throws(() => wrapper.putClass(object, { mode: 'semisync' }), /native call failed|HRESULT|0x80004005/i)", + " assert.throws(() => wrapper.execMethod('root', 'Method', object, { mode: 'sync' }), /native call failed|HRESULT|0x80004005/i)", ' assert.equal(readStats().currentRefCount, conditionalFailureBefore)', ' assert.equal(readStats().getObjectCalls, 3)', ' assert.equal(readStats().putClassCalls, 3)', @@ -207,6 +232,10 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(readStats().putInstanceCalls, 2)', ' assert.equal(readStats().deleteInstanceCalls, 2)', ' assert.equal(readStats().execMethodCalls, 3)', + ' assert.equal(readStats().classObjectEndEnumerationCalls, 2)', + ' assert.equal(readStats().callResultGetStatusCalls, 2)', + ' classObject.release()', + ' object.release()', ' wrapper.release()', ' assert.equal(readStats().currentRefCount, 1)', ' wrapper.release()', diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 083cd29f..09c33297 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -8,12 +8,21 @@ use std::{ use napi::bindgen_prelude::BigInt; use napi_derive::napi; -use windows::core::{IUnknown, IUnknown_Vtbl, Interface, GUID, HRESULT}; +use windows::{ + core::{IUnknown, IUnknown_Vtbl, Interface, GUID, HRESULT, PCWSTR}, + Win32::System::{ + Com::SAFEARRAY, + Variant::VARIANT, + Wmi::{ + IWbemCallResult_Vtbl, IWbemClassObject_Vtbl, IWbemServices_Vtbl, WBEM_COMPARISON_FLAG, + WBEM_CONDITION_FLAG_TYPE, WBEM_GENERIC_FLAG_TYPE, + }, + }, +}; use crate::DynWinRTValue; const IID_IWBEM_SERVICES: GUID = GUID::from_u128(0x9556dc99_828c_11cf_a37e_00aa003240c7); -const IID_IWBEM_CONTEXT: GUID = GUID::from_u128(0x44aca674_e8fc_11d0_a07c_00c04fb68820); 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); @@ -42,6 +51,8 @@ static EXEC_METHOD_CALLS: AtomicU32 = AtomicU32::new(0); static QUERY_OBJECT_SINK_CALLS: AtomicU32 = AtomicU32::new(0); static LAST_FLAGS: AtomicI32 = AtomicI32::new(0); static CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static CLASS_OBJECT_END_ENUMERATION_CALLS: AtomicU32 = AtomicU32::new(0); +static CALL_RESULT_GET_STATUS_CALLS: AtomicU32 = AtomicU32::new(0); static LAST_OUTPUT_ADDRESS: AtomicUsize = AtomicUsize::new(0); static AUDIO_IS_FORMAT_SUPPORTED_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_GET_SERVICE_CALLS: AtomicU32 = AtomicU32::new(0); @@ -54,78 +65,52 @@ 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); -#[repr(C)] -struct GeneratedIWbemServicesVtbl { - base__: IUnknown_Vtbl, - open_namespace: unsafe extern "system" fn( - *mut c_void, - *mut u16, - i32, - *mut c_void, - *mut *mut c_void, - *mut *mut c_void, - ) -> HRESULT, - cancel_async_call: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, - query_object_sink: unsafe extern "system" fn(*mut c_void, i32, *mut *mut c_void) -> HRESULT, - get_object: unsafe extern "system" fn( - *mut c_void, - *mut u16, - i32, - *mut c_void, - *mut *mut c_void, - *mut *mut c_void, - ) -> HRESULT, - get_object_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - put_class: unsafe extern "system" fn( - *mut c_void, - *mut c_void, - i32, - *mut c_void, - *mut *mut c_void, - ) -> HRESULT, - put_class_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - delete_class: - unsafe extern "system" fn(*mut c_void, *mut u16, i32, *mut c_void, *mut *mut c_void) -> HRESULT, - delete_class_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - create_class_enum: unsafe extern "system" fn(*mut c_void) -> HRESULT, - create_class_enum_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - put_instance: unsafe extern "system" fn( - *mut c_void, - *mut c_void, - i32, - *mut c_void, - *mut *mut c_void, - ) -> HRESULT, - put_instance_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - delete_instance: - unsafe extern "system" fn(*mut c_void, *mut u16, i32, *mut c_void, *mut *mut c_void) -> HRESULT, - delete_instance_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - create_instance_enum: unsafe extern "system" fn(*mut c_void) -> HRESULT, - create_instance_enum_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - exec_query: unsafe extern "system" fn(*mut c_void) -> HRESULT, - exec_query_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - exec_notification_query: unsafe extern "system" fn(*mut c_void) -> HRESULT, - exec_notification_query_async: unsafe extern "system" fn(*mut c_void) -> HRESULT, - exec_method: unsafe extern "system" fn( - *mut c_void, - *mut u16, - *mut u16, - i32, - *mut c_void, - *mut c_void, - *mut *mut c_void, - *mut *mut c_void, - ) -> HRESULT, -} - #[repr(C)] struct GeneratedIWbemServicesFake { - vtable: *const GeneratedIWbemServicesVtbl, + services_vtable: *const IWbemServices_Vtbl, + class_object_vtable: *const IWbemClassObject_Vtbl, + call_result_vtable: *const IWbemCallResult_Vtbl, references: AtomicU32, } -unsafe extern "system" fn query_interface( - this: *mut c_void, +unsafe fn owner_from_class_object(this: *mut c_void) -> *mut GeneratedIWbemServicesFake { + unsafe { + this + .cast::() + .sub(std::mem::offset_of!( + GeneratedIWbemServicesFake, + class_object_vtable + )) + .cast() + } +} + +unsafe fn owner_from_call_result(this: *mut c_void) -> *mut GeneratedIWbemServicesFake { + unsafe { + this + .cast::() + .sub(std::mem::offset_of!( + GeneratedIWbemServicesFake, + call_result_vtable + )) + .cast() + } +} + +unsafe fn services_pointer(owner: *mut GeneratedIWbemServicesFake) -> *mut c_void { + owner.cast() +} + +unsafe fn class_object_pointer(owner: *mut GeneratedIWbemServicesFake) -> *mut c_void { + unsafe { std::ptr::addr_of_mut!((*owner).class_object_vtable).cast() } +} + +unsafe fn call_result_pointer(owner: *mut GeneratedIWbemServicesFake) -> *mut c_void { + unsafe { std::ptr::addr_of_mut!((*owner).call_result_vtable).cast() } +} + +unsafe fn query_interface_owner( + owner: *mut GeneratedIWbemServicesFake, iid: *const GUID, result: *mut *mut c_void, ) -> HRESULT { @@ -135,51 +120,121 @@ unsafe extern "system" fn query_interface( } unsafe { *result = std::ptr::null_mut(); - if *iid != IUnknown::IID - && *iid != IID_IWBEM_SERVICES - && *iid != IID_IWBEM_CONTEXT - && *iid != IID_IWBEM_CALL_RESULT - && *iid != IID_IWBEM_CLASS_OBJECT - { + *result = if *iid == IUnknown::IID || *iid == IID_IWBEM_SERVICES { + services_pointer(owner) + } else if *iid == IID_IWBEM_CLASS_OBJECT { + class_object_pointer(owner) + } else if *iid == IID_IWBEM_CALL_RESULT { + call_result_pointer(owner) + } else { return E_NOINTERFACE; - } - *result = this; - add_ref(this); + }; + add_ref_owner(owner); } HRESULT(0) } -unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { +unsafe extern "system" fn services_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + unsafe { query_interface_owner(this.cast(), iid, result) } +} + +unsafe extern "system" fn class_object_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + unsafe { query_interface_owner(owner_from_class_object(this), iid, result) } +} + +unsafe extern "system" fn call_result_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + unsafe { query_interface_owner(owner_from_call_result(this), iid, result) } +} + +unsafe fn add_ref_owner(owner: *mut GeneratedIWbemServicesFake) -> u32 { ADD_REF_CALLS.fetch_add(1, Ordering::SeqCst); - let object = unsafe { &*this.cast::() }; + let object = unsafe { &*owner }; let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; CURRENT_REF_COUNT.store(count, Ordering::SeqCst); count } -unsafe extern "system" fn release(this: *mut c_void) -> u32 { +unsafe extern "system" fn services_add_ref(this: *mut c_void) -> u32 { + unsafe { add_ref_owner(this.cast()) } +} + +unsafe extern "system" fn class_object_add_ref(this: *mut c_void) -> u32 { + unsafe { add_ref_owner(owner_from_class_object(this)) } +} + +unsafe extern "system" fn call_result_add_ref(this: *mut c_void) -> u32 { + unsafe { add_ref_owner(owner_from_call_result(this)) } +} + +unsafe fn release_owner(owner: *mut GeneratedIWbemServicesFake) -> u32 { RELEASE_CALLS.fetch_add(1, Ordering::SeqCst); - let object = unsafe { &*this.cast::() }; + let object = unsafe { &*owner }; let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; CURRENT_REF_COUNT.store(count, Ordering::SeqCst); if count == 0 { unsafe { - drop(Box::from_raw(this.cast::())); + drop(Box::from_raw(owner)); } } count } +unsafe extern "system" fn services_release(this: *mut c_void) -> u32 { + unsafe { release_owner(this.cast()) } +} + +unsafe extern "system" fn class_object_release(this: *mut c_void) -> u32 { + unsafe { release_owner(owner_from_class_object(this)) } +} + +unsafe extern "system" fn call_result_release(this: *mut c_void) -> u32 { + unsafe { release_owner(owner_from_call_result(this)) } +} + +#[derive(Clone, Copy)] +enum WbemOutputView { + Services, + ClassObject, + CallResult, +} + +unsafe fn write_owned_view( + owner: *mut GeneratedIWbemServicesFake, + output: *mut *mut c_void, + view: WbemOutputView, +) { + unsafe { + add_ref_owner(owner); + *output = match view { + WbemOutputView::Services => services_pointer(owner), + WbemOutputView::ClassObject => class_object_pointer(owner), + WbemOutputView::CallResult => call_result_pointer(owner), + }; + } +} + unsafe extern "system" fn open_namespace( this: *mut c_void, - _namespace: *mut u16, - flags: i32, + _namespace: *mut c_void, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, working_namespace: *mut *mut c_void, result: *mut *mut c_void, ) -> HRESULT { OPEN_NAMESPACE_CALLS.fetch_add(1, Ordering::SeqCst); - OPEN_NAMESPACE_LAST_FLAGS.store(flags, Ordering::SeqCst); + OPEN_NAMESPACE_LAST_FLAGS.store(flags.0, Ordering::SeqCst); OPEN_NAMESPACE_CONTEXT_ARGUMENT_NULL.store(u32::from(context.is_null()), Ordering::SeqCst); OPEN_NAMESPACE_WORKING_ARGUMENT_NULL .store(u32::from(working_namespace.is_null()), Ordering::SeqCst); @@ -194,25 +249,22 @@ unsafe extern "system" fn open_namespace( { return E_POINTER; } + let owner = this.cast::(); match WMI_CONDITIONAL_MODE.load(Ordering::SeqCst) { - 0 if flags == 0 && !working_namespace.is_null() && result.is_null() => { - add_ref(this); - unsafe { *working_namespace = this }; + 0 if flags.0 == 0 && !working_namespace.is_null() && result.is_null() => { + unsafe { write_owned_view(owner, working_namespace, WbemOutputView::Services) }; HRESULT(0) } - 1 if flags == 0x10 && working_namespace.is_null() && !result.is_null() => { - add_ref(this); - unsafe { *result = this }; + 1 if flags.0 == 0x10 && working_namespace.is_null() && !result.is_null() => { + unsafe { write_owned_view(owner, result, WbemOutputView::CallResult) }; HRESULT(0) } -1 => { if !working_namespace.is_null() { - add_ref(this); - unsafe { *working_namespace = this }; + unsafe { write_owned_view(owner, working_namespace, WbemOutputView::Services) }; } if !result.is_null() { - add_ref(this); - unsafe { *result = this }; + unsafe { write_owned_view(owner, result, WbemOutputView::CallResult) }; } HRESULT(0x80004005u32 as i32) } @@ -222,11 +274,11 @@ unsafe extern "system" fn open_namespace( unsafe fn complete_conditional_call( this: *mut c_void, - flags: i32, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, synchronous_output: *mut *mut c_void, semisynchronous_output: *mut *mut c_void, - synchronous_returns_value: bool, + synchronous_view: Option, ) -> HRESULT { if !context.is_null() || (!synchronous_output.is_null() && unsafe { !(*synchronous_output).is_null() }) @@ -234,30 +286,33 @@ unsafe fn complete_conditional_call( { return E_POINTER; } + let owner = this.cast::(); match WMI_CONDITIONAL_MODE.load(Ordering::SeqCst) { - 0 if flags == 0 + 0 if flags.0 == 0 && semisynchronous_output.is_null() - && (synchronous_returns_value == !synchronous_output.is_null()) => + && (synchronous_view.is_some() == !synchronous_output.is_null()) => { - if synchronous_returns_value { - add_ref(this); - unsafe { *synchronous_output = this }; + if let Some(view) = synchronous_view { + unsafe { write_owned_view(owner, synchronous_output, view) }; } HRESULT(0) } - 1 if flags == 0x10 && synchronous_output.is_null() && !semisynchronous_output.is_null() => { - add_ref(this); - unsafe { *semisynchronous_output = this }; + 1 if flags.0 == 0x10 && synchronous_output.is_null() && !semisynchronous_output.is_null() => { + unsafe { + write_owned_view(owner, semisynchronous_output, WbemOutputView::CallResult); + } HRESULT(0) } -1 => { if !synchronous_output.is_null() { - add_ref(this); - unsafe { *synchronous_output = this }; + if let Some(view) = synchronous_view { + unsafe { write_owned_view(owner, synchronous_output, view) }; + } } if !semisynchronous_output.is_null() { - add_ref(this); - unsafe { *semisynchronous_output = this }; + unsafe { + write_owned_view(owner, semisynchronous_output, WbemOutputView::CallResult); + } } HRESULT(0x80004005u32 as i32) } @@ -267,8 +322,8 @@ unsafe fn complete_conditional_call( unsafe extern "system" fn get_object( this: *mut c_void, - object_path: *mut u16, - flags: i32, + object_path: *mut c_void, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, object: *mut *mut c_void, result: *mut *mut c_void, @@ -277,13 +332,22 @@ unsafe extern "system" fn get_object( if object_path.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, object, result, true) } + unsafe { + complete_conditional_call( + this, + flags, + context, + object, + result, + Some(WbemOutputView::ClassObject), + ) + } } unsafe extern "system" fn put_class( this: *mut c_void, object: *mut c_void, - flags: i32, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, result: *mut *mut c_void, ) -> HRESULT { @@ -291,13 +355,13 @@ unsafe extern "system" fn put_class( if object.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, None) } } unsafe extern "system" fn delete_class( this: *mut c_void, - class_name: *mut u16, - flags: i32, + class_name: *mut c_void, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, result: *mut *mut c_void, ) -> HRESULT { @@ -305,13 +369,13 @@ unsafe extern "system" fn delete_class( if class_name.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, None) } } unsafe extern "system" fn put_instance( this: *mut c_void, instance: *mut c_void, - flags: i32, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, result: *mut *mut c_void, ) -> HRESULT { @@ -319,13 +383,13 @@ unsafe extern "system" fn put_instance( if instance.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, None) } } unsafe extern "system" fn delete_instance( this: *mut c_void, - object_path: *mut u16, - flags: i32, + object_path: *mut c_void, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, result: *mut *mut c_void, ) -> HRESULT { @@ -333,14 +397,14 @@ unsafe extern "system" fn delete_instance( if object_path.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, false) } + unsafe { complete_conditional_call(this, flags, context, std::ptr::null_mut(), result, None) } } unsafe extern "system" fn exec_method( this: *mut c_void, - object_path: *mut u16, - method_name: *mut u16, - flags: i32, + object_path: *mut c_void, + method_name: *mut c_void, + flags: WBEM_GENERIC_FLAG_TYPE, context: *mut c_void, input: *mut c_void, output: *mut *mut c_void, @@ -350,10 +414,69 @@ unsafe extern "system" fn exec_method( if object_path.is_null() || method_name.is_null() || input.is_null() { return E_POINTER; } - unsafe { complete_conditional_call(this, flags, context, output, result, true) } + unsafe { + complete_conditional_call( + this, + flags, + context, + output, + result, + Some(WbemOutputView::ClassObject), + ) + } +} + +unsafe extern "system" fn unimplemented_wbem_async_single( + _this: *mut c_void, + _value: *mut c_void, + _flags: WBEM_GENERIC_FLAG_TYPE, + _context: *mut c_void, + _response_handler: *mut c_void, +) -> HRESULT { + E_NOTIMPL } -unsafe extern "system" fn unimplemented_wbem_method(_this: *mut c_void) -> HRESULT { +unsafe extern "system" fn unimplemented_wbem_enum( + _this: *mut c_void, + _filter: *mut c_void, + _flags: WBEM_GENERIC_FLAG_TYPE, + _context: *mut c_void, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn unimplemented_wbem_query( + _this: *mut c_void, + _query_language: *mut c_void, + _query: *mut c_void, + _flags: WBEM_GENERIC_FLAG_TYPE, + _context: *mut c_void, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn unimplemented_wbem_query_async( + _this: *mut c_void, + _query_language: *mut c_void, + _query: *mut c_void, + _flags: WBEM_GENERIC_FLAG_TYPE, + _context: *mut c_void, + _response_handler: *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn unimplemented_wbem_exec_method_async( + _this: *mut c_void, + _object_path: *mut c_void, + _method_name: *mut c_void, + _flags: WBEM_GENERIC_FLAG_TYPE, + _context: *mut c_void, + _input: *mut c_void, + _response_handler: *mut c_void, +) -> HRESULT { E_NOTIMPL } @@ -363,50 +486,237 @@ unsafe extern "system" fn cancel_async_call(_this: *mut c_void, _sink: *mut c_vo unsafe extern "system" fn query_object_sink( _this: *mut c_void, - flags: i32, + flags: WBEM_GENERIC_FLAG_TYPE, result: *mut *mut c_void, ) -> HRESULT { if result.is_null() { return E_POINTER; } QUERY_OBJECT_SINK_CALLS.fetch_add(1, Ordering::SeqCst); - LAST_FLAGS.store(flags, Ordering::SeqCst); - let output = std::ptr::with_exposed_provenance_mut::(0x1234); - LAST_OUTPUT_ADDRESS.store(output.expose_provenance(), Ordering::SeqCst); + LAST_FLAGS.store(flags.0, Ordering::SeqCst); unsafe { - *result = output; + *result = std::ptr::null_mut(); + } + LAST_OUTPUT_ADDRESS.store(0, Ordering::SeqCst); + E_NOTIMPL +} + +static SERVICES_VTABLE: IWbemServices_Vtbl = IWbemServices_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: services_query_interface, + AddRef: services_add_ref, + Release: services_release, + }, + OpenNamespace: open_namespace, + CancelAsyncCall: cancel_async_call, + QueryObjectSink: query_object_sink, + GetObject: get_object, + GetObjectAsync: unimplemented_wbem_async_single, + PutClass: put_class, + PutClassAsync: unimplemented_wbem_async_single, + DeleteClass: delete_class, + DeleteClassAsync: unimplemented_wbem_async_single, + CreateClassEnum: unimplemented_wbem_enum, + CreateClassEnumAsync: unimplemented_wbem_async_single, + PutInstance: put_instance, + PutInstanceAsync: unimplemented_wbem_async_single, + DeleteInstance: delete_instance, + DeleteInstanceAsync: unimplemented_wbem_async_single, + CreateInstanceEnum: unimplemented_wbem_enum, + CreateInstanceEnumAsync: unimplemented_wbem_async_single, + ExecQuery: unimplemented_wbem_query, + ExecQueryAsync: unimplemented_wbem_query_async, + ExecNotificationQuery: unimplemented_wbem_query, + ExecNotificationQueryAsync: unimplemented_wbem_query_async, + ExecMethod: exec_method, + ExecMethodAsync: unimplemented_wbem_exec_method_async, +}; + +unsafe extern "system" fn class_object_out( + _this: *mut c_void, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_get( + _this: *mut c_void, + _name: PCWSTR, + _flags: i32, + _value: *mut VARIANT, + _kind: *mut i32, + _flavor: *mut i32, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_put( + _this: *mut c_void, + _name: PCWSTR, + _flags: i32, + _value: *const VARIANT, + _kind: i32, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_name(_this: *mut c_void, _name: PCWSTR) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_get_names( + _this: *mut c_void, + _qualifier_name: PCWSTR, + _flags: WBEM_CONDITION_FLAG_TYPE, + _qualifier_value: *const VARIANT, + _names: *mut *mut SAFEARRAY, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_flags(_this: *mut c_void, _flags: i32) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_next( + _this: *mut c_void, + _flags: i32, + _name: *mut *mut c_void, + _value: *mut VARIANT, + _kind: *mut i32, + _flavor: *mut i32, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_end_enumeration(_this: *mut c_void) -> HRESULT { + CLASS_OBJECT_END_ENUMERATION_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn class_object_named_out( + _this: *mut c_void, + _name: PCWSTR, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_flags_out( + _this: *mut c_void, + _flags: i32, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_compare( + _this: *mut c_void, + _flags: WBEM_COMPARISON_FLAG, + _other: *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_get_method( + _this: *mut c_void, + _name: PCWSTR, + _flags: i32, + _input: *mut *mut c_void, + _output: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_put_method( + _this: *mut c_void, + _name: PCWSTR, + _flags: i32, + _input: *mut c_void, + _output: *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_next_method( + _this: *mut c_void, + _flags: i32, + _name: *mut *mut c_void, + _input: *mut *mut c_void, + _output: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn class_object_end_method_enumeration(_this: *mut c_void) -> HRESULT { + E_NOTIMPL +} + +static CLASS_OBJECT_VTABLE: IWbemClassObject_Vtbl = IWbemClassObject_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: class_object_query_interface, + AddRef: class_object_add_ref, + Release: class_object_release, + }, + GetQualifierSet: class_object_out, + Get: class_object_get, + Put: class_object_put, + Delete: class_object_name, + GetNames: class_object_get_names, + BeginEnumeration: class_object_flags, + Next: class_object_next, + EndEnumeration: class_object_end_enumeration, + GetPropertyQualifierSet: class_object_named_out, + Clone: class_object_out, + GetObjectText: class_object_flags_out, + SpawnDerivedClass: class_object_flags_out, + SpawnInstance: class_object_flags_out, + CompareTo: class_object_compare, + GetPropertyOrigin: class_object_named_out, + InheritsFrom: class_object_name, + GetMethod: class_object_get_method, + PutMethod: class_object_put_method, + DeleteMethod: class_object_name, + BeginMethodEnumeration: class_object_flags, + NextMethod: class_object_next_method, + EndMethodEnumeration: class_object_end_method_enumeration, + GetMethodQualifierSet: class_object_named_out, + GetMethodOrigin: class_object_named_out, +}; + +unsafe extern "system" fn call_result_object( + _this: *mut c_void, + _timeout: i32, + _result: *mut *mut c_void, +) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn call_result_get_status( + _this: *mut c_void, + _timeout: i32, + status: *mut i32, +) -> HRESULT { + if status.is_null() { + return E_POINTER; + } + CALL_RESULT_GET_STATUS_CALLS.fetch_add(1, Ordering::SeqCst); + unsafe { + *status = 0; } HRESULT(0) } -static VTABLE: GeneratedIWbemServicesVtbl = GeneratedIWbemServicesVtbl { +static CALL_RESULT_VTABLE: IWbemCallResult_Vtbl = IWbemCallResult_Vtbl { base__: IUnknown_Vtbl { - QueryInterface: query_interface, - AddRef: add_ref, - Release: release, + QueryInterface: call_result_query_interface, + AddRef: call_result_add_ref, + Release: call_result_release, }, - open_namespace, - cancel_async_call, - query_object_sink, - get_object, - get_object_async: unimplemented_wbem_method, - put_class, - put_class_async: unimplemented_wbem_method, - delete_class, - delete_class_async: unimplemented_wbem_method, - create_class_enum: unimplemented_wbem_method, - create_class_enum_async: unimplemented_wbem_method, - put_instance, - put_instance_async: unimplemented_wbem_method, - delete_instance, - delete_instance_async: unimplemented_wbem_method, - create_instance_enum: unimplemented_wbem_method, - create_instance_enum_async: unimplemented_wbem_method, - exec_query: unimplemented_wbem_method, - exec_query_async: unimplemented_wbem_method, - exec_notification_query: unimplemented_wbem_method, - exec_notification_query_async: unimplemented_wbem_method, - exec_method, + GetResultObject: call_result_object, + GetResultString: call_result_object, + GetResultServices: call_result_object, + GetCallStatus: call_result_get_status, }; #[napi(object)] @@ -431,6 +741,8 @@ pub struct GeneratedUnsafeComStats { pub last_flags: i32, pub current_ref_count: u32, pub last_output_address: u32, + pub class_object_end_enumeration_calls: u32, + pub call_result_get_status_calls: u32, } #[napi] @@ -456,15 +768,67 @@ pub fn create_generated_iwbem_services_fake() -> napi::Result { LAST_FLAGS.store(0, Ordering::SeqCst); CURRENT_REF_COUNT.store(1, Ordering::SeqCst); LAST_OUTPUT_ADDRESS.store(0, Ordering::SeqCst); + CLASS_OBJECT_END_ENUMERATION_CALLS.store(0, Ordering::SeqCst); + CALL_RESULT_GET_STATUS_CALLS.store(0, Ordering::SeqCst); let object = Box::new(GeneratedIWbemServicesFake { - vtable: &VTABLE, + services_vtable: &SERVICES_VTABLE, + class_object_vtable: &CLASS_OBJECT_VTABLE, + call_result_vtable: &CALL_RESULT_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 probe_generated_iwbem_services_unimplemented_slots( + value: &DynWinRTValue, +) -> napi::Result<()> { + let raw = match &value.0 { + dynwinrt::WinRTValue::Object(object) => object.as_raw(), + _ => { + return Err(napi::Error::from_reason( + "IWbemServices probe requires a managed COM object", + )); + } + }; + let vtable = unsafe { *(raw.cast::<*const IWbemServices_Vtbl>()) }; + let mut object_sink = std::ptr::null_mut(); + let query_object_sink = + unsafe { ((*vtable).QueryObjectSink)(raw, WBEM_GENERIC_FLAG_TYPE(0), &mut object_sink) }; + let get_object_async = unsafe { + ((*vtable).GetObjectAsync)( + raw, + std::ptr::null_mut(), + WBEM_GENERIC_FLAG_TYPE(0), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + let exec_method_async = unsafe { + ((*vtable).ExecMethodAsync)( + raw, + std::ptr::null_mut(), + std::ptr::null_mut(), + WBEM_GENERIC_FLAG_TYPE(0), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + if query_object_sink != E_NOTIMPL + || !object_sink.is_null() + || get_object_async != E_NOTIMPL + || exec_method_async != E_NOTIMPL + { + return Err(napi::Error::from_reason( + "IWbemServices unimplemented slot probe returned an unexpected HRESULT", + )); + } + Ok(()) +} + #[napi] pub fn generated_unsafe_com_stats() -> GeneratedUnsafeComStats { GeneratedUnsafeComStats { @@ -493,6 +857,8 @@ pub fn generated_unsafe_com_stats() -> GeneratedUnsafeComStats { last_flags: LAST_FLAGS.load(Ordering::SeqCst), current_ref_count: CURRENT_REF_COUNT.load(Ordering::SeqCst), last_output_address: LAST_OUTPUT_ADDRESS.load(Ordering::SeqCst) as u32, + class_object_end_enumeration_calls: CLASS_OBJECT_END_ENUMERATION_CALLS.load(Ordering::SeqCst), + call_result_get_status_calls: CALL_RESULT_GET_STATUS_CALLS.load(Ordering::SeqCst), } } diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index ff595368..ef6380cb 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -661,10 +661,13 @@ Required tests include: The generated-artifact integration fixture combines safe WMI with unsafe Audio. The complete seven-method WMI conditional-output family executes through a -slot-accurate fake `IWbemServices` vtable. It validates sync/semisync -OptionalOut selection, no-output sync calls, `ExecMethod` multi-input calls, -native-null context, failure cleanup, QueryInterface/AddRef/Release balance, -CJS, ESM, and emitted declarations without requiring a live WMI service. +complete official `IWbemServices_Vtbl`. ABI-correct `IWbemClassObject` and +`IWbemCallResult` tear-offs expose canonical IUnknown identity and shared +reference counting; the fixture calls methods on both returned interfaces. It +also probes unimplemented slots 7 and 25, validates sync/semisync OptionalOut +selection, no-output sync calls, `ExecMethod` multi-input calls, native-null +context, failure cleanup, CJS, ESM, and emitted declarations without requiring +a live WMI service. The same fixture invokes generated `IThumbnailProvider.getThumbnail()` against a fake COM object that returns a real HBITMAP. It validates transfer into diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 9f6c9624..5222e7ca 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -291,10 +291,11 @@ ownership additionally requires the staged file to exist and exactly match the planned bytes before overwrite. CI also generates the real official safe `IWbemServices` wrapper and -`IAudioClientUnsafe` companion, then invokes `queryObjectSink` at absolute slot -5 against a test-hook IUnknown implementation with measured -QueryInterface/AddRef/Release and pointer-slot mutation. This avoids requiring -a live WMI service while testing the actual generated CJS, ESM, and declaration +`IAudioClientUnsafe` companion. The WMI test object uses the official +`IWbemServices_Vtbl` through slot 25 and ABI-correct `IWbemClassObject` and +`IWbemCallResult` tear-offs with one canonical IUnknown and shared reference +counting. Generated calls execute both tear-off interfaces without requiring a +live WMI service while testing the actual generated CJS, ESM, and declaration artifacts. Generated companions are outbound only. They do not infer output ownership, From e6dc69699a91d2bcc3a55c1c42bf516f57911bd4 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sun, 6 Sep 2026 22:05:42 +0800 Subject: [PATCH 6/8] Fix borrowed STGMEDIUM and canonical FORMATETC contracts Pin IDataObject and inherited IOleCache SetData inputs to caller-retained ownership. Model canonical FORMATETC result validity in the COM plan, preserve semantic HRESULTs, and keep ordinary FORMATETC decoding strict. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 14 +- .../generated-unsafe-companion.e2e.ts | 110 +++++++- bindings/js/src/com.rs | 14 + .../js/src/generated_unsafe_test_hooks.rs | 239 ++++++++++++++-- crates/dynwinrt/src/call.rs | 23 +- crates/dynwinrt/src/com.rs | 255 +++++++++++++++++- crates/dynwinrt/src/native_call.rs | 14 + .../classic-com-contract-evidence-registry.md | 21 +- docs/architecture/classic-com-support.md | 10 +- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 17 +- .../classic-com-capability-summary.json | 60 ++++- .../classic-com-interface-support.csv | 4 +- .../src/codegen/com/capability.rs | 24 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 6 +- .../src/codegen/com/javascript/render.rs | 17 +- .../codegen/com/javascript/render_tests.rs | 78 ++++++ .../src/codegen/com/model/metadata.rs | 133 ++++----- .../src/codegen/com/model/method.rs | 6 +- .../src/codegen/com/project/mod.rs | 39 ++- tools/dynwinrt-codegen/src/com_metadata.rs | 171 +++++++++++- .../dynwinrt-codegen/src/contract_registry.rs | 4 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 68 ++++- 22 files changed, 1157 insertions(+), 170 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a20d3899..b09920f0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -135,15 +135,15 @@ jobs: } if ( $result.safeEvidence.safeComplete -ne 5692 -or - $result.safeEvidence.standardDerived -ne 5336 -or - $result.safeEvidence.exactRegistryDependent -ne 356 -or + $result.safeEvidence.standardDerived -ne 5334 -or + $result.safeEvidence.exactRegistryDependent -ne 358 -or $result.safeEvidence.metadataFactOccurrences -ne 5976 -or $result.safeEvidence.comStandardFactOccurrences -ne 26119 -or - $result.safeEvidence.registeredExactEntries -ne 496 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 496 -or - $result.safeEvidence.safeConsumedExactEntries -ne 405 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 656 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 405 + $result.safeEvidence.registeredExactEntries -ne 498 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 498 -or + $result.safeEvidence.safeConsumedExactEntries -ne 407 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 659 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 408 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index f99d1558..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.Com.IDataObject', + '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, ] @@ -89,6 +89,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr 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') @@ -107,6 +109,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '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`)})`, @@ -128,6 +132,8 @@ 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)`, @@ -136,6 +142,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ` 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')", @@ -143,16 +151,22 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' 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', @@ -284,6 +298,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' }', ' const createDataObject = runtime.createGeneratedDataObjectFake', ' const dataObjectStats = runtime.generatedDataObjectStats', + ' const setCanonicalMode = runtime.setGeneratedDataObjectCanonicalMode', + " assert.equal(typeof setCanonicalMode, 'function')", ' let dataObjectFake = createDataObject()', ' let dataObjectWrapper', ' try {', @@ -295,13 +311,38 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' 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 [canonicalResult, canonical] = dataObjectWrapper.getCanonicalFormatEtc(format)', - ' assert.equal(canonicalResult, 0)', - ' assert.equal(canonical.clipboardFormat, 13)', + ' 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: 1, setDataCalls: 1, lastSetRelease: 0, outputReleased: true, getDataHereInputReleased: true, setDataInputReleased: true, currentRefCount: 2 })', + ' 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', @@ -310,6 +351,50 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' 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', @@ -707,6 +792,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr [ "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'", @@ -718,6 +805,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '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' })", @@ -730,9 +819,20 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '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/src/com.rs b/bindings/js/src/com.rs index 5e143070..8530df0c 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -2025,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())) diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 8a1e5d6f..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, @@ -69,12 +70,18 @@ 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 { @@ -1151,6 +1158,15 @@ unsafe fn read_hglobal_bytes( 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, @@ -1210,16 +1226,39 @@ unsafe extern "system" fn data_object_get_canonical_format_etc( 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: (*input).cfFormat, + cfFormat: 1, ptd: std::ptr::null_mut(), - dwAspect: (*input).dwAspect, - lindex: (*input).lindex, - tymed: (*input).tymed, + dwAspect: 4, + lindex: 7, + tymed: match mode { + 0 => 0, + 1 => u32::MAX, + _ => windows::Win32::System::Com::TYMED_HGLOBAL.0 as u32, + }, }); } - HRESULT(0) + HRESULT(if mode == 4 { 1 } else { 0 }) } unsafe extern "system" fn data_object_set_data( @@ -1311,6 +1350,7 @@ pub fn create_generated_data_object_fake() -> napi::Result { 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); @@ -1325,16 +1365,19 @@ pub fn create_generated_data_object_fake() -> napi::Result { 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 { - let handle_released = |address| { - address != 0 - && unsafe { - windows::Win32::System::Memory::GlobalSize(windows::Win32::Foundation::HGLOBAL( - std::ptr::with_exposed_provenance_mut(address), - )) - } == 0 - }; 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), @@ -1342,17 +1385,179 @@ pub fn generated_data_object_stats() -> GeneratedDataObjectStats { 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: handle_released(DATA_OBJECT_LAST_OUTPUT_HANDLE.load(Ordering::SeqCst)), - get_data_here_input_released: handle_released( + 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: handle_released( + 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/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index f76ab0a6..9c4a551c 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -1718,14 +1718,21 @@ where }, )?)); } else if let Some(value) = format_etc_out_values.remove(&p.value_index) { - result_values.push(NativeCallValue::FormatEtc(value.into_value().map_err( - |error| { - windows_core::Error::new( - windows_core::HRESULT(0x80070057u32 as i32), - &error.message(), - ) - }, - )?)); + 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| { diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index 3b4615f1..883109b9 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -735,12 +735,38 @@ impl FormatEtcOutput { 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 { - windows::Win32::System::Com::CoTaskMemFree(Some(self.raw.ptd.cast())); + OutputCleanup::CoTaskMemFree.cleanup(self.raw.ptd.cast()); } self.raw.ptd = std::ptr::null_mut(); } @@ -5616,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 { @@ -5625,6 +5658,7 @@ impl MethodSignature { parameters: Vec::new(), return_plan: ComReturnPlan::HResult, enumerator_next_vtable_index: None, + canonical_format_etc: None, } } @@ -5860,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, @@ -5956,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() @@ -6015,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, @@ -13889,6 +13959,185 @@ mod tests { ); } + #[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 2d6d7078..3c570f59 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -626,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 @@ -723,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), }); @@ -744,6 +746,7 @@ impl AbiMethodSignature { kind: ParamKind::Out, typ, output_cleanup, + canonical_format_input: None, value_index: self.out_count, input_index: None, }); @@ -762,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), }); @@ -790,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), }); @@ -804,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), }); @@ -956,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 { @@ -974,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) } diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 11cb958e..b5a13ccc 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -336,7 +336,8 @@ Current code registries are migrated without changing behavior: - `IWbemServices::OpenNamespace`; - `IDispatch::Invoke` compound behavior; - `STATSTG` and allocator-specific outputs; -- `IDataObject::SetData` caller-retained STGMEDIUM ownership; and +- `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 @@ -401,19 +402,19 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,336 | -| `exact_registry_dependent` | 356 | +| `standard_derived` | 5,334 | +| `exact_registry_dependent` | 358 | | **Total** | **5,692** | -The registry contains **496 declared entries**, all 496 match the pinned -metadata, and 405 distinct entries are consumed by safe plans. Safe plans have -656 entry/interface dependencies and 405 family/interface dependencies. +The registry contains **498 declared entries**, all 498 match the pinned +metadata, and 407 distinct entries are consumed by safe plans. Safe plans have +659 entry/interface dependencies and 408 family/interface dependencies. Per-interface dependency-set totals also include 5,976 metadata-attribute dependencies and 26,119 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 173 | +| `ownership` | 175 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 7 | @@ -423,7 +424,7 @@ dependencies and 26,119 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: @@ -436,10 +437,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` | 163 | 112 | 117 | +| `com.ownership.v1` | 164 | 113 | 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 | diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 4da6a117..e39aed4d 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -658,7 +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` fixes `fRelease` to `FALSE`. | +| 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. | @@ -680,6 +680,14 @@ 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. + 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. diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 134422c2..2cc9e314 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -358,17 +358,17 @@ classifies all 5,692 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,336 | -| `exact_registry_dependent` | 356 | +| `standard_derived` | 5,334 | +| `exact_registry_dependent` | 358 | -The registry declares 496 selector-specific entries; all 496 match pinned -metadata, 405 distinct entries are safe-consumed, and safe plans contain 656 -entry/interface plus 405 family/interface dependencies. They also consume +The registry declares 498 selector-specific entries; all 498 match pinned +metadata, 407 distinct entries are safe-consumed, and safe plans contain 659 +entry/interface plus 408 family/interface dependencies. They also consume 5,976 metadata-attribute and 26,119 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 173, parameter-direction 45, bounded-two-call 16, +borrowed-handle 54, ownership 175, 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,9 @@ 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. The strict embedded registry lives in `tools/dynwinrt-codegen/contracts/classic-com/`. JSON is the sole source for diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 0bb19500..aba12b9a 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -84,15 +84,15 @@ "safe_incomplete": 2237, "safeEvidence": { "safeComplete": 5692, - "standardDerived": 5336, - "exactRegistryDependent": 356, + "standardDerived": 5334, + "exactRegistryDependent": 358, "metadataFactOccurrences": 5976, "comStandardFactOccurrences": 26119, - "registeredExactEntries": 496, - "metadataMatchedExactEntries": 496, - "safeConsumedExactEntries": 405, - "exactEntryInterfaceDependencies": 656, - "exactFamilyInterfaceDependencies": 405, + "registeredExactEntries": 498, + "metadataMatchedExactEntries": 498, + "safeConsumedExactEntries": 407, + "exactEntryInterfaceDependencies": 659, + "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": 173, + "ownership": 175, "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, @@ -455,6 +455,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, @@ -484,6 +485,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, @@ -520,10 +522,10 @@ "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, - "com.ownership.v1": 117, + "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, @@ -9096,6 +9098,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", @@ -9873,6 +9893,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", diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 5364de08..46ac20e7 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -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,true,standard_derived, -Windows.Win32.System.Ole,IOleCache2,00000128-0000-0000-c000-000000000046,true,standard_derived, +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 diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 428b23af..d901461b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4561,8 +4561,8 @@ mod tests { assert_eq!(report.summary.eligible_interfaces, 7_929); assert_eq!(report.summary.safe_complete, 5_692); assert_eq!(report.summary.safe_evidence.safe_complete, 5_692); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_336); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 356); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_334); + 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, @@ -4576,28 +4576,28 @@ mod tests { report.summary.safe_evidence.com_standard_fact_occurrences, 26_119 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 496); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 498); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 496 + 498 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 405 + 407 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 656 + 659 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 405 + 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(), 173), + ("ownership".into(), 175), ("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"], - 117 + 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(), 405); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 407); assert!( report .summary @@ -4677,7 +4677,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 405 + 407 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 0cf90159..0a93f65a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -456,9 +456,13 @@ pub(super) enum ProjectedComMethodKind { synchronous_flags: i32, semisynchronous_flags: i32, }, - DataObjectSetData { + BorrowedStgMediumInput { release_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 diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index b28f813d..0d153918 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -409,7 +409,8 @@ fn render_js(meta: &ProjectedComInterface) -> String { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } - | ProjectedComMethodKind::DataObjectSetData { .. } => { + | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { emit_method_js(&mut out, method, &iface_var) } ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -775,6 +776,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 { @@ -1234,7 +1244,7 @@ fn emit_method_js_named( } if matches!( method.kind, - ProjectedComMethodKind::DataObjectSetData { + ProjectedComMethodKind::BorrowedStgMediumInput { release_param_index } if release_param_index == index ) { @@ -2420,7 +2430,8 @@ fn render_dts(meta: &ProjectedComInterface) -> String { ProjectedComMethodKind::Normal | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } - | ProjectedComMethodKind::DataObjectSetData { .. } => { + | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { (dts_params(method), dts_return_type(method)) } ProjectedComMethodKind::CallerSuppliedDynamicIid { 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..0c970cf4 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,84 @@ 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 = "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/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 62b3fb6e..84380a39 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, @@ -376,72 +378,77 @@ fn map_method( if let Some(contract) = dynamic_iid { method = method.with_dynamic_iid_contract(contract)?; } - let method = if let Some(contract) = &raw.exact_interface_output_call { - if contract.public_input_param_indices.len() > 3 { - return Err(ModelError::InvalidContract( - "conditional interface output supports at most three public inputs".into(), - )); - } - let mut public_input_params = [None; 3]; - for (target, source) in public_input_params - .iter_mut() - .zip(&contract.public_input_param_indices) - { - *target = Some(ParamIndex::new(*source)); - } - method.with_special_contract(ComMethodSpecialContract::ConditionalInterfaceOutput { - public_input_params, - flags_param: ParamIndex::new(contract.flags_param_index), - context_param: ParamIndex::new(contract.context_param_index), - synchronous_output: contract.synchronous_output_param_index.map(ParamIndex::new), - semisynchronous_output: contract - .semisynchronous_output_param_index - .map(ParamIndex::new), - synchronous_flags: contract.synchronous_flags, - semisynchronous_flags: contract.semisynchronous_flag_value, - }) - } else { - match raw.exact_contract.as_ref().map(|contract| contract.kind) { - Some(RawExactMethodContractKind::FixedCapacityBytes) => { - method.with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { - guid_param: ParamIndex::new(0), - }) - } - Some(RawExactMethodContractKind::UnsafePrivateData) => { - unreachable!("unsafe private-data contracts fail before method mapping") - } - Some(RawExactMethodContractKind::StatStg) => method, - Some(RawExactMethodContractKind::Malloc) => { - method.with_special_contract(ComMethodSpecialContract::Malloc) + let method = + if let Some(contract) = &raw.exact_interface_output_call { + if contract.public_input_param_indices.len() > 3 { + return Err(ModelError::InvalidContract( + "conditional interface output supports at most three public inputs".into(), + )); } - Some(RawExactMethodContractKind::FlagSelectedString) => { - let contract = raw.exact_contract.as_ref().unwrap(); - method.with_special_contract(ComMethodSpecialContract::FlagSelectedString { - discriminator_param: ParamIndex::new( - contract.discriminator_param_index.unwrap(), - ), - reserved_null_param: ParamIndex::new( - contract.reserved_null_param_index.unwrap(), - ), - buffer_param: ParamIndex::new(contract.buffer_param_index), - capacity_param: ParamIndex::new(contract.capacity_param_index), - string_flags: [4, 5], - validation_flag: 6, - }) + let mut public_input_params = [None; 3]; + for (target, source) in public_input_params + .iter_mut() + .zip(&contract.public_input_param_indices) + { + *target = Some(ParamIndex::new(*source)); } - Some(RawExactMethodContractKind::DataObjectSetData) => { - let contract = raw.exact_contract.as_ref().unwrap(); - method.with_special_contract(ComMethodSpecialContract::DataObjectSetData { - release_param: ParamIndex::new( - contract - .ownership_transfer_param_index - .expect("validated SetData ownership-transfer parameter"), - ), - }) + method.with_special_contract(ComMethodSpecialContract::ConditionalInterfaceOutput { + public_input_params, + flags_param: ParamIndex::new(contract.flags_param_index), + context_param: ParamIndex::new(contract.context_param_index), + synchronous_output: contract.synchronous_output_param_index.map(ParamIndex::new), + semisynchronous_output: contract + .semisynchronous_output_param_index + .map(ParamIndex::new), + synchronous_flags: contract.synchronous_flags, + semisynchronous_flags: contract.semisynchronous_flag_value, + }) + } else { + match raw.exact_contract.as_ref().map(|contract| contract.kind) { + Some(RawExactMethodContractKind::FixedCapacityBytes) => method + .with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { + guid_param: ParamIndex::new(0), + }), + Some(RawExactMethodContractKind::UnsafePrivateData) => { + unreachable!("unsafe private-data contracts fail before method mapping") + } + Some(RawExactMethodContractKind::StatStg) => method, + Some(RawExactMethodContractKind::Malloc) => { + method.with_special_contract(ComMethodSpecialContract::Malloc) + } + Some(RawExactMethodContractKind::FlagSelectedString) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::FlagSelectedString { + discriminator_param: ParamIndex::new( + contract.discriminator_param_index.unwrap(), + ), + reserved_null_param: ParamIndex::new( + contract.reserved_null_param_index.unwrap(), + ), + buffer_param: ParamIndex::new(contract.buffer_param_index), + capacity_param: ParamIndex::new(contract.capacity_param_index), + string_flags: [4, 5], + 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::CanonicalFormatEtc) => method + .with_special_contract(ComMethodSpecialContract::CanonicalFormatEtc { + input_param: ParamIndex::new(0), + output_param: ParamIndex::new(1), + }), + None => method, } - None => method, - } - }; + }; Ok(method) } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index abeed3ce..af24470b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -53,9 +53,13 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { synchronous_flags: i32, semisynchronous_flags: i32, }, - DataObjectSetData { + BorrowedStgMediumInput { release_param: ParamIndex, }, + CanonicalFormatEtc { + input_param: ParamIndex, + output_param: ParamIndex, + }, Malloc, } diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index b8a52195..7452a9f8 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -690,11 +690,18 @@ fn project_method( synchronous_flags, semisynchronous_flags, }, - Some(ComMethodSpecialContract::DataObjectSetData { release_param }) => { - ProjectedComMethodKind::DataObjectSetData { + Some(ComMethodSpecialContract::BorrowedStgMediumInput { release_param }) => { + ProjectedComMethodKind::BorrowedStgMediumInput { release_param_index: release_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| { @@ -992,7 +999,7 @@ fn project_method( } if matches!( &kind, - ProjectedComMethodKind::DataObjectSetData { + ProjectedComMethodKind::BorrowedStgMediumInput { release_param_index } if *release_param_index == index ) { @@ -1277,6 +1284,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()), diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 9b47f1c4..ec242eb3 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -381,7 +381,8 @@ pub enum RawExactMethodContractKind { StatStg, Malloc, FlagSelectedString, - DataObjectSetData, + BorrowedStgMediumInput, + CanonicalFormatEtc, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -414,9 +415,12 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::DataObjectSetData => { + | RawExactMethodContractKind::BorrowedStgMediumInput => { crate::contract_registry::ExactFamilyId::Ownership } + RawExactMethodContractKind::CanonicalFormatEtc => { + crate::contract_registry::ExactFamilyId::SemanticHresult + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ExactFamilyId::ShellCommandString } @@ -444,9 +448,12 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::DataObjectSetData => { + | RawExactMethodContractKind::BorrowedStgMediumInput => { crate::contract_registry::ContractKind::Ownership } + RawExactMethodContractKind::CanonicalFormatEtc => { + crate::contract_registry::ContractKind::SemanticHresult + } RawExactMethodContractKind::FlagSelectedString => { crate::contract_registry::ContractKind::FlagSelectedBuffer } @@ -2180,7 +2187,8 @@ fn apply_exact_method_contract( } RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} - RawExactMethodContractKind::DataObjectSetData => {} + RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::CanonicalFormatEtc => {} RawExactMethodContractKind::FlagSelectedString => { let buffer = contract.buffer_param_index; let capacity = contract.capacity_param_index; @@ -2327,13 +2335,29 @@ fn registered_exact_method_contract( "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-imalloc-heapminimize", ), ("Windows.Win32.System.Com", "IDataObject", "SetData") => ( - RawExactMethodContractKind::DataObjectSetData, + 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, @@ -2402,6 +2426,7 @@ fn registered_exact_method_contract( "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", "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", @@ -2421,6 +2446,7 @@ fn registered_exact_method_contract( "IContextMenu" => "IContextMenu", "IMalloc" => "IMalloc", "IDataObject" => "IDataObject", + "IOleCache" => "IOleCache", _ => unreachable!("matched exact method interface"), }, declaring_iid: match kind { @@ -2446,7 +2472,14 @@ fn registered_exact_method_contract( RawExactMethodContractKind::FlagSelectedString => { "000214e4-0000-0000-c000-000000000046" } - RawExactMethodContractKind::DataObjectSetData => "0000010e-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::CanonicalFormatEtc => { + "0000010e-0000-0000-c000-000000000046" + } }, method_name: match kind { RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", @@ -2462,7 +2495,8 @@ fn registered_exact_method_contract( _ => unreachable!("matched exact IMalloc method"), }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", - RawExactMethodContractKind::DataObjectSetData => "SetData", + RawExactMethodContractKind::BorrowedStgMediumInput => "SetData", + RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", }, vtable_index: match (interface, method) { ("IMFAttributes", "GetBlob") => 15, @@ -2481,7 +2515,8 @@ fn registered_exact_method_contract( ("IMalloc", "GetSize") => 6, ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, - ("IDataObject", "SetData") => 7, + ("IDataObject" | "IOleCache", "SetData") => 7, + ("IDataObject", "GetCanonicalFormatEtc") => 6, _ => unreachable!("matched exact method identity"), }, buffer_param_index: buffer, @@ -2491,10 +2526,21 @@ fn registered_exact_method_contract( .then_some(1), reserved_null_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) .then_some(2), - ownership_transfer_param_index: (kind == RawExactMethodContractKind::DataObjectSetData) + ownership_transfer_param_index: (kind + == RawExactMethodContractKind::BorrowedStgMediumInput) .then_some(2), - source_fingerprint: (kind == RawExactMethodContractKind::DataObjectSetData) - .then_some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1"), + source_fingerprint: match (interface, method) { + ("IDataObject", "SetData") => { + Some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1") + } + ("IOleCache", "SetData") => { + Some("AACEA7AC7F8360EE26C559E2EC69F254DF944977174AB767769B40AF899D5573") + } + ("IDataObject", "GetCanonicalFormatEtc") => { + Some("CD6292C4AFD80B76A7C3BA8122D4D98DA02105748829B7F63543A045AE92DDEA") + } + _ => None, + }, citation, reason, }) @@ -2612,6 +2658,28 @@ 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::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, @@ -2780,7 +2848,7 @@ pub(crate) fn validate_exact_method_contract( && raw_u32_scalar(&raw.params[capacity], RawParamDirection::In, false) && raw_hresult(&raw.return_type) } - RawExactMethodContractKind::DataObjectSetData => { + RawExactMethodContractKind::BorrowedStgMediumInput => { raw.params.len() == 3 && raw.params[0].name == "pformatetc" && raw.params[0].direction == RawParamDirection::In @@ -2830,6 +2898,10 @@ pub(crate) fn validate_exact_method_contract( }) && raw_hresult(&raw.return_type) } + 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 @@ -2852,16 +2924,24 @@ pub(crate) fn validate_exact_method_contract( .is_some_and(|index| index < raw.params.len()) } RawExactMethodContractKind::Malloc => true, - RawExactMethodContractKind::DataObjectSetData => { + 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::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 { @@ -4998,6 +5078,69 @@ mod tests { .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.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(); + 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..6 { + 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, + _ => 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 426e3767..f9ff7891 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -492,12 +492,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", @@ -1140,7 +1142,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(), 496); + assert_eq!(ids.len(), 498); 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 903cecd0..78800392 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2148,7 +2148,7 @@ fn data_object_projects_hglobal_format_and_medium_values() { .expect("SetData must carry exact ownership evidence"); assert_eq!( set_data_contract.kind, - com_metadata::RawExactMethodContractKind::DataObjectSetData + com_metadata::RawExactMethodContractKind::BorrowedStgMediumInput ); assert_eq!(set_data_contract.ownership_transfer_param_index, Some(2)); assert!( @@ -2177,6 +2177,17 @@ fn data_object_projects_hglobal_format_and_medium_values() { .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(), @@ -2190,6 +2201,61 @@ fn data_object_projects_hglobal_format_and_medium_values() { assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); } +#[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() { From b82ae8621c2752096731f3007ac8562c8500c060 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Mon, 7 Sep 2026 11:32:26 +0800 Subject: [PATCH 7/8] Require exact contracts for STGMEDIUM InOut Pin IDataObject::GetDataHere to caller-owned, non-replacing HGLOBAL storage. Reject unproven STGMEDIUM InOut projections such as IWiaDataTransfer, preserve the existing runtime API, and update capability evidence and coverage baselines. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 28 ++-- README.md | 4 +- .../classic-com-contract-evidence-registry.md | 29 ++-- docs/architecture/classic-com-support.md | 21 ++- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 44 +++--- .../classic-com-capability-summary.json | 79 ++++++---- .../classic-com-interface-support.csv | 2 +- .../src/codegen/com/capability.rs | 37 +++-- .../src/codegen/com/generated_unsafe.rs | 2 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 3 + .../src/codegen/com/javascript/render.rs | 2 + .../codegen/com/javascript/render_tests.rs | 29 ++++ .../src/codegen/com/model/metadata.rs | 143 +++++++++--------- .../src/codegen/com/model/method.rs | 64 +++++++- .../src/codegen/com/project/mod.rs | 13 +- tools/dynwinrt-codegen/src/com_metadata.rs | 46 +++++- .../dynwinrt-codegen/src/contract_registry.rs | 3 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 78 ++++++++++ 18 files changed, 450 insertions(+), 177 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b09920f0..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 5692) { + 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 5692) { + 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 5692 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2237 + @($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, 1437, 388) - i686 = @(411, 1414, 412) - arm64 = @(412, 1437, 388) + x64 = @(412, 1437, 389) + i686 = @(411, 1414, 413) + arm64 = @(412, 1437, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -134,15 +134,15 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5692 -or - $result.safeEvidence.standardDerived -ne 5334 -or + $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 26119 -or - $result.safeEvidence.registeredExactEntries -ne 498 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 498 -or - $result.safeEvidence.safeConsumedExactEntries -ne 407 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 659 -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 54aa8ff3..a5ad2321 100644 --- a/README.md +++ b/README.md @@ -142,8 +142,8 @@ is not a general Automation or native Win32 projection, and it does not project flat DLL exports. The current CI baseline against -`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,692 of 7,929 -eligible interfaces (71.79%)** 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, the diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index b5a13ccc..a380e6cd 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -336,12 +336,13 @@ Current code registries are migrated without changing behavior: - `IWbemServices::OpenNamespace`; - `IDispatch::Invoke` compound behavior; - `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,692/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 @@ -402,19 +403,19 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,334 | +| `standard_derived` | 5,333 | | `exact_registry_dependent` | 358 | -| **Total** | **5,692** | +| **Total** | **5,691** | -The registry contains **498 declared entries**, all 498 match the pinned -metadata, and 407 distinct entries are consumed by safe plans. Safe plans have -659 entry/interface dependencies and 408 family/interface 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,119 COM-standard-rule dependencies. +dependencies and 26,114 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 175 | +| `ownership` | 176 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 7 | @@ -437,7 +438,7 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 164 | 113 | 119 | +| `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` | 2 | 2 | 3 | @@ -455,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,574 | -| `com.interface.input-borrow.v1` | 1,891 | -| `com.interface.typed-output-plus-one.v1` | 3,458 | -| `com.iunknown.identity-refcount.v1` | 5,692 | -| `com.query-interface.output-plus-one.v1` | 5,692 | +| `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 e39aed4d..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,692 complete safe -> interface projections out of 7,929 eligible interfaces (71.79%). 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,7 +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`; `GetDataHere` preserves caller allocation; exact IID/slot/shape/fingerprint evidence pins `SetData.fRelease=FALSE` | `DVTARGETDEVICE`, non-HGLOBAL media, JavaScript callback implementation, and ownership-transfer input | +| 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 | @@ -688,6 +688,14 @@ 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. @@ -1235,13 +1243,14 @@ 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 that census to 5,681. The dedicated target-device-independent -`TYMED_HGLOBAL` FORMATETC/STGMEDIUM model promotes 11 more interfaces, bringing -the current literal census to **5,692 / 7,929 = 71.787111%**. The result remains +`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,692, or coverage +if the denominator changes, complete generation drops below 5,691, or coverage falls below 70%. ## Public-code frequency snapshot diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 2cc9e314..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,692 | 71.79% | -| Rejected because at least one contract is incomplete | 2,237 | 28.21% | +| 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,692 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: @@ -348,25 +348,25 @@ 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,067 executable manual methods**, **0 remaining portable manual-classified methods omitted**, -and **1,160 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,692 safe-complete interfaces exactly once: +classifies all 5,691 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,334 | +| `standard_derived` | 5,333 | | `exact_registry_dependent` | 358 | -The registry declares 498 selector-specific entries; all 498 match pinned -metadata, 407 distinct entries are safe-consumed, and safe plans contain 659 +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,119 universal COM-rule dependency sets. +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 175, 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 3, and compound-dispatch 1. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary @@ -381,6 +381,10 @@ 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 @@ -397,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,692 of 7,929 interfaces. The separate outbound raw census -classifies the 2,237 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,437 | 388 | -| i686 | 411 | 1,414 | 412 | -| ARM64 | 412 | 1,437 | 388 | +| x64 | 412 | 1,437 | 389 | +| i686 | 411 | 1,414 | 413 | +| ARM64 | 412 | 1,437 | 389 | -Including safe-complete interfaces, x64 and ARM64 have 6,104 -metadata-complete, 1,437 manual, and 388 blocked interfaces. i686 has 6,103 -metadata-complete, 1,414 manual, and 412 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 @@ -425,7 +429,7 @@ External pointer/callback requirements affect 1,089 x64/ARM64 interfaces and 1,090 i686 interfaces; 6,804 require external acquisition and all 7,929 retain the current-apartment rule. -For all 5,692 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, @@ -512,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,692 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 aba12b9a..9332ea9c 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -80,18 +80,18 @@ "parsed_interface_identities": 7944, "eligible_interfaces": 7929, "not_addressable": 15, - "safe_complete": 5692, - "safe_incomplete": 2237, + "safe_complete": 5691, + "safe_incomplete": 2238, "safeEvidence": { - "safeComplete": 5692, - "standardDerived": 5334, + "safeComplete": 5691, + "standardDerived": 5333, "exactRegistryDependent": 358, "metadataFactOccurrences": 5976, - "comStandardFactOccurrences": 26119, - "registeredExactEntries": 498, - "metadataMatchedExactEntries": 498, - "safeConsumedExactEntries": 407, - "exactEntryInterfaceDependencies": 659, + "comStandardFactOccurrences": 26114, + "registeredExactEntries": 499, + "metadataMatchedExactEntries": 499, + "safeConsumedExactEntries": 408, + "exactEntryInterfaceDependencies": 660, "exactFamilyInterfaceDependencies": 408, "byContractKind": { "borrowed-handle": 54, @@ -102,7 +102,7 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 2, - "ownership": 175, + "ownership": 176, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 @@ -445,6 +445,7 @@ "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, @@ -543,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": 5574, - "com.interface.input-borrow.v1": 1891, - "com.interface.typed-output-plus-one.v1": 3458, - "com.iunknown.identity-refcount.v1": 5692, - "com.query-interface.output-plus-one.v1": 5692, + "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": { @@ -8912,6 +8913,24 @@ "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", @@ -10708,37 +10727,37 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6104, + "raw_metadata_complete": 6103, "raw_manual_contract": 1437, - "raw_runtime_blocked": 388, + "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, "safe_incomplete_raw_manual_contract": 1437, - "safe_incomplete_raw_runtime_blocked": 388 + "safe_incomplete_raw_runtime_blocked": 389 }, "i686": { - "raw_metadata_complete": 6103, + "raw_metadata_complete": 6102, "raw_manual_contract": 1414, - "raw_runtime_blocked": 412, + "raw_runtime_blocked": 413, "safe_incomplete_raw_metadata_complete": 411, "safe_incomplete_raw_manual_contract": 1414, - "safe_incomplete_raw_runtime_blocked": 412 + "safe_incomplete_raw_runtime_blocked": 413 }, "x64": { - "raw_metadata_complete": 6104, + "raw_metadata_complete": 6103, "raw_manual_contract": 1437, - "raw_runtime_blocked": 388, + "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, "safe_incomplete_raw_manual_contract": 1437, - "safe_incomplete_raw_runtime_blocked": 388 + "safe_incomplete_raw_runtime_blocked": 389 } }, "blocker_reason_counts": { "arm64": { - "incomplete_pointee_layout_for_storage": 337, + "incomplete_pointee_layout_for_storage": 338, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 240, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10747,11 +10766,11 @@ "unsupported_layout_kind": 4 }, "i686": { - "incomplete_pointee_layout_for_storage": 361, + "incomplete_pointee_layout_for_storage": 362, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 240, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, @@ -10760,11 +10779,11 @@ "unsupported_layout_kind": 4 }, "x64": { - "incomplete_pointee_layout_for_storage": 337, + "incomplete_pointee_layout_for_storage": 338, "missing_declaring_iid": 46, "missing_interface_iid": 73, "missing_layout": 5, - "pointee_missing_layout": 240, + "pointee_missing_layout": 241, "pointee_unknown_native_type": 4, "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 45, diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 46ac20e7..6dac20cf 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -274,7 +274,7 @@ Windows.Win32.Devices.ImageAcquisition,IEnumWiaItem,5e8383fc-3391-11d2-9a33-00c0 Windows.Win32.Devices.ImageAcquisition,IEnumWiaItem2,59970af4-cd0d-44d9-ab24-52295630e582,true,exact_registry_dependent, Windows.Win32.Devices.ImageAcquisition,IWiaAppErrorHandler,6c16186c-d0a6-400c-80f4-d26986a0e734,true,exact_registry_dependent, Windows.Win32.Devices.ImageAcquisition,IWiaDataCallback,a558a866-a5b0-11d2-a08f-00c04f72dc3c,true,standard_derived, -Windows.Win32.Devices.ImageAcquisition,IWiaDataTransfer,a6cef998-a5b0-11d2-a08f-00c04f72dc3c,true,standard_derived, +Windows.Win32.Devices.ImageAcquisition,IWiaDataTransfer,a6cef998-a5b0-11d2-a08f-00c04f72dc3c,false,,incomplete_pointee_layout_for_storage Windows.Win32.Devices.ImageAcquisition,IWiaDevMgr,5eb2502a-8cf1-11d1-bf92-0060081ed811,false,,safe_projection_incomplete Windows.Win32.Devices.ImageAcquisition,IWiaDevMgr2,79c07cf1-cbdd-41ee-8ec3-f00080cada7a,false,,safe_projection_incomplete Windows.Win32.Devices.ImageAcquisition,IWiaDrvItem,1f02b5c5-b00c-11d2-a094-00c04f72dc3c,false,,missing_allocator diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index d901461b..1a7fd2ae 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4559,9 +4559,9 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_692); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_692); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_334); + 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 @@ -4574,23 +4574,23 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_119 + 26_114 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 498); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 499); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 498 + 499 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 407 + 408 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 659 + 660 ); assert_eq!( report @@ -4610,7 +4610,7 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 2), - ("ownership".into(), 175), + ("ownership".into(), 176), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 3), @@ -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(), 407); + 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(), - 407 + 408 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( @@ -4759,6 +4759,19 @@ mod tests { 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 @@ -4828,7 +4841,7 @@ mod tests { ( 412 - usize::from(target == CensusTarget::I686), 1_437 - 23 * usize::from(target == CensusTarget::I686), - 388 + 24 * 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 c964c32b..42d6124f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -2327,7 +2327,7 @@ mod tests { ); assert_eq!(coverage.executable_manual_methods, 6_067); assert_eq!(coverage.remaining_manual_methods, 0); - assert_eq!(coverage.runtime_blocked_methods, 1_160); + 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 0a93f65a..91adc38a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -459,6 +459,9 @@ pub(super) enum ProjectedComMethodKind { BorrowedStgMediumInput { release_param_index: usize, }, + PreservedStgMediumInOut { + medium_param_index: usize, + }, CanonicalFormatEtc { input_param_index: usize, output_param_index: usize, diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index 0d153918..1995100b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -410,6 +410,7 @@ fn render_js(meta: &ProjectedComInterface) -> String { | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::PreservedStgMediumInOut { .. } | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { emit_method_js(&mut out, method, &iface_var) } @@ -2431,6 +2432,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { | ProjectedComMethodKind::FixedCapacityBytes { .. } | ProjectedComMethodKind::OwningCallerOutput { .. } | ProjectedComMethodKind::BorrowedStgMediumInput { .. } + | ProjectedComMethodKind::PreservedStgMediumInOut { .. } | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { (dts_params(method), dts_return_type(method)) } 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 0c970cf4..52e82bea 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -248,6 +248,35 @@ fn storage_medium_result_rules_and_borrowing_are_serialized_from_ir() { 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 { diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 84380a39..3e1f1157 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -378,77 +378,84 @@ fn map_method( if let Some(contract) = dynamic_iid { method = method.with_dynamic_iid_contract(contract)?; } - let method = - if let Some(contract) = &raw.exact_interface_output_call { - if contract.public_input_param_indices.len() > 3 { - return Err(ModelError::InvalidContract( - "conditional interface output supports at most three public inputs".into(), - )); + let method = if let Some(contract) = &raw.exact_interface_output_call { + if contract.public_input_param_indices.len() > 3 { + return Err(ModelError::InvalidContract( + "conditional interface output supports at most three public inputs".into(), + )); + } + let mut public_input_params = [None; 3]; + for (target, source) in public_input_params + .iter_mut() + .zip(&contract.public_input_param_indices) + { + *target = Some(ParamIndex::new(*source)); + } + method.with_special_contract(ComMethodSpecialContract::ConditionalInterfaceOutput { + public_input_params, + flags_param: ParamIndex::new(contract.flags_param_index), + context_param: ParamIndex::new(contract.context_param_index), + synchronous_output: contract.synchronous_output_param_index.map(ParamIndex::new), + semisynchronous_output: contract + .semisynchronous_output_param_index + .map(ParamIndex::new), + synchronous_flags: contract.synchronous_flags, + semisynchronous_flags: contract.semisynchronous_flag_value, + }) + } else { + match raw.exact_contract.as_ref().map(|contract| contract.kind) { + Some(RawExactMethodContractKind::FixedCapacityBytes) => { + method.with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { + guid_param: ParamIndex::new(0), + }) } - let mut public_input_params = [None; 3]; - for (target, source) in public_input_params - .iter_mut() - .zip(&contract.public_input_param_indices) - { - *target = Some(ParamIndex::new(*source)); + Some(RawExactMethodContractKind::UnsafePrivateData) => { + unreachable!("unsafe private-data contracts fail before method mapping") } - method.with_special_contract(ComMethodSpecialContract::ConditionalInterfaceOutput { - public_input_params, - flags_param: ParamIndex::new(contract.flags_param_index), - context_param: ParamIndex::new(contract.context_param_index), - synchronous_output: contract.synchronous_output_param_index.map(ParamIndex::new), - semisynchronous_output: contract - .semisynchronous_output_param_index - .map(ParamIndex::new), - synchronous_flags: contract.synchronous_flags, - semisynchronous_flags: contract.semisynchronous_flag_value, - }) - } else { - match raw.exact_contract.as_ref().map(|contract| contract.kind) { - Some(RawExactMethodContractKind::FixedCapacityBytes) => method - .with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { - guid_param: ParamIndex::new(0), - }), - Some(RawExactMethodContractKind::UnsafePrivateData) => { - unreachable!("unsafe private-data contracts fail before method mapping") - } - Some(RawExactMethodContractKind::StatStg) => method, - Some(RawExactMethodContractKind::Malloc) => { - method.with_special_contract(ComMethodSpecialContract::Malloc) - } - Some(RawExactMethodContractKind::FlagSelectedString) => { - let contract = raw.exact_contract.as_ref().unwrap(); - method.with_special_contract(ComMethodSpecialContract::FlagSelectedString { - discriminator_param: ParamIndex::new( - contract.discriminator_param_index.unwrap(), - ), - reserved_null_param: ParamIndex::new( - contract.reserved_null_param_index.unwrap(), - ), - buffer_param: ParamIndex::new(contract.buffer_param_index), - capacity_param: ParamIndex::new(contract.capacity_param_index), - string_flags: [4, 5], - 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::CanonicalFormatEtc) => method - .with_special_contract(ComMethodSpecialContract::CanonicalFormatEtc { - input_param: ParamIndex::new(0), - output_param: ParamIndex::new(1), - }), - None => method, + Some(RawExactMethodContractKind::StatStg) => method, + Some(RawExactMethodContractKind::Malloc) => { + method.with_special_contract(ComMethodSpecialContract::Malloc) } - }; + Some(RawExactMethodContractKind::FlagSelectedString) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::FlagSelectedString { + discriminator_param: ParamIndex::new( + contract.discriminator_param_index.unwrap(), + ), + reserved_null_param: ParamIndex::new( + contract.reserved_null_param_index.unwrap(), + ), + buffer_param: ParamIndex::new(contract.buffer_param_index), + capacity_param: ParamIndex::new(contract.capacity_param_index), + string_flags: [4, 5], + 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, + } + }; Ok(method) } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index af24470b..13477a8d 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -56,6 +56,9 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { BorrowedStgMediumInput { release_param: ParamIndex, }, + PreservedStgMediumInOut { + medium_param: ParamIndex, + }, CanonicalFormatEtc { input_param: ParamIndex, output_param: ParamIndex, @@ -148,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( @@ -1015,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/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 7452a9f8..2a69113f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -695,6 +695,11 @@ fn project_method( 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, @@ -1007,7 +1012,13 @@ fn project_method( } if direction == ComParamDirection::InOut && !is_scalar_in_out(&typ) - && !matches!(typ, ComType::StgMedium) + && !matches!( + (&typ, &kind), + ( + ComType::StgMedium, + ProjectedComMethodKind::PreservedStgMediumInOut { medium_param_index } + ) if *medium_param_index == index + ) { return Err(format!( "{}: unsupported [in, out] parameter `{}`", diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index ec242eb3..8a4f73e1 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -382,6 +382,7 @@ pub enum RawExactMethodContractKind { Malloc, FlagSelectedString, BorrowedStgMediumInput, + PreservedStgMediumInOut, CanonicalFormatEtc, } @@ -415,7 +416,8 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::BorrowedStgMediumInput => { + | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ExactFamilyId::Ownership } RawExactMethodContractKind::CanonicalFormatEtc => { @@ -448,7 +450,8 @@ impl RawExactMethodContract { } RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc - | RawExactMethodContractKind::BorrowedStgMediumInput => { + | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ContractKind::Ownership } RawExactMethodContractKind::CanonicalFormatEtc => { @@ -2188,6 +2191,7 @@ fn apply_exact_method_contract( RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc => {} RawExactMethodContractKind::FlagSelectedString => { let buffer = contract.buffer_param_index; @@ -2334,6 +2338,14 @@ 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, @@ -2477,7 +2489,8 @@ fn registered_exact_method_contract( "IOleCache" => "0000011e-0000-0000-c000-000000000046", _ => unreachable!("matched exact borrowed STGMEDIUM input"), }, - RawExactMethodContractKind::CanonicalFormatEtc => { + RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc => { "0000010e-0000-0000-c000-000000000046" } }, @@ -2496,6 +2509,7 @@ fn registered_exact_method_contract( }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", RawExactMethodContractKind::BorrowedStgMediumInput => "SetData", + RawExactMethodContractKind::PreservedStgMediumInOut => "GetDataHere", RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", }, vtable_index: match (interface, method) { @@ -2516,6 +2530,7 @@ fn registered_exact_method_contract( ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, ("IDataObject" | "IOleCache", "SetData") => 7, + ("IDataObject", "GetDataHere") => 4, ("IDataObject", "GetCanonicalFormatEtc") => 6, _ => unreachable!("matched exact method identity"), }, @@ -2530,6 +2545,9 @@ fn registered_exact_method_contract( == RawExactMethodContractKind::BorrowedStgMediumInput) .then_some(2), source_fingerprint: match (interface, method) { + ("IDataObject", "GetDataHere") => { + Some("65165D814B216835E273E9342B4CBEC2A4F6F1A68477F3F07036C2479BDADBFF") + } ("IDataObject", "SetData") => { Some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1") } @@ -2668,6 +2686,7 @@ pub(crate) fn validate_storage_medium_contract_presence(raw: &RawComMethod) -> R matches!( contract.kind, RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc ) }); @@ -2898,6 +2917,10 @@ pub(crate) fn validate_exact_method_contract( }) && 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" @@ -2931,7 +2954,8 @@ pub(crate) fn validate_exact_method_contract( && contract.discriminator_param_index.is_none() && contract.reserved_null_param_index.is_none() } - RawExactMethodContractKind::CanonicalFormatEtc => { + RawExactMethodContractKind::PreservedStgMediumInOut + | RawExactMethodContractKind::CanonicalFormatEtc => { contract.buffer_param_index == 1 && contract.ownership_transfer_param_index.is_none() && contract.actual_length_param_index.is_none() @@ -5088,6 +5112,7 @@ mod tests { }; 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"), ( @@ -5104,7 +5129,13 @@ mod tests { .iter() .find(|method| method.metadata_name == method_name) .unwrap(); - let contract = method.exact_contract.as_ref().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, @@ -5114,7 +5145,7 @@ mod tests { ) { errors.push(format!("{error}: {}", raw_method_shape(method))); } - for mutation in 0..6 { + for mutation in 0..9 { let mut drift = method.clone(); match mutation { 0 => drift.declaring_iid = "00000000-0000-0000-0000-000000000001".into(), @@ -5123,6 +5154,9 @@ mod tests { 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!( diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index f9ff7891..34956b03 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -482,6 +482,7 @@ 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", @@ -1142,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(), 498); + 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 78800392..21b53c50 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2201,6 +2201,84 @@ fn data_object_projects_hglobal_format_and_medium_values() { 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() { From 047bcb69fdb351abd745e3948862f170aabb8554 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Mon, 7 Sep 2026 13:19:42 +0800 Subject: [PATCH 8/8] Support device-default audio formats in Record Add exact nullable-input contracts for IMDSPDeviceControl and IWMDMDeviceControl Record. Preserve nullability through generated declarations, COM signatures and native pointer marshalling while keeping other audio-format inputs required. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 14 +- bindings/js/Cargo.toml | 2 +- .../generated-unsafe-companion.e2e.ts | 84 +++++- bindings/js/src/com.rs | 8 + .../js/src/generated_unsafe_test_hooks.rs | 241 ++++++++++++++++++ crates/dynwinrt/src/call.rs | 12 +- crates/dynwinrt/src/com.rs | 122 ++++++++- crates/dynwinrt/src/native_call.rs | 43 +++- .../classic-com-contract-evidence-registry.md | 17 +- docs/architecture/classic-com-support.md | 11 +- docs/guides/windows/classic-com-usage.md | 6 + docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 15 +- .../classic-com-capability-summary.json | 55 +++- .../classic-com-interface-support.csv | 4 +- .../src/codegen/com/capability.rs | 24 +- .../src/codegen/com/javascript/render.rs | 3 + .../codegen/com/javascript/render_tests.rs | 44 ++++ .../src/codegen/com/model/metadata.rs | 15 +- .../src/codegen/com/project/mod.rs | 11 +- tools/dynwinrt-codegen/src/com_metadata.rs | 105 +++++++- .../dynwinrt-codegen/src/contract_registry.rs | 7 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 63 +++++ 22 files changed, 826 insertions(+), 80 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1aba23b4..f62b7588 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -135,15 +135,15 @@ jobs: } if ( $result.safeEvidence.safeComplete -ne 5696 -or - $result.safeEvidence.standardDerived -ne 5335 -or - $result.safeEvidence.exactRegistryDependent -ne 361 -or + $result.safeEvidence.standardDerived -ne 5333 -or + $result.safeEvidence.exactRegistryDependent -ne 363 -or $result.safeEvidence.metadataFactOccurrences -ne 5982 -or $result.safeEvidence.comStandardFactOccurrences -ne 26129 -or - $result.safeEvidence.registeredExactEntries -ne 502 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 502 -or - $result.safeEvidence.safeConsumedExactEntries -ne 411 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 667 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 414 + $result.safeEvidence.registeredExactEntries -ne 504 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 504 -or + $result.safeEvidence.safeConsumedExactEntries -ne 413 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 669 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 416 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index 69d4771b..a9be7a15 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = ["windows/Win32_System_Wmi"] +test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager"] [dependencies] napi = { version = "3", features = ["napi7"] } diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 903ffb64..593c807b 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -33,7 +33,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr '--winmd', winmd!, '--class-name', - 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext', + 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext,Windows.Win32.Media.DeviceManager.IMDSPDeviceControl,Windows.Win32.Media.DeviceManager.IWMDMDeviceControl', '--output', output, ] @@ -95,6 +95,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr const wbemClassObjectBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'system', 'wmi', 'IWbemClassObjectUnsafe') const thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') const audioBase = join(output, 'com', 'windows', 'win32', 'media', 'audio', 'IAudioClient') + const mdspDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IMDSPDeviceControl') + const wmdmDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IWMDMDeviceControl') const evaluationBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'ai', 'machine-learning', 'win-ml', 'IWinMLEvaluationContextUnsafe') const runner = join(output, 'generated-companion-runner.cjs') writeFileSync( @@ -116,6 +118,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr `const wbemClassObject = require(${JSON.stringify(`${wbemClassObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, + `const mdspDeviceControl = require(${JSON.stringify(`${mdspDeviceControlBase}.js`)})`, + `const wmdmDeviceControl = require(${JSON.stringify(`${wmdmDeviceControlBase}.js`)})`, `const evaluation = require(${JSON.stringify(`${evaluationBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, `const cjsBarrel = require(${JSON.stringify(join(output, 'com', 'unsafe', 'index.js'))})`, @@ -140,6 +144,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ` const esmWbemClassObject = await import(pathToFileURL(${JSON.stringify(`${wbemClassObjectBase}.js`)}).href)`, ` const esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, + ` const esmMdspDeviceControl = await import(pathToFileURL(${JSON.stringify(`${mdspDeviceControlBase}.js`)}).href)`, + ` const esmWmdmDeviceControl = await import(pathToFileURL(${JSON.stringify(`${wmdmDeviceControlBase}.js`)}).href)`, ` const esmEvaluation = await import(pathToFileURL(${JSON.stringify(`${evaluationBase}.js`)}).href)`, ` 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)`, @@ -151,10 +157,16 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr " assert.equal(typeof wbemClassObject.IWbemClassObjectUnsafe, 'function')", " assert.equal(typeof thumbnail.IThumbnailProvider, 'function')", " assert.equal(typeof audio.IAudioClient, 'function')", + " assert.equal(typeof mdspDeviceControl.IMDSPDeviceControl, 'function')", + " assert.equal(typeof wmdmDeviceControl.IWMDMDeviceControl, 'function')", " assert.equal(typeof evaluation.IWinMLEvaluationContextUnsafe, 'function')", ' assert.equal(esmAudio.IAudioClient, audio.IAudioClient)', + ' assert.equal(esmMdspDeviceControl.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(esmWmdmDeviceControl.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(esmEvaluation.IWinMLEvaluationContextUnsafe, evaluation.IWinMLEvaluationContextUnsafe)', ' assert.equal(safeBarrel.IAudioClient, audio.IAudioClient)', + ' assert.equal(safeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(safeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(safeBarrel.IDataObject, dataObject.IDataObject)', ' assert.equal(safeBarrel.IOleCache, oleCache.IOleCache)', @@ -171,6 +183,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ' assert.equal(esmWbemClassObject.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmSafeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(esmSafeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(esmSafeBarrel.IOleCache, oleCache.IOleCache)', ' assert.equal(esmSafeBarrel.IOleCache2, oleCache2.IOleCache2)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', @@ -357,6 +371,51 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr ' dataObjectWrapper?.release()', ' dataObjectFake?.release()', ' }', + ' const deviceControlFixtures = [', + " [mdspDeviceControl.IMDSPDeviceControl, runtime.createGeneratedMdspDeviceControlFake, runtime.generatedMdspDeviceControlStats, '1dcb3a04-33ed-11d3-8470-00c04f79dbc0'],", + " [wmdmDeviceControl.IWMDMDeviceControl, runtime.createGeneratedWmdmDeviceControlFake, runtime.generatedWmdmDeviceControlStats, '1dcb3a14-33ed-11d3-8470-00c04f79dbc0'],", + ' ]', + ' for (const [DeviceControl, createControl, controlStats, unrelatedIid] of deviceControlFixtures) {', + " assert.equal(typeof createControl, 'function')", + " assert.equal(typeof controlStats, 'function')", + ' let controlFake = createControl()', + ' let controlUnknown', + ' let controlWrapper', + ' try {', + ' assert.equal(controlStats().currentRefCount, 1)', + ' assert.throws(() => controlFake.cast(WinGuid.parse(unrelatedIid)), /interface|0x80004002/i)', + ' assert.equal(controlStats().currentRefCount, 1)', + " controlUnknown = controlFake.cast(WinGuid.parse('00000000-0000-0000-c000-000000000046'))", + ' assert.equal(controlStats().currentRefCount, 2)', + ' controlUnknown.release()', + ' controlUnknown = undefined', + ' assert.equal(controlStats().currentRefCount, 1)', + ' controlWrapper = DeviceControl._fromNative(controlFake)', + ' assert.equal(controlStats().currentRefCount, 2)', + ' const pcm = DynComAudioFormat.pcm(2, 48000, 16)', + ' const originalPcm = pcm.toBuffer()', + ' assert.equal(controlWrapper.record(null), undefined)', + ' const afterDefault = controlStats()', + ' assert.deepEqual([afterDefault.recordCalls, afterDefault.nullFormatCalls, afterDefault.explicitFormatCalls, afterDefault.currentRefCount], [1, 1, 0, 2])', + ' assert.deepEqual(pcm.toBuffer(), originalPcm)', + ' assert.equal(controlWrapper.record(pcm), undefined)', + ' const afterExplicit = controlStats()', + ' assert.deepEqual([afterExplicit.recordCalls, afterExplicit.nullFormatCalls, afterExplicit.explicitFormatCalls, afterExplicit.currentRefCount], [2, 1, 1, 2])', + ' assert.deepEqual(pcm.toBuffer(), originalPcm)', + ' controlWrapper.release()', + ' controlWrapper = undefined', + ' assert.equal(controlStats().currentRefCount, 1)', + ' controlFake.release()', + ' controlFake = undefined', + ' const released = controlStats()', + ' assert.equal(released.currentRefCount, 0)', + ' assert.equal(released.releaseCalls, released.addRefCalls + 1)', + ' } finally {', + ' controlWrapper?.release()', + ' controlUnknown?.release()', + ' controlFake?.release()', + ' }', + ' }', ' const createSafeAudio = runtime.createGeneratedAudioClientFake', ' const safeAudioStats = runtime.generatedAudioClientStats', ' const setFormatSupportMode = runtime.setGeneratedAudioClientFormatSupportMode', @@ -840,6 +899,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr "import { IOleCache2 } from './com/windows/win32/system/ole/IOleCache2.js'", "import { IThumbnailProvider } from './com/windows/win32/ui/shell/IThumbnailProvider.js'", "import { IAudioClient } from './com/windows/win32/media/audio/IAudioClient.js'", + "import { IMDSPDeviceControl } from './com/windows/win32/media/device-manager/IMDSPDeviceControl.js'", + "import { IWMDMDeviceControl } from './com/windows/win32/media/device-manager/IWMDMDeviceControl.js'", "import { IWinMLEvaluationContextUnsafe } from './com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js'", "import { IWbemServices as FromBarrel } from './com/index.js'", "import { UnsafePointee, UnsafePointerOutput } from './com/unsafe/runtime.js'", @@ -852,6 +913,8 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr 'declare const dataObjects: IDataObject', 'declare const oleCaches: IOleCache', 'declare const oleCaches2: IOleCache2', + 'declare const mdspControl: IMDSPDeviceControl', + 'declare const wmdmControl: IWMDMDeviceControl', 'const direct: IWbemServices = IWbemServices._fromNative(native)', 'const barrel: FromBarrel = FromBarrel._fromNative(native)', "const namespaceOutput = direct.openNamespace('root', { mode: 'sync' })", @@ -872,6 +935,25 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', 'const audio = IAudioClient._fromNative(native)', 'audio.isFormatSupported(0, DynComAudioFormat.pcm(2, 48_000, 16))', + '// @ts-expect-error IsFormatSupported still requires an explicit audio format', + 'audio.isFormatSupported(0, null)', + 'const pcm = DynComAudioFormat.pcm(2, 48_000, 16)', + 'const mdspDefaultResult: void = mdspControl.record(null)', + 'const mdspPcmResult: void = mdspControl.record(pcm)', + 'const wmdmDefaultResult: void = wmdmControl.record(null)', + 'const wmdmPcmResult: void = wmdmControl.record(pcm)', + 'void mdspDefaultResult', + 'void mdspPcmResult', + 'void wmdmDefaultResult', + 'void wmdmPcmResult', + '// @ts-expect-error Record accepts an audio format or null, not a plain object', + 'mdspControl.record({})', + '// @ts-expect-error Record does not accept an unrelated COM format value', + 'wmdmControl.record(format)', + '// @ts-expect-error selecting the default format requires explicit null', + 'mdspControl.record()', + '// @ts-expect-error selecting the default format requires explicit null', + 'wmdmControl.record()', 'const unsafeEvaluation = IWinMLEvaluationContextUnsafe.from(native)', 'const cacheSetResult: void = oleCaches.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', 'const cache2SetResult: void = oleCaches2.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 7811f012..10951ef9 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -5894,6 +5894,14 @@ impl DynCom { ) } + #[napi] + pub fn null_audio_format() -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::WinRt(dynwinrt::WinRTValue::Null), + dynwinrt::com::PointerOutputKind::None, + ) + } + #[napi] pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { let result = value diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 33b75fde..339a9ebc 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -8,6 +8,12 @@ use std::{ use napi::bindgen_prelude::BigInt; use napi_derive::napi; +use windows::Win32::Media::{ + Audio::WAVEFORMATEX, + DeviceManager::{ + IMDSPDeviceControl, IMDSPDeviceControl_Vtbl, IWMDMDeviceControl, IWMDMDeviceControl_Vtbl, + }, +}; use windows::{ core::{IUnknown, IUnknown_Vtbl, Interface, BOOL, GUID, HRESULT, PCWSTR}, Win32::System::{ @@ -1566,6 +1572,241 @@ pub fn generated_ole_cache_stats() -> GeneratedOleCacheStats { } } +struct DeviceControlCounters { + record_calls: AtomicU32, + null_format_calls: AtomicU32, + explicit_format_calls: AtomicU32, + add_ref_calls: AtomicU32, + release_calls: AtomicU32, + current_ref_count: AtomicU32, +} + +impl DeviceControlCounters { + const fn new() -> Self { + Self { + record_calls: AtomicU32::new(0), + null_format_calls: AtomicU32::new(0), + explicit_format_calls: AtomicU32::new(0), + add_ref_calls: AtomicU32::new(0), + release_calls: AtomicU32::new(0), + current_ref_count: AtomicU32::new(0), + } + } + + fn reset(&self) { + for counter in [ + &self.record_calls, + &self.null_format_calls, + &self.explicit_format_calls, + &self.add_ref_calls, + &self.release_calls, + ] { + counter.store(0, Ordering::SeqCst); + } + self.current_ref_count.store(1, Ordering::SeqCst); + } + + fn snapshot(&self) -> GeneratedDeviceControlStats { + GeneratedDeviceControlStats { + record_calls: self.record_calls.load(Ordering::SeqCst), + null_format_calls: self.null_format_calls.load(Ordering::SeqCst), + explicit_format_calls: self.explicit_format_calls.load(Ordering::SeqCst), + add_ref_calls: self.add_ref_calls.load(Ordering::SeqCst), + release_calls: self.release_calls.load(Ordering::SeqCst), + current_ref_count: self.current_ref_count.load(Ordering::SeqCst), + } + } +} + +static MDSP_DEVICE_CONTROL_COUNTERS: DeviceControlCounters = DeviceControlCounters::new(); +static WMDM_DEVICE_CONTROL_COUNTERS: DeviceControlCounters = DeviceControlCounters::new(); + +#[repr(C)] +struct GeneratedDeviceControlFake { + vtable: *const IUnknown_Vtbl, + iid: GUID, + references: AtomicU32, + counters: &'static DeviceControlCounters, +} + +unsafe extern "system" fn device_control_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(); + let object = &*this.cast::(); + if *iid != IUnknown::IID && *iid != object.iid { + return E_NOINTERFACE; + } + *result = this; + device_control_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn device_control_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counters.add_ref_calls.fetch_add(1, Ordering::SeqCst); + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + object + .counters + .current_ref_count + .store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn device_control_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counters.release_calls.fetch_add(1, Ordering::SeqCst); + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + object + .counters + .current_ref_count + .store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn device_control_get_u32(_this: *mut c_void, _value: *mut u32) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn device_control_no_args(_this: *mut c_void) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn device_control_record( + this: *mut c_void, + format: *const WAVEFORMATEX, +) -> HRESULT { + let counters = unsafe { &*this.cast::() }.counters; + counters.record_calls.fetch_add(1, Ordering::SeqCst); + if format.is_null() { + counters.null_format_calls.fetch_add(1, Ordering::SeqCst); + return HRESULT(0); + } + // WAVEFORMATEX is packed; copy the header without forming aligned field references. + let header = unsafe { format.read_unaligned() }; + if header.wFormatTag != 1 + || header.nChannels != 2 + || header.nSamplesPerSec != 48_000 + || header.nAvgBytesPerSec != 192_000 + || header.nBlockAlign != 4 + || header.wBitsPerSample != 16 + || header.cbSize != 0 + { + return HRESULT(0x80070057u32 as i32); + } + counters + .explicit_format_calls + .fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn device_control_seek( + _this: *mut c_void, + _mode: u32, + _offset: i32, +) -> HRESULT { + E_NOTIMPL +} + +static MDSP_DEVICE_CONTROL_VTABLE: IMDSPDeviceControl_Vtbl = IMDSPDeviceControl_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: device_control_query_interface, + AddRef: device_control_add_ref, + Release: device_control_release, + }, + GetDCStatus: device_control_get_u32, + GetCapabilities: device_control_get_u32, + Play: device_control_no_args, + Record: device_control_record, + Pause: device_control_no_args, + Resume: device_control_no_args, + Stop: device_control_no_args, + Seek: device_control_seek, +}; + +static WMDM_DEVICE_CONTROL_VTABLE: IWMDMDeviceControl_Vtbl = IWMDMDeviceControl_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: device_control_query_interface, + AddRef: device_control_add_ref, + Release: device_control_release, + }, + GetStatus: device_control_get_u32, + GetCapabilities: device_control_get_u32, + Play: device_control_no_args, + Record: device_control_record, + Pause: device_control_no_args, + Resume: device_control_no_args, + Stop: device_control_no_args, + Seek: device_control_seek, +}; + +fn create_generated_device_control_fake( + vtable: &'static IUnknown_Vtbl, + iid: GUID, + counters: &'static DeviceControlCounters, +) -> napi::Result { + counters.reset(); + // Each object has its own full SDK vtable and advertises only its matching IID. + let object = Box::new(GeneratedDeviceControlFake { + vtable, + iid, + references: AtomicU32::new(1), + counters, + }); + let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; + crate::com::apartment_bound_com_object(unknown) +} + +#[napi(object)] +pub struct GeneratedDeviceControlStats { + pub record_calls: u32, + pub null_format_calls: u32, + pub explicit_format_calls: u32, + pub add_ref_calls: u32, + pub release_calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_mdsp_device_control_fake() -> napi::Result { + create_generated_device_control_fake( + &MDSP_DEVICE_CONTROL_VTABLE.base__, + IMDSPDeviceControl::IID, + &MDSP_DEVICE_CONTROL_COUNTERS, + ) +} + +#[napi] +pub fn create_generated_wmdm_device_control_fake() -> napi::Result { + create_generated_device_control_fake( + &WMDM_DEVICE_CONTROL_VTABLE.base__, + IWMDMDeviceControl::IID, + &WMDM_DEVICE_CONTROL_COUNTERS, + ) +} + +#[napi] +pub fn generated_mdsp_device_control_stats() -> GeneratedDeviceControlStats { + MDSP_DEVICE_CONTROL_COUNTERS.snapshot() +} + +#[napi] +pub fn generated_wmdm_device_control_stats() -> GeneratedDeviceControlStats { + WMDM_DEVICE_CONTROL_COUNTERS.snapshot() +} + #[repr(C)] struct GeneratedAudioClientVtbl { base__: IUnknown_Vtbl, diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index 965dc82e..4eca2706 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -1215,11 +1215,13 @@ where })?, ); } else if p.is_input() && !p.is_out() && p.typ.is_audio_format() { - audio_format_in_ptrs.push( - args.get_audio_format(p.input_index.expect("WAVEFORMATEX input index")) - .expect("validated WAVEFORMATEX input") - .as_ptr(), - ); + let input_index = p.input_index.expect("WAVEFORMATEX input index"); + let pointer = match args.get_audio_format(input_index) { + Some(format) => format.as_ptr(), + None if p.typ.is_nullable_audio_format_input() => std::ptr::null(), + None => panic!("validated WAVEFORMATEX input"), + }; + audio_format_in_ptrs.push(pointer); } } let native_struct_in_ptrs = native_struct_in_slots diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index e0ca594a..f2149b54 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -2239,7 +2239,7 @@ impl BufferElementPlan { | ParameterType::StatStg | ParameterType::FormatEtc | ParameterType::StgMedium - | ParameterType::AudioFormat => { + | ParameterType::AudioFormat { .. } => { return Err(invalid_argument( "Automation buffer elements require dedicated ownership and cleanup plans", )); @@ -2559,7 +2559,7 @@ impl Type { pub fn audio_format() -> Self { Self { - abi: ParameterType::audio_format(), + abi: ParameterType::audio_format(false), pointer_output: PointerOutputKind::None, allow_direct_aggregate_return: false, aggregate_capability: None, @@ -3500,9 +3500,9 @@ impl CallbackMethodPlan { | ParameterType::DispatchParams | ParameterType::ExcepInfo | ParameterType::StatStg => Some(crate::native_callback::CallbackAbiType::Pointer), - ParameterType::FormatEtc | ParameterType::StgMedium | ParameterType::AudioFormat => { - None - } + ParameterType::FormatEtc + | ParameterType::StgMedium + | ParameterType::AudioFormat { .. } => None, ParameterType::NativeStruct(layout) => { Some(crate::native_callback::CallbackAbiType::NativeStruct( format!("{layout:?}"), @@ -3960,7 +3960,7 @@ impl CallbackMethodPlan { | ParameterType::VariantByValue | ParameterType::FormatEtc | ParameterType::StgMedium - | ParameterType::AudioFormat => Err(SINK_E_FAIL), + | ParameterType::AudioFormat { .. } => Err(SINK_E_FAIL), } } @@ -5882,7 +5882,10 @@ impl MethodSignature { self } - pub fn add_nullable_in(mut self, typ: Type) -> Self { + pub fn add_nullable_in(mut self, mut typ: Type) -> Self { + if let ParameterType::AudioFormat { nullable_input } = &mut typ.abi { + *nullable_input = true; + } self.parameters.push(ComParameterSpec { direction: ComParameterDirection::In, typ, @@ -14295,6 +14298,111 @@ mod tests { ); } + #[test] + fn audio_format_nullable_inputs_preserve_null_slots_and_required_contracts() { + #[repr(C)] + struct AudioInputs { + vtable: *const *mut c_void, + calls: u32, + fail: bool, + } + + unsafe extern "system" fn observe( + this: *mut c_void, + first: *const c_void, + second: *const c_void, + ) -> HRESULT { + let state = unsafe { &mut *this.cast::() }; + state.calls += 1; + if state.fail { + return HRESULT(0x80004005u32 as i32); + } + for pointer in [first, second] { + if !pointer.is_null() { + let status = unsafe { inspect_audio_format(this, pointer) }; + if status.is_err() { + return status; + } + } + } + HRESULT(i32::from(first.is_null()) | (i32::from(second.is_null()) << 1)) + } + + let table = MetadataTable::new(); + let method = MethodSignature::new(&table) + .add_nullable_in(Type::audio_format()) + .add_nullable_in(Type::audio_format()) + .preserve_hresult() + .build(0) + .unwrap(); + let required = MethodSignature::new(&table) + .add_in(Type::audio_format()) + .add_nullable_in(Type::audio_format()) + .preserve_hresult() + .build(0) + .unwrap(); + let vtable = [observe as *mut c_void]; + let mut state = AudioInputs { + vtable: vtable.as_ptr(), + calls: 0, + fail: false, + }; + let format = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + let original = format.bytes().to_vec(); + for mask in 0..4 { + let arguments = (0..2) + .map(|index| { + if mask & (1 << index) != 0 { + Value::WinRt(WinRTValue::Null) + } else { + Value::AudioFormat(format.clone()) + } + }) + .collect::>(); + let output = method + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &arguments) + .unwrap(); + assert!( + matches!(output.as_slice(), [Value::WinRt(WinRTValue::HResult(hr))] if hr.0 == mask) + ); + } + assert_eq!(state.calls, 4); + let null = || Value::WinRt(WinRTValue::Null); + let error = required + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &[null(), null()]) + .unwrap_err(); + assert!( + error + .message() + .contains("required COM parameter 0 cannot be null") + ); + for invalid in [ + Value::WinRt(WinRTValue::I32(0)), + Value::WinRt(WinRTValue::RawPtr(std::ptr::null_mut())), + ] { + assert!( + method + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &[invalid, null()]) + .is_err() + ); + } + assert_eq!(state.calls, 4); + state.fail = true; + let error = method + .plan + .invoke_values( + (&mut state as *mut AudioInputs).cast(), + &[null(), Value::AudioFormat(format.clone())], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(state.calls, 5); + assert_eq!(format.bytes(), original); + } + #[test] fn audio_format_calls_validate_variable_storage_and_cotaskmem_ownership() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 6383e438..004e422d 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -79,7 +79,9 @@ pub(crate) enum ParameterType { StatStg, FormatEtc, StgMedium, - AudioFormat, + AudioFormat { + nullable_input: bool, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -242,8 +244,8 @@ impl ParameterType { Self::StgMedium } - pub(crate) fn audio_format() -> Self { - Self::AudioFormat + pub(crate) fn audio_format(nullable_input: bool) -> Self { + Self::AudioFormat { nullable_input } } pub(crate) fn as_winrt(&self) -> Option<&TypeHandle> { @@ -265,7 +267,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => None, + | Self::AudioFormat { .. } => None, } } @@ -287,7 +289,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => None, + | Self::AudioFormat { .. } => None, } } @@ -381,7 +383,16 @@ impl ParameterType { } pub(crate) fn is_audio_format(&self) -> bool { - matches!(self, Self::AudioFormat) + matches!(self, Self::AudioFormat { .. }) + } + + pub(crate) fn is_nullable_audio_format_input(&self) -> bool { + matches!( + self, + Self::AudioFormat { + nullable_input: true + } + ) } pub(crate) fn is_array(&self) -> bool { @@ -453,7 +464,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => AbiType::Ptr, + | Self::AudioFormat { .. } => AbiType::Ptr, Self::NativeStruct(_) | Self::NativeUnion(_) | Self::VariantByValue => { panic!("aggregate values do not have a scalar AbiType") } @@ -476,7 +487,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => libffi::middle::Type::pointer(), + | Self::AudioFormat { .. } => libffi::middle::Type::pointer(), Self::NativeStruct(layout) => layout.libffi_type(), Self::NativeUnion(layout) => layout.libffi_type(), Self::VariantByValue => variant_by_value_libffi_type(), @@ -514,7 +525,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => { + | Self::AudioFormat { .. } => { panic!("native POD storage is allocated by the dynamic executor") } } @@ -539,7 +550,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat => { + | Self::AudioFormat { .. } => { unreachable!("native POD output conversion uses NativeStructValue") } } @@ -579,7 +590,7 @@ impl ParameterType { | Self::StatStg | Self::FormatEtc | Self::StgMedium - | Self::AudioFormat, + | Self::AudioFormat { .. }, _, ) => { unreachable!("native POD output conversion uses NativeStructValue") @@ -600,7 +611,7 @@ impl ParameterType { Self::StatStg => OutputCleanup::None, Self::FormatEtc => OutputCleanup::None, Self::StgMedium => OutputCleanup::None, - Self::AudioFormat => OutputCleanup::None, + Self::AudioFormat { .. } => OutputCleanup::None, Self::Bstr { .. } => OutputCleanup::BstrFree, Self::CoTaskMemWideString => OutputCleanup::CoTaskMemFree, Self::WinRT(_) @@ -2267,7 +2278,13 @@ impl Method { } if parameter.typ.is_audio_format() { - if !matches!(&args[input_index], crate::com::Value::AudioFormat(_)) { + let is_format = matches!(&args[input_index], crate::com::Value::AudioFormat(_)); + let is_nullable_input = parameter.typ.is_nullable_audio_format_input() + && matches!( + &args[input_index], + crate::com::Value::WinRt(WinRTValue::Null) + ); + if !is_format && !is_nullable_input { return Err(invalid_argument( "Argument type mismatch: expected WAVEFORMATEX", )); diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 24c6cd19..65f11eb8 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -340,7 +340,9 @@ Current code registries are migrated without changing behavior: - `IDataObject::SetData` and `IOleCache::SetData` caller-retained STGMEDIUM ownership; - `IDataObject::GetCanonicalFormatEtc` output validity and ignored `tymed`; - `IAudioClient` shared/exclusive format negotiation and CoTaskMem format - outputs; and + outputs; +- `IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` nullable + audio-format inputs selecting the device default; and - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the @@ -405,13 +407,13 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,335 | -| `exact_registry_dependent` | 361 | +| `standard_derived` | 5,333 | +| `exact_registry_dependent` | 363 | | **Total** | **5,696** | -The registry contains **502 declared entries**, all 502 match the pinned -metadata, and 411 distinct entries are consumed by safe plans. Safe plans have -667 entry/interface dependencies and 414 family/interface dependencies. +The registry contains **504 declared entries**, all 504 match the pinned +metadata, and 413 distinct entries are consumed by safe plans. Safe plans have +669 entry/interface dependencies and 416 family/interface dependencies. Per-interface dependency-set totals also include 5,982 metadata-attribute dependencies and 26,129 COM-standard-rule dependencies. @@ -422,7 +424,7 @@ dependencies and 26,129 COM-standard-rule dependencies. | `bounded-two-call` | 16 | | `conditional-output` | 10 | | `flag-selected-buffer` | 3 | -| `null-input` | 2 | +| `null-input` | 4 | | `safearray` | 263 | | `enumerator-next` | 74 | | `borrowed-handle` | 54 | @@ -443,6 +445,7 @@ Family rollups deliberately count each interface once per family: | `com.ownership.v1` | 167 | 116 | 122 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | +| `com.nullable-input.v1` | 2 | 2 | 2 | | `com.semantic-hresult.v1` | 2 | 2 | 3 | | `automation.idispatch-invoke.v1` | 1 | 1 | 1 | | `graphics.private-data-hazard.v1` | 7 | 0 | 0 | diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 65f31026..5c8dc3cb 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -614,7 +614,7 @@ and `@microsoft/dynwinrt/com`. | 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 | -| Audio formats | Variable-length WAVEFORMATEX/WAVEFORMATEXTENSIBLE bytes with validated `cbSize`; PCM factory; exact shared/exclusive `IsFormatSupported` output selection; CoTaskMem-owned format outputs | Format-specific codec payload interpretation and JavaScript callback implementation | +| Audio formats | Variable-length WAVEFORMATEX/WAVEFORMATEXTENSIBLE bytes with validated `cbSize`; PCM factory; exact shared/exclusive `IsFormatSupported` output selection; CoTaskMem-owned format outputs; exact nullable device-control `Record` inputs | Format-specific codec payload interpretation and JavaScript callback implementation | | 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 | @@ -660,7 +660,7 @@ and `@microsoft/dynwinrt/com`. | 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`. | -| WAVEFORMATEX / WAVEFORMATEXTENSIBLE | Supported | `DynComAudioFormat` validates the packed 18-byte header plus exact `cbSize` extension, provides a PCM factory and field accessors, and preserves unknown codec extension bytes. Exact contracts pass `IsFormatSupported.ppClosestMatch` only in shared mode and free GetMixFormat/current-engine-format outputs with `CoTaskMemFree`. | +| WAVEFORMATEX / WAVEFORMATEXTENSIBLE | Supported | `DynComAudioFormat` validates the packed 18-byte header plus exact `cbSize` extension, provides a PCM factory and field accessors, and preserves unknown codec extension bytes. Exact contracts pass `IsFormatSupported.ppClosestMatch` only in shared mode and free GetMixFormat/current-engine-format outputs with `CoTaskMemFree`. The two device-control `Record` methods accept an explicit format or `null` for the device default. | | 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. | @@ -682,6 +682,13 @@ 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. | +`IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` have exact +nullable audio-input contracts. Their declarations accept +`DynComAudioFormat | null`, the COM signature retains input nullability, and +the executor passes a native NULL without constructing a dummy format. +Required inputs such as `IAudioClient::Initialize` and `IsFormatSupported` +remain non-nullable; unknown or drifted Record evidence fails generation. + `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. diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 377f4a21..6f7895d9 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -231,6 +231,12 @@ const [status, closest] = audio.isFormatSupported(0, pcm); const mixFormat = audio.getMixFormat(); ``` +For `IMDSPDeviceControl` and `IWMDMDeviceControl`, `record(null)` selects the +device's default recording format after the required capability and seek +setup. `record(pcm)` supplies an explicit format. This nullable contract does +not apply to `IAudioClient.initialize` or `isFormatSupported`, whose format +inputs remain required. + `IDXGIObjectUnsafe.getPrivateData` keeps its exact caller-storage API because metadata proves the ABI but not whether the payload is bytes or an AddRef'd interface. Pass ordinary bounded memory for bytes. For an interface payload, diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 5cac8c22..d91b109e 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -359,16 +359,16 @@ classifies all 5,696 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,335 | -| `exact_registry_dependent` | 361 | +| `standard_derived` | 5,333 | +| `exact_registry_dependent` | 363 | -The registry declares 502 selector-specific entries; all 502 match pinned -metadata, 411 distinct entries are safe-consumed, and safe plans contain 667 -entry/interface plus 414 family/interface dependencies. They also consume +The registry declares 504 selector-specific entries; all 504 match pinned +metadata, 413 distinct entries are safe-consumed, and safe plans contain 669 +entry/interface plus 416 family/interface dependencies. They also consume 5,982 metadata-attribute and 26,129 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, borrowed-handle 54, ownership 180, parameter-direction 45, bounded-two-call 16, -counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 2, +counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 4, semantic-HRESULT 3, and compound-dispatch 1. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. @@ -383,6 +383,9 @@ entries with full selectors, fingerprints, and citations. output contract, while `GetMixFormat` and `IAudioClient3::GetCurrentSharedModeEnginePeriod` add exact CoTaskMem-owned variable-format outputs. +The two device-control `Record` methods have separate exact nullable-input +contracts: `null` selects the device default format without allocating a +placeholder WAVEFORMATEX. Other audio-format inputs remain required. The storage-medium contracts also pin `IOleCache::SetData` (including inherited `IOleCache2` calls) to caller-retained ownership and describe the distinct diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 7e5005a0..622aa102 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -84,15 +84,15 @@ "safe_incomplete": 2233, "safeEvidence": { "safeComplete": 5696, - "standardDerived": 5335, - "exactRegistryDependent": 361, + "standardDerived": 5333, + "exactRegistryDependent": 363, "metadataFactOccurrences": 5982, "comStandardFactOccurrences": 26129, - "registeredExactEntries": 502, - "metadataMatchedExactEntries": 502, - "safeConsumedExactEntries": 411, - "exactEntryInterfaceDependencies": 667, - "exactFamilyInterfaceDependencies": 414, + "registeredExactEntries": 504, + "metadataMatchedExactEntries": 504, + "safeConsumedExactEntries": 413, + "exactEntryInterfaceDependencies": 669, + "exactFamilyInterfaceDependencies": 416, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, @@ -101,7 +101,7 @@ "counted-buffer": 16, "enumerator-next": 74, "flag-selected-buffer": 3, - "null-input": 2, + "null-input": 4, "ownership": 180, "parameter-direction": 45, "safearray": 263, @@ -368,6 +368,8 @@ "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfproperties.19188cb0aca911d2afc500105a2799b5.next.slot-4.v1": 1, "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfranges.f99d3f408e3211d2bf4600105a2799b5.next.slot-4.v1": 1, "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfuielements.887aa91eacba493184da3c5208cf543f.next.slot-4.v1": 1, + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1": 1, + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1": 1, "com.ownership.entry.windows-win32-devices-tapi.itcallinfo.350f85d1122711d383d400c04fb6809f.getcallinfobuffer.slot-17.param-2-ppcallinfobuffer.v1": 2, "com.ownership.entry.windows-win32-devices-tapi.itlegacycallmediacontrol.d624582fcc234436b8a547c625c8045d.getid.slot-9.param-2-ppdeviceid.v1": 2, "com.ownership.entry.windows-win32-graphics-direct3d-dxc.idxcversioninfo2.fb6904c442f04b629c46983af7da7c83.getcommitinfo.slot-5.param-1-pcommithash.v1": 1, @@ -527,6 +529,7 @@ "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, + "com.nullable-input.v1": 2, "com.ownership.v1": 122, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, @@ -6397,6 +6400,42 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1": { + "familyId": "com.nullable-input.v1", + "contractKind": "null-input", + "selector": { + "namespace": "Windows.Win32.Media.DeviceManager", + "interface": "IMDSPDeviceControl", + "iid": "1dcb3a14-33ed-11d3-8470-00c04f79dbc0", + "method": "Record", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "346C3A5C69100EF034C6B1773533C7B9AB74C66F05581FF8D1D02370C9506F52", + "citation": "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-imdspdevicecontrol-record", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1": { + "familyId": "com.nullable-input.v1", + "contractKind": "null-input", + "selector": { + "namespace": "Windows.Win32.Media.DeviceManager", + "interface": "IWMDMDeviceControl", + "iid": "1dcb3a04-33ed-11d3-8470-00c04f79dbc0", + "method": "Record", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "68EB1BDA9994CE96C21642D9D336EBBF7BC38DD14C04E799A9091025D0D55871", + "citation": "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-iwmdmdevicecontrol-record", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-devices-portabledevices.iportabledevice.625e2df863924cf09ad13cfa5f17775c.getpnpdeviceid.slot-11.param-0-ppszpnpdeviceid.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index ed8f01aa..5cf2de56 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -1491,7 +1491,7 @@ Windows.Win32.Media.DeviceManager,IComponentAuthenticate,a9889c00-6d2b-11d3-8496 Windows.Win32.Media.DeviceManager,IMDSPDevice,1dcb3a12-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice2,420d16ad-c97d-4e00-82aa-00e9f4335ddd,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice3,1a839845-fc55-487c-976f-ee38ac0e8c4e,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, +Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,true,exact_registry_dependent, Windows.Win32.Media.DeviceManager,IMDSPDirectTransfer,c2fe57a8-9304-478c-9ee4-47e397b912d7,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumDevice,1dcb3a11-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumStorage,1dcb3a15-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, @@ -1519,7 +1519,7 @@ Windows.Win32.Media.DeviceManager,ISCPSession,88a3e6ed-eee4-4619-bbb3-fd4fb62715 Windows.Win32.Media.DeviceManager,IWMDMDevice,1dcb3a02-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice2,e34f3d37-9d67-4fc1-9252-62d28b2f8b55,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice3,6c03e4fe-05db-4dda-9e3c-06233a6d5d65,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, +Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,true,exact_registry_dependent, Windows.Win32.Media.DeviceManager,IWMDMDeviceSession,82af0a65-9d96-412c-83e5-3c43e4b06cc7,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumDevice,1dcb3a01-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumStorage,1dcb3a05-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 3249703a..c55a2a0d 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4561,8 +4561,8 @@ mod tests { assert_eq!(report.summary.eligible_interfaces, 7_929); assert_eq!(report.summary.safe_complete, 5_696); assert_eq!(report.summary.safe_evidence.safe_complete, 5_696); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_335); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 361); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_333); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 363); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4576,28 +4576,28 @@ mod tests { report.summary.safe_evidence.com_standard_fact_occurrences, 26_129 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 502); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 504); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 502 + 504 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 411 + 413 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 667 + 669 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 414 + 416 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4609,7 +4609,7 @@ mod tests { ("counted-buffer".into(), 16), ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), - ("null-input".into(), 2), + ("null-input".into(), 4), ("ownership".into(), 180), ("parameter-direction".into(), 45), ("safearray".into(), 263), @@ -4624,6 +4624,10 @@ mod tests { report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], 3 ); + assert_eq!( + report.summary.safe_evidence.by_family_id["com.nullable-input.v1"], + 2 + ); assert_eq!( report.summary.safe_evidence.by_family_id["windows.borrowed-hwnd-output.v1"], 45 @@ -4636,7 +4640,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(), 411); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 413); assert!( report .summary @@ -4681,7 +4685,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 411 + 413 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index ac1b89bd..bf97a571 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -842,6 +842,9 @@ fn wrap_param_arg_js(param: &ProjectedComParam, variable: &str) -> String { matches!(encoding, StringEncoding::Wide) ), ComType::Bstr => format!("{variable} === null ? DynCom.nullBstr() : {wrapped}"), + ComType::AudioFormat => { + format!("{variable} === null ? DynCom.nullAudioFormat() : {wrapped}") + } _ => unreachable!("nullable projection was validated"), }; } 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 52e82bea..fd0c0031 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,50 @@ fn renderer_serializes_validated_com_sink_plan() { ); } +#[test] +fn nullable_audio_format_inputs_serialize_the_validated_contract() { + let mut method = ProjectedComMethod { + name: "UseFormat".into(), + camel_name: "useFormat".into(), + vtable_index: 6, + params: vec![ProjectedComParam { + name: "format".into(), + typ: ComType::AudioFormat, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: true, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addNullableIn(DynCom.audioFormatType())" + ); + assert_eq!(dts_params(&method), ["format: DynComAudioFormat | null"]); + assert_eq!( + wrap_param_arg_js(&method.params[0], "format"), + "format === null ? DynCom.nullAudioFormat() : DynCom.audioFormat(format)" + ); + method.params[0].nullable = false; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addIn(DynCom.audioFormatType())" + ); + assert_eq!(dts_params(&method), ["format: DynComAudioFormat"]); + assert_eq!( + wrap_param_arg_js(&method.params[0], "format"), + "DynCom.audioFormat(format)" + ); +} + #[test] fn storage_medium_result_rules_and_borrowing_are_serialized_from_ir() { let format_param = |name: &str, direction| ProjectedComParam { diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 8785ba02..0a9408bf 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -294,7 +294,7 @@ 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) + crate::com_metadata::validate_required_exact_contract_presence(raw) .map_err(ModelError::InvalidContract)?; if let Some(contract) = &raw.exact_contract { crate::com_metadata::validate_exact_method_contract( @@ -453,7 +453,10 @@ fn map_method( output_param: ParamIndex::new(1), }) } - Some(RawExactMethodContractKind::AudioFormatOwnedOutput) => method, + Some( + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::NullableAudioFormatInput, + ) => method, Some(RawExactMethodContractKind::AudioFormatSupport) => { let contract = raw.exact_contract.as_ref().unwrap(); method.with_special_contract(ComMethodSpecialContract::AudioFormatSupport { @@ -730,7 +733,13 @@ fn map_param( param_index, dynamic_iid_output, )?; - let nullable = if !exact_null_input + let exact_nullable_audio_input = raw_method.exact_contract.as_ref().is_some_and(|contract| { + contract.kind == RawExactMethodContractKind::NullableAudioFormatInput + && contract.buffer_param_index == param_index + }); + let nullable = if exact_nullable_audio_input { + Nullability::Nullable + } else if !exact_null_input && (raw.optional || known_nullable_param_override( interface_namespace, diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 390be9a4..1dd1c9d2 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -1190,11 +1190,12 @@ fn project_method( | ComType::Bstr | ComType::ManagedInterface { .. } | ComType::SafeArray { .. } - ) || (direction == ComParamDirection::InputBuffer - && matches!( - typ, - ComType::TypedBuffer { .. } | ComType::StringArray { .. } - )) + ) || (direction == ComParamDirection::In && matches!(typ, ComType::AudioFormat)) + || (direction == ComParamDirection::InputBuffer + && matches!( + typ, + ComType::TypedBuffer { .. } | ComType::StringArray { .. } + )) } let mut return_convention = match method.return_kind() { diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index cf7641ba..825b6904 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -386,6 +386,7 @@ pub enum RawExactMethodContractKind { CanonicalFormatEtc, AudioFormatOwnedOutput, AudioFormatSupport, + NullableAudioFormatInput, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -426,6 +427,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::AudioFormatSupport => { crate::contract_registry::ExactFamilyId::AudioConditionalOutput } + RawExactMethodContractKind::NullableAudioFormatInput => { + crate::contract_registry::ExactFamilyId::NullableInput + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ExactFamilyId::SemanticHresult } @@ -464,6 +468,9 @@ impl RawExactMethodContract { RawExactMethodContractKind::AudioFormatSupport => { crate::contract_registry::ContractKind::ConditionalOutput } + RawExactMethodContractKind::NullableAudioFormatInput => { + crate::contract_registry::ContractKind::NullInput + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ContractKind::SemanticHresult } @@ -2202,6 +2209,7 @@ fn apply_exact_method_contract( RawExactMethodContractKind::Malloc => {} RawExactMethodContractKind::AudioFormatOwnedOutput => {} RawExactMethodContractKind::AudioFormatSupport => {} + RawExactMethodContractKind::NullableAudioFormatInput => {} RawExactMethodContractKind::BorrowedStgMediumInput | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc => {} @@ -2366,6 +2374,22 @@ fn registered_exact_method_contract( "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.Media.DeviceManager", + "IMDSPDeviceControl" | "IWMDMDeviceControl", + "Record", + ) => ( + RawExactMethodContractKind::NullableAudioFormatInput, + 0, + 0, + None, + "Record accepts a null WAVEFORMATEX pointer to select the device default format; explicit formats are borrowed for the call", + if interface == "IMDSPDeviceControl" { + "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-imdspdevicecontrol-record" + } else { + "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-iwmdmdevicecontrol-record" + }, + ), ("Windows.Win32.Media.Audio", "IAudioClient", "IsFormatSupported") => ( RawExactMethodContractKind::AudioFormatSupport, 2, @@ -2475,6 +2499,7 @@ fn registered_exact_method_contract( "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", "IStream" | "IDataObject" => "Windows.Win32.System.Com", "IAudioClient" | "IAudioClient3" => "Windows.Win32.Media.Audio", + "IMDSPDeviceControl" | "IWMDMDeviceControl" => "Windows.Win32.Media.DeviceManager", "IOleCache" => "Windows.Win32.System.Ole", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", "IContextMenu" => "Windows.Win32.UI.Shell", @@ -2497,6 +2522,8 @@ fn registered_exact_method_contract( "IDataObject" => "IDataObject", "IAudioClient" => "IAudioClient", "IAudioClient3" => "IAudioClient3", + "IMDSPDeviceControl" => "IMDSPDeviceControl", + "IWMDMDeviceControl" => "IWMDMDeviceControl", "IOleCache" => "IOleCache", _ => unreachable!("matched exact method interface"), }, @@ -2535,6 +2562,11 @@ fn registered_exact_method_contract( RawExactMethodContractKind::AudioFormatSupport => { unreachable!("audio format support belongs to IAudioClient") } + RawExactMethodContractKind::NullableAudioFormatInput => match interface { + "IMDSPDeviceControl" => "1dcb3a14-33ed-11d3-8470-00c04f79dbc0", + "IWMDMDeviceControl" => "1dcb3a04-33ed-11d3-8470-00c04f79dbc0", + _ => unreachable!("matched exact nullable audio input"), + }, RawExactMethodContractKind::BorrowedStgMediumInput => match interface { "IDataObject" => "0000010e-0000-0000-c000-000000000046", "IOleCache" => "0000011e-0000-0000-c000-000000000046", @@ -2565,6 +2597,7 @@ fn registered_exact_method_contract( _ => unreachable!("matched exact audio format output"), }, RawExactMethodContractKind::AudioFormatSupport => "IsFormatSupported", + RawExactMethodContractKind::NullableAudioFormatInput => "Record", RawExactMethodContractKind::BorrowedStgMediumInput => "SetData", RawExactMethodContractKind::PreservedStgMediumInOut => "GetDataHere", RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", @@ -2589,6 +2622,7 @@ fn registered_exact_method_contract( ("IAudioClient", "IsFormatSupported") => 7, ("IAudioClient", "GetMixFormat") => 8, ("IAudioClient3", "GetCurrentSharedModeEnginePeriod") => 19, + ("IMDSPDeviceControl" | "IWMDMDeviceControl", "Record") => 6, ("IDataObject" | "IOleCache", "SetData") => 7, ("IDataObject", "GetDataHere") => 4, ("IDataObject", "GetCanonicalFormatEtc") => 6, @@ -2608,6 +2642,12 @@ fn registered_exact_method_contract( == RawExactMethodContractKind::BorrowedStgMediumInput) .then_some(2), source_fingerprint: match (interface, method) { + ("IMDSPDeviceControl", "Record") => { + Some("346C3A5C69100EF034C6B1773533C7B9AB74C66F05581FF8D1D02370C9506F52") + } + ("IWMDMDeviceControl", "Record") => { + Some("68EB1BDA9994CE96C21642D9D336EBBF7BC38DD14C04E799A9091025D0D55871") + } ("IDataObject", "GetDataHere") => { Some("65165D814B216835E273E9342B4CBEC2A4F6F1A68477F3F07036C2479BDADBFF") } @@ -2748,7 +2788,7 @@ 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> { +pub(crate) fn validate_required_exact_contract_presence(raw: &RawComMethod) -> Result<(), String> { let required = registered_exact_method_contract( &raw.declaring_namespace, &raw.declaring_interface, @@ -2760,11 +2800,12 @@ pub(crate) fn validate_storage_medium_contract_presence(raw: &RawComMethod) -> R RawExactMethodContractKind::BorrowedStgMediumInput | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc + | RawExactMethodContractKind::NullableAudioFormatInput ) }); if required && raw.exact_contract.is_none() { return Err(format!( - "{}.{} requires its exact storage-medium contract", + "{}.{} requires exact contract evidence for its input/output semantics", raw.declaring_interface, raw.metadata_name )); } @@ -2989,6 +3030,10 @@ pub(crate) fn validate_exact_method_contract( }) && raw_hresult(&raw.return_type) } + RawExactMethodContractKind::NullableAudioFormatInput => { + raw_method_shape(raw) + == "Record@6(pFormat:in:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } RawExactMethodContractKind::AudioFormatOwnedOutput => { if contract.method_name == "GetMixFormat" { raw_method_shape(raw) @@ -3039,6 +3084,14 @@ pub(crate) fn validate_exact_method_contract( && contract.discriminator_param_index.is_none() && contract.reserved_null_param_index.is_none() } + RawExactMethodContractKind::NullableAudioFormatInput => { + contract.buffer_param_index == 0 + && contract.capacity_param_index == 0 + && contract.actual_length_param_index.is_none() + && contract.discriminator_param_index.is_none() + && contract.reserved_null_param_index.is_none() + && contract.ownership_transfer_param_index.is_none() + } RawExactMethodContractKind::AudioFormatOwnedOutput => { contract.buffer_param_index == 0 && contract.discriminator_param_index.is_none() @@ -5201,6 +5254,54 @@ mod tests { .unwrap(); } + #[test] + fn audio_record_nullability_contracts_are_exact() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let mut missing = Vec::new(); + for name in ["IMDSPDeviceControl", "IWMDMDeviceControl"] { + let namespace = "Windows.Win32.Media.DeviceManager"; + let interface = parse_com_interface(&winmd, namespace, name).unwrap(); + let raw = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Record") + .unwrap(); + if let Some(contract) = &raw.exact_contract { + assert_eq!( + contract.kind, + RawExactMethodContractKind::NullableAudioFormatInput + ); + assert_eq!(contract.buffer_param_index, 0); + validate_exact_method_contract( + namespace, + name, + &interface.interface.iid, + raw, + contract, + ) + .unwrap(); + } else { + missing.push(format!( + "{name} {}: {} ({})", + interface.interface.iid, + raw_method_shape(raw), + raw_method_fingerprint(raw) + )); + } + } + assert!( + missing.is_empty(), + "missing nullable Record evidence: {missing:#?}" + ); + } + #[test] fn audio_format_exact_contracts_are_fingerprint_pinned() { let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index 212125e1..72e55d97 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -92,6 +92,7 @@ pub enum ExactFamilyId { SequentialStreamBuffer, DispatchInvoke, ReservedNullInput, + NullableInput, ParameterDirection, ShellCommandString, AudioConditionalOutput, @@ -112,6 +113,7 @@ impl ExactFamilyId { Self::SequentialStreamBuffer => "com.sequential-stream-buffer.v1", Self::DispatchInvoke => "automation.idispatch-invoke.v1", Self::ReservedNullInput => "com.reserved-null-input.v1", + Self::NullableInput => "com.nullable-input.v1", Self::ParameterDirection => "com.parameter-direction.v1", Self::ShellCommandString => "shell.flag-selected-string.v1", Self::AudioConditionalOutput => "audio.conditional-output.v1", @@ -132,6 +134,7 @@ impl ExactFamilyId { Self::SequentialStreamBuffer, Self::DispatchInvoke, Self::ReservedNullInput, + Self::NullableInput, Self::ParameterDirection, Self::ShellCommandString, Self::AudioConditionalOutput, @@ -478,6 +481,8 @@ pub(crate) fn statically_declared_exact_entry_ids() -> Result, } const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1", + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1", "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1", "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1", "buffers.bounded-two-call.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getblob.slot-15.v1", @@ -1149,7 +1154,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(), 502); + assert_eq!(ids.len(), 504); 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 8dfb92d1..788b40af 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2201,6 +2201,69 @@ fn data_object_projects_hglobal_format_and_medium_values() { assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); } +#[test] +fn device_control_record_projects_exact_nullable_audio_formats() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + for name in ["IMDSPDeviceControl", "IWMDMDeviceControl"] { + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Media.DeviceManager", + name, + ) + .unwrap(); + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + assert!( + output + .dts + .contains("record(pFormat: DynComAudioFormat | null): void;") + ); + assert!( + output + .js + .contains(".addNullableIn(DynCom.audioFormatType())") + ); + assert!( + output.js.contains( + "pFormat === null ? DynCom.nullAudioFormat() : DynCom.audioFormat(pFormat)" + ) + ); + let index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "Record") + .unwrap(); + let raw = &interface.raw_methods.as_ref().unwrap()[index]; + assert!(!raw.params[0].optional); + assert_eq!( + raw.exact_contract.as_ref().unwrap().kind, + com_metadata::RawExactMethodContractKind::NullableAudioFormatInput + ); + for mutation in 0..7 { + let mut drift = interface.clone(); + let raw = &mut drift.raw_methods.as_mut().unwrap()[index]; + match mutation { + 0 => raw.exact_contract = None, + 1 => raw.vtable_index += 1, + 2 => raw.params[0].typ.pointer_depth = 2, + 3 => raw.params[0].direction = com_metadata::RawParamDirection::Out, + 4 => raw.params[0].optional = true, + 5 => raw.params[0].const_attribute = true, + 6 => raw.exact_contract.as_mut().unwrap().buffer_param_index = 1, + _ => unreachable!(), + } + assert!( + com::generate_com_interface_files(&drift, &win32_winmd()).is_err(), + "{name}.Record admitted mutation {mutation}" + ); + } + } +} + #[test] fn audio_clients_project_variable_wave_formats_and_exact_ownership() { if !win32_available() {