1#[repr(C)]
44pub struct Canary<const MAGIC: u32> {
45 magic: u32,
46}
47
48impl<const MAGIC: u32> Canary<MAGIC> {
49 pub const fn new() -> Self {
51 Canary { magic: MAGIC }
52 }
53
54 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 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
90pub 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 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; 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}