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/2] 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 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 2/2] 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,