Skip to main content

webbluetooth_windows/
com.rs

1//! COM, by hand.
2//!
3//! A COM object is a pointer to a pointer to a table of function pointers. The
4//! first three entries are always `QueryInterface`, `AddRef` and `Release`; a
5//! WinRT object adds three more for `IInspectable`, so an interface's own
6//! methods begin at slot six. Calls use the `system` ABI — `stdcall` on 32-bit
7//! Windows, the ordinary C convention elsewhere.
8//!
9//! Two directions matter here:
10//!
11//! * **Calling out** — [`ComPtr`] wraps a pointer, holds a reference for as
12//!   long as it lives, and invokes methods by slot.
13//! * **Being called** — Windows delivers events and async completions to an
14//!   object *you* supply, so [`Delegate`] is one: a `#[repr(C)]` struct whose
15//!   first field is a vtable, with a refcount and a Rust closure behind it.
16//!
17//! The second is the interesting half, and it is entirely ordinary Rust — which
18//! is why its reference counting and `QueryInterface` behaviour are tested
19//! directly, on any host, by calling through the vtable exactly as COM would.
20
21use crate::guid::Guid;
22use std::ffi::c_void;
23use std::sync::atomic::{AtomicU32, Ordering};
24
25/// `HRESULT`. Negative means failure.
26pub type Hresult = i32;
27
28pub const S_OK: Hresult = 0;
29pub const E_NOINTERFACE: Hresult = -2147467262; // 0x8000_4002
30pub const E_POINTER: Hresult = -2147467261; // 0x8000_4003
31
32/// Did the call succeed?
33#[inline]
34pub fn succeeded(hr: Hresult) -> bool {
35    hr >= 0
36}
37
38/// `IUnknown`.
39pub const IID_IUNKNOWN: Guid = Guid::parse("00000000-0000-0000-c000-000000000046");
40/// `IAgileObject` — marks an object safe to call from any apartment. WinRT
41/// asks for it, and a delegate that refuses is one the runtime may marshal.
42pub const IID_IAGILE_OBJECT: Guid = Guid::parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90");
43/// `IInspectable`.
44pub const IID_IINSPECTABLE: Guid = Guid::parse("af86e2e0-b12d-4c6a-9c5a-d7aa65101e90");
45
46/// The three `IUnknown` slots every COM vtable starts with.
47#[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/// `IInspectable`: `IUnknown` plus three.
56#[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
64/// The first slot an interface's own methods can occupy.
65///
66/// Three for `IUnknown`, three for `IInspectable`. A method called one slot out
67/// is a jump into the wrong function with the wrong arguments.
68pub const FIRST_METHOD: usize = 6;
69
70/// An owned reference to a COM object.
71///
72/// Releases on drop and adds a reference on clone, so ownership follows Rust's
73/// rules rather than the caller's memory.
74pub struct ComPtr(*mut c_void);
75
76impl ComPtr {
77    /// Adopt a pointer the callee already added a reference for — which is the
78    /// convention for every `[out]` parameter and return value in COM.
79    ///
80    /// # Safety
81    /// `raw` must be null or a COM interface pointer owned at `+1`.
82    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    /// A stable identity key.
92    #[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        // SAFETY: a COM pointer's first word is its vtable pointer.
100        unsafe { *(self.0 as *const *const *const c_void) }
101    }
102
103    /// The function in slot `index`, typed.
104    ///
105    /// # Safety
106    /// `T` must match the signature at that slot, receiver included.
107    #[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    /// `QueryInterface`, which is how one interface on an object reaches
113    /// another — and how WinRT's many small interfaces on one class are used.
114    pub fn cast(&self, iid: Guid) -> Option<ComPtr> {
115        let mut out: *mut c_void = std::ptr::null_mut();
116        // SAFETY: slot 0 is always QueryInterface.
117        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        // SAFETY: slot 1 is always AddRef.
132        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        // SAFETY: slot 2 is always Release.
143        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
156// A COM object may be called from any thread; that is what IAgileObject
157// asserts, and every object this crate hands out is agile.
158unsafe impl Send for ComPtr {}
159unsafe impl Sync for ComPtr {}
160
161// ── Being called ────────────────────────────────────────────────────────────
162
163/// The vtable of a WinRT delegate: `IUnknown` plus a single `Invoke`.
164///
165/// Delegates are not `IInspectable`, so `Invoke` sits at slot three rather than
166/// six — the one place in this crate where [`FIRST_METHOD`] does not apply.
167#[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/// A delegate Windows can call: an event handler or an async completion.
174///
175/// `#[repr(C)]` with the vtable first, so a pointer to this *is* a valid COM
176/// interface pointer. The refcount is atomic because the runtime may hold and
177/// release it from several threads.
178#[repr(C)]
179pub struct Delegate {
180    vtable: *const DelegateVtbl,
181    references: AtomicU32,
182    /// The IID this delegate answers to — computed, for a parameterised type.
183    iid: Guid,
184    /// Called with the delegate's two arguments: sender and args, or the
185    /// completed operation and its status.
186    handler: Box<dyn Fn(*mut c_void, *mut c_void) + Send + Sync>,
187}
188
189impl Delegate {
190    /// Build one, returning a `+1` COM pointer.
191    ///
192    /// Not `-> Self`: the object owns itself and lives until the last
193    /// `Release`, so what the caller gets is a reference to it, not the value.
194    #[allow(clippy::new_ret_no_self)]
195    ///
196    /// The object owns itself: it is freed when the last `Release` arrives,
197    /// which is why this hands back a pointer rather than a Rust value.
198    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    // SAFETY: `this` is a Delegate, by construction.
230    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    // A delegate answers to IUnknown, to IAgileObject — refusing that makes the
238    // runtime marshal it across apartments — and to its own computed IID.
239    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        // Acquire pairs with every Release above, so the box is not dropped
260        // while another thread is still inside a method.
261        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    // A panic crossing back into Windows is undefined, so it stops here.
274    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    /// Call through the vtable exactly as COM would.
293    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        // Three pointers for IUnknown, six for IInspectable, four for a
313        // delegate. A wrong size means every slot after it is misaddressed.
314        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        // Its first word must be the vtable, or Windows calls into nothing.
332        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        // The same static `Delegate::new` installs.
340        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        // Unwinding across the ABI is undefined; it must become an HRESULT.
370        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            // QueryInterface adds a reference; give it back.
392            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        // The closure owns the Arc, so the count rises when the box is freed.
422        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); // the last Release
435        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        // Parameterised delegates differ only by computed IID, so this is what
460        // keeps an IAsyncOperation<bool> handler from being handed an
461        // IAsyncOperation<i32>.
462        let a = Delegate::new(TEST_IID, |_, _| {});
463        let b = Delegate::new(OTHER_IID, |_, _| {});
464
465        // Every *successful* QueryInterface hands back a +1 reference, so each
466        // one has to be released or the object never reaches zero. A failed
467        // one adds nothing and has nothing to release.
468        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}