Skip to main content

webbluetooth_windows/
guid.rs

1//! GUIDs, and the one WinRT computes rather than publishes.
2//!
3//! Most WinRT interfaces have an IID written down in metadata, and those are
4//! vendored in [`crate::iids`]. *Parameterised* interfaces do not:
5//! `IAsyncOperation<GattDeviceServicesResult>` is a distinct interface from
6//! `IAsyncOperation<bool>`, with a distinct IID, and there are too many
7//! instantiations to enumerate. So WinRT derives them.
8//!
9//! The rule is a UUID version 5 — SHA-1 over a namespace GUID and a name — with
10//! a fixed namespace and a *signature string* for the name:
11//!
12//! ```text
13//!   pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};rc(Windows.Foo.Bar;{…}))
14//!   └ the generic's own GUID ┘                        └ the argument's signature ┘
15//! ```
16//!
17//! Signatures nest, so a handler over an operation over a runtime class builds
18//! one string three levels deep. Every primitive has a short code; an interface
19//! is its IID in braces; a runtime class is its name and the IID of its default
20//! interface.
21//!
22//! # What is and is not checked here
23//!
24//! The UUID-5 construction is pinned against a published vector, and the
25//! signature strings are pinned against the exact byte sequences Microsoft's
26//! own generated bindings use. What cannot be checked without Windows is the
27//! composition of the two — that a computed IID is one the system will accept.
28
29use std::fmt;
30
31/// A COM `GUID`, laid out as the ABI expects.
32///
33/// The first three fields are little-endian on the wire; the last is a byte
34/// array and is not byte-swapped. Getting that wrong produces a GUID that
35/// looks right when printed and matches nothing.
36#[repr(C)]
37#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
38pub struct Guid {
39    pub data1: u32,
40    pub data2: u16,
41    pub data3: u16,
42    pub data4: [u8; 8],
43}
44
45impl Guid {
46    /// From the canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` form.
47    ///
48    /// # Panics
49    /// If the string is not a well-formed GUID. Every call site passes a
50    /// literal, so a malformed one is a bug to find at first run, not a
51    /// `Result` to thread through the whole crate.
52    pub const fn parse(s: &str) -> Self {
53        let b = s.as_bytes();
54        assert!(b.len() == 36, "a GUID is 36 characters");
55        assert!(
56            b[8] == b'-' && b[13] == b'-' && b[18] == b'-' && b[23] == b'-',
57            "GUID separators are misplaced"
58        );
59
60        const fn hex(c: u8) -> u32 {
61            match c {
62                b'0'..=b'9' => (c - b'0') as u32,
63                b'a'..=b'f' => (c - b'a' + 10) as u32,
64                b'A'..=b'F' => (c - b'A' + 10) as u32,
65                _ => panic!("not a hex digit in a GUID"),
66            }
67        }
68        const fn u32_at(b: &[u8], i: usize) -> u32 {
69            let mut v = 0u32;
70            let mut k = 0;
71            while k < 8 {
72                v = (v << 4) | hex(b[i + k]);
73                k += 1;
74            }
75            v
76        }
77        const fn u16_at(b: &[u8], i: usize) -> u16 {
78            ((hex(b[i]) << 12) | (hex(b[i + 1]) << 8) | (hex(b[i + 2]) << 4) | hex(b[i + 3])) as u16
79        }
80        const fn u8_at(b: &[u8], i: usize) -> u8 {
81            ((hex(b[i]) << 4) | hex(b[i + 1])) as u8
82        }
83
84        Self {
85            data1: u32_at(b, 0),
86            data2: u16_at(b, 9),
87            data3: u16_at(b, 14),
88            data4: [
89                u8_at(b, 19),
90                u8_at(b, 21),
91                u8_at(b, 24),
92                u8_at(b, 26),
93                u8_at(b, 28),
94                u8_at(b, 30),
95                u8_at(b, 32),
96                u8_at(b, 34),
97            ],
98        }
99    }
100
101    /// The 16 bytes in big-endian (RFC 4122) order, which is what hashing uses.
102    pub fn to_be_bytes(self) -> [u8; 16] {
103        let mut out = [0u8; 16];
104        out[0..4].copy_from_slice(&self.data1.to_be_bytes());
105        out[4..6].copy_from_slice(&self.data2.to_be_bytes());
106        out[6..8].copy_from_slice(&self.data3.to_be_bytes());
107        out[8..16].copy_from_slice(&self.data4);
108        out
109    }
110
111    fn from_be_bytes(b: [u8; 16]) -> Self {
112        Self {
113            data1: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
114            data2: u16::from_be_bytes([b[4], b[5]]),
115            data3: u16::from_be_bytes([b[6], b[7]]),
116            data4: [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]],
117        }
118    }
119
120    /// The signature of this interface, for use inside a parameterised one.
121    pub fn signature(&self) -> String {
122        format!("{{{self}}}")
123    }
124}
125
126impl fmt::Display for Guid {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(
129            f,
130            "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
131            self.data1,
132            self.data2,
133            self.data3,
134            self.data4[0],
135            self.data4[1],
136            self.data4[2],
137            self.data4[3],
138            self.data4[4],
139            self.data4[5],
140            self.data4[6],
141            self.data4[7]
142        )
143    }
144}
145
146impl fmt::Debug for Guid {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        write!(f, "{self}")
149    }
150}
151
152/// A WinRT type, as far as computing a signature needs to know.
153#[derive(Debug, Clone)]
154pub enum Signature {
155    /// `b1`, `i4`, `string`, and the rest of the primitive codes.
156    Primitive(&'static str),
157    /// A non-parameterised interface: its IID in braces.
158    Interface(Guid),
159    /// `rc(Full.Type.Name;<default interface>)`.
160    Class {
161        name: &'static str,
162        default_interface: Guid,
163    },
164    /// `enum(Full.Type.Name;i4)` — or `u4` for a flags enum.
165    Enum { name: &'static str, signed: bool },
166    /// `struct(Full.Type.Name;<fields>)`.
167    Struct {
168        name: &'static str,
169        fields: Vec<Signature>,
170    },
171    /// `delegate({iid})`.
172    Delegate(Guid),
173    /// `pinterface({generic};<args>)`.
174    Parameterized {
175        generic: Guid,
176        arguments: Vec<Signature>,
177    },
178}
179
180impl Signature {
181    pub const BOOL: Self = Self::Primitive("b1");
182    pub const U8: Self = Self::Primitive("u1");
183    pub const I16: Self = Self::Primitive("i2");
184    pub const U16: Self = Self::Primitive("u2");
185    pub const I32: Self = Self::Primitive("i4");
186    pub const U32: Self = Self::Primitive("u4");
187    pub const I64: Self = Self::Primitive("i8");
188    pub const U64: Self = Self::Primitive("u8");
189    pub const STRING: Self = Self::Primitive("string");
190    pub const GUID: Self = Self::Primitive("g16");
191    /// `IInspectable`.
192    pub const OBJECT: Self = Self::Primitive("cinterface(IInspectable)");
193
194    /// The signature string WinRT hashes.
195    pub fn text(&self) -> String {
196        match self {
197            Self::Primitive(code) => (*code).to_string(),
198            Self::Interface(iid) => iid.signature(),
199            Self::Class {
200                name,
201                default_interface,
202            } => {
203                format!("rc({name};{})", default_interface.signature())
204            }
205            Self::Enum { name, signed } => {
206                format!("enum({name};{})", if *signed { "i4" } else { "u4" })
207            }
208            Self::Struct { name, fields } => {
209                let inner: Vec<String> = fields.iter().map(Self::text).collect();
210                format!("struct({name};{})", inner.join(";"))
211            }
212            Self::Delegate(iid) => format!("delegate({})", iid.signature()),
213            Self::Parameterized { generic, arguments } => {
214                let inner: Vec<String> = arguments.iter().map(Self::text).collect();
215                format!("pinterface({};{})", generic.signature(), inner.join(";"))
216            }
217        }
218    }
219
220    /// The IID of this type, computed if it is parameterised.
221    ///
222    /// A non-parameterised interface already has one; anything else has no IID
223    /// at all and this returns `None`.
224    pub fn iid(&self) -> Option<Guid> {
225        match self {
226            Self::Interface(iid) | Self::Delegate(iid) => Some(*iid),
227            Self::Parameterized { .. } => {
228                Some(uuid_v5(WINRT_PIID_NAMESPACE, self.text().as_bytes()))
229            }
230            _ => None,
231        }
232    }
233}
234
235/// The namespace WinRT hashes every parameterised interface against.
236pub const WINRT_PIID_NAMESPACE: Guid = Guid::parse("11f47ad5-7b73-42c0-abae-878b1e16adee");
237
238/// A version 5 UUID: SHA-1 over a namespace and a name, per RFC 4122.
239pub fn uuid_v5(namespace: Guid, name: &[u8]) -> Guid {
240    let mut input = Vec::with_capacity(16 + name.len());
241    input.extend_from_slice(&namespace.to_be_bytes());
242    input.extend_from_slice(name);
243
244    let hash = sha1(&input);
245    let mut bytes = [0u8; 16];
246    bytes.copy_from_slice(&hash[..16]);
247    // Version 5 in the high nibble of byte 6, RFC 4122 variant in byte 8.
248    bytes[6] = (bytes[6] & 0x0F) | 0x50;
249    bytes[8] = (bytes[8] & 0x3F) | 0x80;
250    Guid::from_be_bytes(bytes)
251}
252
253/// SHA-1. The same one the DEX writer needs, kept here so neither crate
254/// depends on the other.
255fn sha1(data: &[u8]) -> [u8; 20] {
256    let mut h: [u32; 5] = [
257        0x6745_2301,
258        0xEFCD_AB89,
259        0x98BA_DCFE,
260        0x1032_5476,
261        0xC3D2_E1F0,
262    ];
263
264    let mut message = data.to_vec();
265    let bit_length = (data.len() as u64) * 8;
266    message.push(0x80);
267    while message.len() % 64 != 56 {
268        message.push(0);
269    }
270    message.extend_from_slice(&bit_length.to_be_bytes());
271
272    for chunk in message.chunks_exact(64) {
273        let mut w = [0u32; 80];
274        for (i, word) in chunk.chunks_exact(4).enumerate() {
275            w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
276        }
277        for i in 16..80 {
278            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
279        }
280        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
281        for (i, word) in w.iter().enumerate() {
282            let (f, k) = match i {
283                0..=19 => ((b & c) | (!b & d), 0x5A82_7999),
284                20..=39 => (b ^ c ^ d, 0x6ED9_EBA1),
285                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
286                _ => (b ^ c ^ d, 0xCA62_C1D6),
287            };
288            let temp = a
289                .rotate_left(5)
290                .wrapping_add(f)
291                .wrapping_add(e)
292                .wrapping_add(k)
293                .wrapping_add(*word);
294            e = d;
295            d = c;
296            c = b.rotate_left(30);
297            b = a;
298            a = temp;
299        }
300        h[0] = h[0].wrapping_add(a);
301        h[1] = h[1].wrapping_add(b);
302        h[2] = h[2].wrapping_add(c);
303        h[3] = h[3].wrapping_add(d);
304        h[4] = h[4].wrapping_add(e);
305    }
306
307    let mut out = [0u8; 20];
308    for (i, word) in h.iter().enumerate() {
309        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
310    }
311    out
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317    use crate::iids::generics;
318
319    #[test]
320    fn guids_round_trip_through_their_text_form() {
321        for text in [
322            "9fc2b0bb-e446-44e2-aa61-9cab8f636af2",
323            "00000000-0000-0000-0000-000000000000",
324            "ffffffff-ffff-ffff-ffff-ffffffffffff",
325            "11f47ad5-7b73-42c0-abae-878b1e16adee",
326        ] {
327            assert_eq!(Guid::parse(text).to_string(), text);
328        }
329    }
330
331    /// `DeviceInformationCollection` is the one class this crate names by hand,
332    /// because its default interface is parameterised and so the generator
333    /// skips it. This pins the shape against what Microsoft's own metadata
334    /// says it is — `for_class::<Self, IVectorView<DeviceInformation>>` — so a
335    /// wrong IID fails here rather than silently returning no adapters.
336    #[test]
337    fn a_class_with_a_parameterised_default_interface_gets_an_iid() {
338        use crate::iids::classes;
339
340        let element = Signature::Parameterized {
341            generic: generics::I_VECTOR_VIEW,
342            arguments: vec![Signature::Class {
343                name: classes::DEVICE_INFORMATION.0,
344                default_interface: classes::DEVICE_INFORMATION.1,
345            }],
346        };
347        let iid = element.iid().expect("a parameterised signature has an IID");
348
349        // Not the generic's own GUID: the argument has to change it, or every
350        // instantiation would share one IID and QueryInterface would be a
351        // coin toss.
352        assert_ne!(iid, generics::I_VECTOR_VIEW);
353        assert_ne!(iid, classes::DEVICE_INFORMATION.1);
354
355        // And it is stable: the same inputs give the same answer, which is
356        // what makes it safe to compute at each call site.
357        let again = Signature::Parameterized {
358            generic: generics::I_VECTOR_VIEW,
359            arguments: vec![Signature::Class {
360                name: classes::DEVICE_INFORMATION.0,
361                default_interface: classes::DEVICE_INFORMATION.1,
362            }],
363        }
364        .iid()
365        .unwrap();
366        assert_eq!(iid, again);
367
368        // Changing the element type must change the IID; if it did not, the
369        // hash would not be covering the argument at all.
370        let other = Signature::Parameterized {
371            generic: generics::I_VECTOR_VIEW,
372            arguments: vec![Signature::Primitive("string")],
373        }
374        .iid()
375        .unwrap();
376        assert_ne!(iid, other);
377    }
378
379    #[test]
380    fn the_abi_layout_is_what_com_expects() {
381        assert_eq!(std::mem::size_of::<Guid>(), 16);
382        assert_eq!(std::mem::align_of::<Guid>(), 4);
383    }
384
385    #[test]
386    fn only_the_first_three_fields_are_byte_swapped() {
387        // The trailing eight bytes are an array, not an integer — swapping them
388        // gives a GUID that prints correctly and matches nothing.
389        let g = Guid::parse("01020304-0506-0708-090a-0b0c0d0e0f10");
390        assert_eq!(g.data1, 0x0102_0304);
391        assert_eq!(g.data2, 0x0506);
392        assert_eq!(g.data3, 0x0708);
393        assert_eq!(g.data4, [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10]);
394        assert_eq!(
395            g.to_be_bytes(),
396            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
397        );
398    }
399
400    #[test]
401    fn sha1_matches_known_vectors() {
402        assert_eq!(
403            sha1(b"abc"),
404            [
405                0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50,
406                0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D
407            ]
408        );
409        assert_eq!(
410            sha1(b""),
411            [
412                0xDA, 0x39, 0xA3, 0xEE, 0x5E, 0x6B, 0x4B, 0x0D, 0x32, 0x55, 0xBF, 0xEF, 0x95, 0x60,
413                0x18, 0x90, 0xAF, 0xD8, 0x07, 0x09
414            ]
415        );
416    }
417
418    #[test]
419    fn uuid_v5_matches_the_published_vector() {
420        // The widely reproduced RFC 4122 v5 example: the DNS namespace over
421        // "python.org". If this is right, the hashing, the big-endian namespace
422        // and the version/variant bits all are.
423        let dns = Guid::parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
424        assert_eq!(
425            uuid_v5(dns, b"python.org").to_string(),
426            "886313e1-3b8a-5372-9b90-0c9aee199e5d"
427        );
428    }
429
430    #[test]
431    fn version_and_variant_bits_are_set() {
432        let id = uuid_v5(WINRT_PIID_NAMESPACE, b"anything at all");
433        assert_eq!(id.data3 >> 12, 5, "version must be 5");
434        assert_eq!(id.data4[0] >> 6, 0b10, "variant must be RFC 4122");
435    }
436
437    #[test]
438    fn signature_strings_match_the_official_bindings() {
439        // These are the exact byte sequences Microsoft's generated bindings
440        // build, copied from windows-rs. If the shape were wrong, every
441        // computed IID would be wrong in a way nothing here could detect.
442        let handler = Signature::Parameterized {
443            generic: generics::TYPED_EVENT_HANDLER,
444            arguments: vec![Signature::OBJECT, Signature::OBJECT],
445        };
446        assert!(
447            handler
448                .text()
449                .starts_with("pinterface({9de1c534-6ae1-11e0-84e1-18a905bcc53f};"),
450            "got {}",
451            handler.text()
452        );
453
454        let operation = Signature::Parameterized {
455            generic: generics::I_ASYNC_OPERATION,
456            arguments: vec![Signature::BOOL],
457        };
458        assert_eq!(
459            operation.text(),
460            "pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};b1)"
461        );
462    }
463
464    #[test]
465    fn nested_signatures_compose() {
466        // A completed handler over an operation over a runtime class — three
467        // levels, which is what a real GATT call needs.
468        let class = Signature::Class {
469            name: "Windows.Devices.Bluetooth.BluetoothLEDevice",
470            default_interface: Guid::parse("b5ee2f7b-4ad8-4642-ac48-80a0b500e887"),
471        };
472        let operation = Signature::Parameterized {
473            generic: generics::I_ASYNC_OPERATION,
474            arguments: vec![class],
475        };
476        let handler = Signature::Parameterized {
477            generic: generics::ASYNC_OPERATION_COMPLETED_HANDLER,
478            arguments: vec![operation.clone()],
479        };
480
481        assert_eq!(
482            operation.text(),
483            "pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};\
484             rc(Windows.Devices.Bluetooth.BluetoothLEDevice;\
485             {b5ee2f7b-4ad8-4642-ac48-80a0b500e887}))"
486                .replace(char::is_whitespace, "")
487        );
488        assert!(handler.text().contains(&operation.text()));
489        // Distinct instantiations must not collide.
490        assert_ne!(operation.iid(), handler.iid());
491    }
492
493    #[test]
494    fn a_parameterised_iid_is_stable_and_argument_dependent() {
495        let of = |arg: Signature| {
496            Signature::Parameterized {
497                generic: generics::I_ASYNC_OPERATION,
498                arguments: vec![arg],
499            }
500            .iid()
501            .unwrap()
502        };
503        assert_eq!(
504            of(Signature::BOOL),
505            of(Signature::BOOL),
506            "must be deterministic"
507        );
508        assert_ne!(
509            of(Signature::BOOL),
510            of(Signature::I32),
511            "must depend on the argument"
512        );
513    }
514
515    #[test]
516    fn non_parameterised_types_have_no_computed_iid() {
517        assert!(Signature::BOOL.iid().is_none());
518        assert!(Signature::Class {
519            name: "X.Y",
520            default_interface: Guid::default()
521        }
522        .iid()
523        .is_none());
524        let iid = Guid::parse("59cb50c1-5934-4f68-a198-eb864fa44e6b");
525        assert_eq!(Signature::Interface(iid).iid(), Some(iid));
526    }
527}