1use crate::guid::Guid;
22use std::ffi::c_void;
23use std::sync::atomic::{AtomicU32, Ordering};
24
25pub type Hresult = i32;
27
28pub const S_OK: Hresult = 0;
29pub const E_NOINTERFACE: Hresult = -2147467262; pub const E_POINTER: Hresult = -2147467261; #[inline]
34pub fn succeeded(hr: Hresult) -> bool {
35 hr >= 0
36}
37
38pub const IID_IUNKNOWN: Guid = Guid::parse("00000000-0000-0000-c000-000000000046");
40pub const IID_IAGILE_OBJECT: Guid = Guid::parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90");
43pub const IID_IINSPECTABLE: Guid = Guid::parse("af86e2e0-b12d-4c6a-9c5a-d7aa65101e90");
45
46#[repr(C)]
48pub struct IUnknownVtbl {
49 pub query_interface:
50 unsafe extern "system" fn(*mut c_void, *const Guid, *mut *mut c_void) -> Hresult,
51 pub add_ref: unsafe extern "system" fn(*mut c_void) -> u32,
52 pub release: unsafe extern "system" fn(*mut c_void) -> u32,
53}
54
55#[repr(C)]
57pub struct IInspectableVtbl {
58 pub base: IUnknownVtbl,
59 pub get_iids: unsafe extern "system" fn(*mut c_void, *mut u32, *mut *mut Guid) -> Hresult,
60 pub get_runtime_class_name: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> Hresult,
61 pub get_trust_level: unsafe extern "system" fn(*mut c_void, *mut i32) -> Hresult,
62}
63
64pub const FIRST_METHOD: usize = 6;
69
70pub struct ComPtr(*mut c_void);
75
76impl ComPtr {
77 pub unsafe fn adopt(raw: *mut c_void) -> Option<Self> {
83 (!raw.is_null()).then_some(Self(raw))
84 }
85
86 #[inline]
87 pub fn as_raw(&self) -> *mut c_void {
88 self.0
89 }
90
91 #[inline]
93 pub fn key(&self) -> usize {
94 self.0 as usize
95 }
96
97 #[inline]
98 fn vtable(&self) -> *const *const c_void {
99 unsafe { *(self.0 as *const *const *const c_void) }
101 }
102
103 #[inline]
108 pub unsafe fn method<T: Copy>(&self, index: usize) -> T {
109 unsafe { std::mem::transmute_copy(&*self.vtable().add(index)) }
110 }
111
112 pub fn cast(&self, iid: Guid) -> Option<ComPtr> {
115 let mut out: *mut c_void = std::ptr::null_mut();
116 let hr = unsafe {
118 let f: unsafe extern "system" fn(
119 *mut c_void,
120 *const Guid,
121 *mut *mut c_void,
122 ) -> Hresult = self.method(0);
123 f(self.0, &iid, &mut out)
124 };
125 (succeeded(hr) && !out.is_null()).then_some(ComPtr(out))
126 }
127}
128
129impl Clone for ComPtr {
130 fn clone(&self) -> Self {
131 unsafe {
133 let f: unsafe extern "system" fn(*mut c_void) -> u32 = self.method(1);
134 f(self.0);
135 }
136 Self(self.0)
137 }
138}
139
140impl Drop for ComPtr {
141 fn drop(&mut self) {
142 unsafe {
144 let f: unsafe extern "system" fn(*mut c_void) -> u32 = self.method(2);
145 f(self.0);
146 }
147 }
148}
149
150impl std::fmt::Debug for ComPtr {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 write!(f, "ComPtr({:p})", self.0)
153 }
154}
155
156unsafe impl Send for ComPtr {}
159unsafe impl Sync for ComPtr {}
160
161#[repr(C)]
168pub struct DelegateVtbl {
169 pub base: IUnknownVtbl,
170 pub invoke: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> Hresult,
171}
172
173#[repr(C)]
179pub struct Delegate {
180 vtable: *const DelegateVtbl,
181 references: AtomicU32,
182 iid: Guid,
184 handler: Box<dyn Fn(*mut c_void, *mut c_void) + Send + Sync>,
187}
188
189impl Delegate {
190 #[allow(clippy::new_ret_no_self)]
195 pub fn new(
199 iid: Guid,
200 handler: impl Fn(*mut c_void, *mut c_void) + Send + Sync + 'static,
201 ) -> ComPtr {
202 static VTABLE: DelegateVtbl = DelegateVtbl {
203 base: IUnknownVtbl {
204 query_interface: delegate_query_interface,
205 add_ref: delegate_add_ref,
206 release: delegate_release,
207 },
208 invoke: delegate_invoke,
209 };
210
211 let boxed = Box::new(Delegate {
212 vtable: &VTABLE,
213 references: AtomicU32::new(1),
214 iid,
215 handler: Box::new(handler),
216 });
217 ComPtr(Box::into_raw(boxed) as *mut c_void)
218 }
219}
220
221unsafe extern "system" fn delegate_query_interface(
222 this: *mut c_void,
223 iid: *const Guid,
224 out: *mut *mut c_void,
225) -> Hresult {
226 if out.is_null() {
227 return E_POINTER;
228 }
229 let delegate = unsafe { &*(this as *const Delegate) };
231 let requested = if iid.is_null() {
232 Guid::default()
233 } else {
234 unsafe { *iid }
235 };
236
237 if requested == IID_IUNKNOWN || requested == IID_IAGILE_OBJECT || requested == delegate.iid {
240 unsafe {
241 delegate_add_ref(this);
242 *out = this;
243 }
244 return S_OK;
245 }
246 unsafe { *out = std::ptr::null_mut() };
247 E_NOINTERFACE
248}
249
250unsafe extern "system" fn delegate_add_ref(this: *mut c_void) -> u32 {
251 let delegate = unsafe { &*(this as *const Delegate) };
252 delegate.references.fetch_add(1, Ordering::Relaxed) + 1
253}
254
255unsafe extern "system" fn delegate_release(this: *mut c_void) -> u32 {
256 let delegate = unsafe { &*(this as *const Delegate) };
257 let remaining = delegate.references.fetch_sub(1, Ordering::Release) - 1;
258 if remaining == 0 {
259 std::sync::atomic::fence(Ordering::Acquire);
262 drop(unsafe { Box::from_raw(this as *mut Delegate) });
263 }
264 remaining
265}
266
267unsafe extern "system" fn delegate_invoke(
268 this: *mut c_void,
269 sender: *mut c_void,
270 args: *mut c_void,
271) -> Hresult {
272 let delegate = unsafe { &*(this as *const Delegate) };
273 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
275 (delegate.handler)(sender, args);
276 }));
277 if result.is_err() {
278 return E_POINTER;
279 }
280 S_OK
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 use std::sync::atomic::AtomicUsize;
287 use std::sync::Arc;
288
289 const TEST_IID: Guid = Guid::parse("1234abcd-0000-0000-0000-000000000001");
290 const OTHER_IID: Guid = Guid::parse("1234abcd-0000-0000-0000-000000000002");
291
292 fn query(p: &ComPtr, iid: Guid) -> (Hresult, *mut c_void) {
294 let mut out = std::ptr::null_mut();
295 let hr = unsafe {
296 let f: unsafe extern "system" fn(
297 *mut c_void,
298 *const Guid,
299 *mut *mut c_void,
300 ) -> Hresult = p.method(0);
301 f(p.as_raw(), &iid, &mut out)
302 };
303 (hr, out)
304 }
305
306 fn release(raw: *mut c_void) -> u32 {
307 unsafe { delegate_release(raw) }
308 }
309
310 #[test]
311 fn the_vtable_layout_is_what_com_expects() {
312 assert_eq!(
315 std::mem::size_of::<IUnknownVtbl>(),
316 3 * std::mem::size_of::<usize>()
317 );
318 assert_eq!(
319 std::mem::size_of::<IInspectableVtbl>(),
320 6 * std::mem::size_of::<usize>()
321 );
322 assert_eq!(
323 std::mem::size_of::<DelegateVtbl>(),
324 4 * std::mem::size_of::<usize>()
325 );
326 assert_eq!(FIRST_METHOD, 6);
327 }
328
329 #[test]
330 fn a_delegate_is_a_valid_com_pointer() {
331 let delegate = Delegate::new(TEST_IID, |_, _| {});
333 let first_word = unsafe { *(delegate.as_raw() as *const usize) };
334 assert_ne!(first_word, 0);
335 assert_eq!(first_word, &raw const *delegate_vtable() as usize);
336 }
337
338 fn delegate_vtable() -> &'static DelegateVtbl {
339 let d = Delegate::new(TEST_IID, |_, _| {});
341 unsafe { &*(*(d.as_raw() as *const *const DelegateVtbl)) }
342 }
343
344 #[test]
345 fn invoke_reaches_the_closure() {
346 let seen = Arc::new(AtomicUsize::new(0));
347 let counter = seen.clone();
348 let delegate = Delegate::new(TEST_IID, move |sender, _args| {
349 counter.fetch_add(sender as usize, Ordering::Relaxed);
350 });
351
352 unsafe {
353 let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> Hresult =
354 delegate.method(3);
355 assert_eq!(
356 f(delegate.as_raw(), 7 as *mut c_void, std::ptr::null_mut()),
357 S_OK
358 );
359 assert_eq!(
360 f(delegate.as_raw(), 5 as *mut c_void, std::ptr::null_mut()),
361 S_OK
362 );
363 }
364 assert_eq!(seen.load(Ordering::Relaxed), 12);
365 }
366
367 #[test]
368 fn a_panic_does_not_unwind_into_windows() {
369 let delegate = Delegate::new(TEST_IID, |_, _| panic!("handler exploded"));
371 let hr = unsafe {
372 let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> Hresult =
373 delegate.method(3);
374 f(
375 delegate.as_raw(),
376 std::ptr::null_mut(),
377 std::ptr::null_mut(),
378 )
379 };
380 assert!(!succeeded(hr), "a panicking handler must report failure");
381 }
382
383 #[test]
384 fn query_interface_answers_the_three_it_must() {
385 let delegate = Delegate::new(TEST_IID, |_, _| {});
386
387 for iid in [IID_IUNKNOWN, IID_IAGILE_OBJECT, TEST_IID] {
388 let (hr, out) = query(&delegate, iid);
389 assert_eq!(hr, S_OK, "should answer to {iid}");
390 assert_eq!(out, delegate.as_raw());
391 release(out);
393 }
394
395 let (hr, out) = query(&delegate, OTHER_IID);
396 assert_eq!(hr, E_NOINTERFACE);
397 assert!(
398 out.is_null(),
399 "a failed QueryInterface must null the out pointer"
400 );
401 }
402
403 #[test]
404 fn a_null_out_pointer_is_rejected_rather_than_written_through() {
405 let delegate = Delegate::new(TEST_IID, |_, _| {});
406 let hr = unsafe {
407 let f: unsafe extern "system" fn(
408 *mut c_void,
409 *const Guid,
410 *mut *mut c_void,
411 ) -> Hresult = delegate.method(0);
412 f(delegate.as_raw(), &TEST_IID, std::ptr::null_mut())
413 };
414 assert_eq!(hr, E_POINTER);
415 }
416
417 #[test]
418 fn reference_counting_frees_exactly_once() {
419 let dropped = Arc::new(AtomicUsize::new(0));
420 let witness = dropped.clone();
421 let delegate = Delegate::new(TEST_IID, move |_, _| {
423 let _ = &witness;
424 });
425 let raw = delegate.as_raw();
426
427 let add_ref = |raw| unsafe { delegate_add_ref(raw) };
428 assert_eq!(add_ref(raw), 2);
429 assert_eq!(add_ref(raw), 3);
430 assert_eq!(release(raw), 2);
431 assert_eq!(release(raw), 1);
432
433 assert_eq!(Arc::strong_count(&dropped), 2, "still held by the delegate");
434 drop(delegate); assert_eq!(
436 Arc::strong_count(&dropped),
437 1,
438 "the closure was freed exactly once"
439 );
440 }
441
442 #[test]
443 fn cloning_a_com_pointer_holds_a_reference() {
444 let dropped = Arc::new(AtomicUsize::new(0));
445 let witness = dropped.clone();
446 let delegate = Delegate::new(TEST_IID, move |_, _| {
447 let _ = &witness;
448 });
449
450 let second = delegate.clone();
451 drop(delegate);
452 assert_eq!(Arc::strong_count(&dropped), 2, "the clone still holds it");
453 drop(second);
454 assert_eq!(Arc::strong_count(&dropped), 1);
455 }
456
457 #[test]
458 fn delegates_with_different_iids_do_not_answer_for_each_other() {
459 let a = Delegate::new(TEST_IID, |_, _| {});
463 let b = Delegate::new(OTHER_IID, |_, _| {});
464
465 let (hr, matched) = query(&a, TEST_IID);
469 assert_eq!(hr, S_OK);
470 release(matched);
471 assert_eq!(query(&a, OTHER_IID).0, E_NOINTERFACE);
472
473 let (hr, matched) = query(&b, OTHER_IID);
474 assert_eq!(hr, S_OK);
475 release(matched);
476 assert_eq!(query(&b, TEST_IID).0, E_NOINTERFACE);
477 }
478}