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/6] 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/6] 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/6] 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 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 4/6] 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 5/6] 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 6/6] 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() {