Skip to main content

fbl/
canary.rs

1// Copyright 2026 The Fuchsia Authors
2//
3// Use of this source code is governed by a MIT-style
4// license that can be found in the LICENSE file or at
5// https://opensource.org/licenses/MIT
6
7/// An embeddable structure guard.
8///
9/// To use `fbl::Canary`, choose a 4-byte guard value.
10///
11/// You can use the `Canary::new()` method to instantiate a `Canary` object.
12/// The compiler will infer the magic value from the type definition.
13///
14/// ```rust
15/// struct MyStruct {
16///     canary: fbl::Canary<{ fbl::magic(b"guar") }>,
17///     // ...
18/// }
19///
20/// impl MyStruct {
21///     fn new() -> Self {
22///         MyStruct {
23///             canary: fbl::Canary::new(),
24///             // ...
25///         }
26///     }
27/// }
28/// ```
29///
30/// The canary initializes itself with the guard value during construction and
31/// checks it during destruction (on `Drop`). You can also manually check the
32/// value during the lifetime of your object by calling the `assert` method.
33///
34/// If the value is not an ASCII string, you can directly use an integer literal
35/// as the const generic parameter.
36///
37/// ```rust
38/// struct MyStruct {
39///     canary: fbl::Canary<0x12345678>,
40///     // ...
41/// }
42/// ```
43#[repr(C)]
44pub struct Canary<const MAGIC: u32> {
45    magic: u32,
46}
47
48impl<const MAGIC: u32> Canary<MAGIC> {
49    /// Create a new Canary with the specified magic value.
50    pub const fn new() -> Self {
51        Canary { magic: MAGIC }
52    }
53
54    /// Assert that the value of `magic` is as expected.
55    ///
56    /// # Panics
57    ///
58    /// Panics if `self.magic` is not the expected value.
59    pub fn assert(&self) {
60        let observed_magic = unsafe { core::ptr::read_volatile(&self.magic) };
61        if observed_magic != MAGIC {
62            panic!("Invalid canary (expt: {:08x}, got: {:08x})", MAGIC, observed_magic);
63        }
64    }
65
66    /// Some places have special handling of bad magic values. For these
67    /// cases, simply return whether the `magic` is correct, and let
68    /// them respond appropriately if not.
69    pub fn valid(&self) -> bool {
70        let observed_magic = unsafe { core::ptr::read_volatile(&self.magic) };
71        observed_magic == MAGIC
72    }
73}
74
75impl<const MAGIC: u32> Default for Canary<MAGIC> {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl<const MAGIC: u32> Drop for Canary<MAGIC> {
82    fn drop(&mut self) {
83        self.assert();
84        unsafe {
85            core::ptr::write_volatile(&mut self.magic, 0);
86        }
87    }
88}
89
90/// Function for generating canary magic values from strings
91pub const fn magic(str: &[u8; 4]) -> u32 {
92    ((str[0] as u32) << 24) | ((str[1] as u32) << 16) | ((str[2] as u32) << 8) | (str[3] as u32)
93}
94
95#[macro_export]
96macro_rules! canary {
97    ($str:literal) => {
98        $crate::Canary::<{ $crate::magic($str) }>::new()
99    };
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn test_canary_default() {
108        let canary: Canary<{ magic(b"test") }> = Default::default();
109        assert!(canary.valid());
110    }
111
112    #[test]
113    fn test_magic_runtime() {
114        let m = magic(b"abcd");
115        assert_eq!(m, 0x61626364);
116    }
117
118    #[test]
119    fn test_canary() {
120        let canary = canary!(b"test");
121        assert!(canary.valid());
122        canary.assert();
123    }
124
125    #[test]
126    #[should_panic(expected = "Invalid canary")]
127    fn test_canary_corruption() {
128        let mut canary = canary!(b"test");
129        // Corrupt the canary storage directly
130        unsafe {
131            core::ptr::write_volatile(&mut canary.magic, 0);
132        }
133        canary.assert();
134    }
135
136    unsafe extern "C" {
137        fn check_rust_canary(ptr: *const core::ffi::c_void, expected_magic: u32) -> bool;
138    }
139
140    #[test]
141    #[cfg_attr(miri, ignore = "miri does not support calling foreign functions")]
142    fn test_canary_ffi() {
143        const MAGIC_VAL: u32 = 0x12345678; // Must match the hardcoded value in C++ helper
144        let canary = Canary::<MAGIC_VAL>::new();
145        unsafe {
146            assert!(check_rust_canary(&canary as *const _ as *const core::ffi::c_void, MAGIC_VAL));
147        }
148    }
149}