Skip to main content

webbluetooth_windows/
winrt.rs

1//! Strings and activation — the two things `combase.dll` is needed for.
2//!
3//! WinRT strings are `HSTRING`: immutable, reference-counted, UTF-16, and
4//! allocated by the runtime. WinRT objects are reached through an *activation
5//! factory*, asked for by class name, which is why the class names in
6//! [`crate::iids::classes`] matter as much as the IIDs beside them.
7//!
8//! The UTF-16 conversion is ordinary Rust and is tested here; everything that
9//! crosses into `combase` is not, and cannot be without Windows.
10
11// An HSTRING is a handle, not something dereferenced here — it is passed
12// straight back to combase, which is what validates it.
13#![allow(clippy::not_unsafe_ptr_arg_deref)]
14
15use crate::com::{succeeded, ComPtr, Hresult};
16use crate::guid::Guid;
17use std::ffi::c_void;
18
19/// An `HSTRING`.
20pub type HString = *mut c_void;
21
22// These six live in `combase.dll` at runtime, but the Windows SDK ships no
23// `combase.lib` to import them from — naming the DLL here fails the link with
24// `LNK1181: cannot open input file 'combase.lib'` (and the lld-link spelling,
25// `could not open 'combase.lib'`). `runtimeobject.lib` is the SDK import
26// library that resolves the WinRT string and activation exports, so the lib
27// name and the DLL name deliberately differ.
28#[cfg(windows)]
29#[link(name = "runtimeobject")]
30unsafe extern "system" {
31    fn WindowsCreateString(source: *const u16, length: u32, out: *mut HString) -> Hresult;
32    fn WindowsDeleteString(string: HString) -> Hresult;
33    fn WindowsGetStringRawBuffer(string: HString, length: *mut u32) -> *const u16;
34    fn RoInitialize(kind: i32) -> Hresult;
35    fn RoUninitialize();
36    fn RoGetActivationFactory(
37        class_id: HString,
38        iid: *const Guid,
39        factory: *mut *mut c_void,
40    ) -> Hresult;
41}
42
43// Off Windows these are never called — the backend is `cfg`'d out — but the
44// module still compiles so its conversions can be tested anywhere.
45#[cfg(not(windows))]
46#[allow(non_snake_case, unused_variables)]
47mod stubs {
48    use super::*;
49    pub unsafe fn WindowsCreateString(_: *const u16, _: u32, _: *mut HString) -> Hresult {
50        crate::com::E_NOINTERFACE
51    }
52    pub unsafe fn WindowsDeleteString(_: HString) -> Hresult {
53        crate::com::S_OK
54    }
55    pub unsafe fn WindowsGetStringRawBuffer(_: HString, length: *mut u32) -> *const u16 {
56        if !length.is_null() {
57            unsafe { *length = 0 };
58        }
59        std::ptr::null()
60    }
61    pub unsafe fn RoInitialize(_: i32) -> Hresult {
62        crate::com::E_NOINTERFACE
63    }
64    pub unsafe fn RoUninitialize() {}
65    pub unsafe fn RoGetActivationFactory(
66        _: HString,
67        _: *const Guid,
68        _: *mut *mut c_void,
69    ) -> Hresult {
70        crate::com::E_NOINTERFACE
71    }
72}
73#[cfg(not(windows))]
74use stubs::*;
75
76/// `RO_INIT_MULTITHREADED`. Single-threaded apartments need a message pump, and
77/// a library has no business installing one.
78const RO_INIT_MULTITHREADED: i32 = 1;
79
80/// An owned `HSTRING`, deleted on drop.
81pub struct WinRtString(HString);
82
83impl WinRtString {
84    /// Copy a Rust string into the runtime.
85    pub fn new(s: &str) -> Option<Self> {
86        let utf16 = to_utf16(s);
87        let mut out: HString = std::ptr::null_mut();
88        // The length excludes the terminator, which the runtime adds.
89        let hr = unsafe { WindowsCreateString(utf16.as_ptr(), (utf16.len() - 1) as u32, &mut out) };
90        (succeeded(hr) && !out.is_null()).then_some(Self(out))
91    }
92
93    #[inline]
94    pub fn as_raw(&self) -> HString {
95        self.0
96    }
97
98    /// Read an `HSTRING` back, borrowed. An empty string is a null handle, not
99    /// a pointer to nothing — which is why this is not simply a null check.
100    pub fn read(handle: HString) -> String {
101        if handle.is_null() {
102            return String::new();
103        }
104        let mut length = 0u32;
105        let buffer = unsafe { WindowsGetStringRawBuffer(handle, &mut length) };
106        if buffer.is_null() || length == 0 {
107            return String::new();
108        }
109        let slice = unsafe { std::slice::from_raw_parts(buffer, length as usize) };
110        String::from_utf16_lossy(slice)
111    }
112}
113
114impl Drop for WinRtString {
115    fn drop(&mut self) {
116        unsafe { WindowsDeleteString(self.0) };
117    }
118}
119
120/// Release an `HSTRING` obtained from a property getter.
121///
122/// # Safety
123/// `handle` must be an `HSTRING` this process owns and has not already deleted.
124pub unsafe fn delete_string(handle: HString) {
125    unsafe { WindowsDeleteString(handle) };
126}
127
128/// UTF-16, NUL-terminated.
129///
130/// Windows wants sixteen-bit units with a terminator; Rust strings are UTF-8
131/// with neither. Astral characters become surrogate pairs, which `encode_utf16`
132/// handles and a naive cast would not.
133pub fn to_utf16(s: &str) -> Vec<u16> {
134    let mut out: Vec<u16> = s.encode_utf16().collect();
135    out.push(0);
136    out
137}
138
139/// Join the multi-threaded apartment for this thread.
140///
141/// Every thread that touches WinRT must, and it is refcounted, so calling twice
142/// is fine as long as each is balanced.
143pub fn initialize() -> bool {
144    // RPC_E_CHANGED_MODE means the thread is already in a single-threaded
145    // apartment — someone else's, and workable.
146    const RPC_E_CHANGED_MODE: Hresult = -2147417850;
147    let hr = unsafe { RoInitialize(RO_INIT_MULTITHREADED) };
148    succeeded(hr) || hr == RPC_E_CHANGED_MODE
149}
150
151pub fn uninitialize() {
152    unsafe { RoUninitialize() };
153}
154
155/// The activation factory for a runtime class.
156///
157/// Every WinRT object begins here: `BluetoothLEDevice` has no constructor, only
158/// static methods on a factory reached by name.
159pub fn activation_factory(class_name: &str, iid: Guid) -> Option<ComPtr> {
160    let name = WinRtString::new(class_name)?;
161    let mut factory: *mut c_void = std::ptr::null_mut();
162    let hr = unsafe { RoGetActivationFactory(name.as_raw(), &iid, &mut factory) };
163    if !succeeded(hr) {
164        return None;
165    }
166    // SAFETY: the factory arrives at +1.
167    unsafe { ComPtr::adopt(factory) }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn utf16_is_terminated() {
176        assert_eq!(to_utf16(""), vec![0]);
177        assert_eq!(to_utf16("ab"), vec![0x61, 0x62, 0]);
178        assert_eq!(*to_utf16("anything").last().unwrap(), 0);
179    }
180
181    #[test]
182    fn astral_characters_become_surrogate_pairs() {
183        // A naive byte-to-u16 cast would mangle these; encode_utf16 does not.
184        let coffee = to_utf16("☕");
185        assert_eq!(coffee, vec![0x2615, 0]);
186
187        let emoji = to_utf16("🦀");
188        assert_eq!(emoji.len(), 3, "one pair plus the terminator");
189        assert_eq!(emoji, vec![0xD83E, 0xDD80, 0]);
190    }
191
192    #[test]
193    fn the_length_passed_to_windows_excludes_the_terminator() {
194        // WindowsCreateString takes the character count, not the buffer length;
195        // passing the latter creates a string with a stray NUL inside it.
196        for s in ["", "a", "hello", "☕", "🦀"] {
197            let utf16 = to_utf16(s);
198            assert_eq!(utf16.len() - 1, s.encode_utf16().count());
199        }
200    }
201
202    #[test]
203    fn reading_a_null_handle_gives_an_empty_string() {
204        // WinRT represents the empty string as a null HSTRING, so this is a
205        // normal value rather than a failure.
206        assert_eq!(WinRtString::read(std::ptr::null_mut()), "");
207    }
208
209    #[test]
210    fn class_names_round_trip_through_utf16() {
211        let name = "Windows.Devices.Bluetooth.BluetoothLEDevice";
212        let utf16 = to_utf16(name);
213        assert_eq!(String::from_utf16_lossy(&utf16[..utf16.len() - 1]), name);
214    }
215}