Skip to main content

shared/
plain_data.rs

1//! Plain data: types for which every bit pattern is a valid value.
2//!
3//! Control command payloads cross the host/guest boundary as raw bytes, so a
4//! payload type must accept every byte pattern a guest can send. [`PlainData`]
5//! is that marker, in the style of `bytemuck::AnyBitPattern` or
6//! `zerocopy::FromBytes`.
7
8/// Marker trait for plain data: a type for which every bit pattern of
9/// `size_of::<Self>()` bytes is a valid value.
10///
11/// # Safety
12///
13/// A type may implement `PlainData` only when every bit pattern of its size is
14/// a valid value of the type. In particular, a `PlainData` type must not
15/// contain `bool`, `char`, enum, reference or pointer fields, and code must not
16/// read padding bytes of a `PlainData` structure as values.
17///
18/// A `PlainData` type must also have harmless drop glue: writing a payload over
19/// an existing one (`*output = ..`) drops the bytes the guest supplied, so a
20/// type with a `Drop` implementation (for example a password buffer that
21/// zeroises itself on drop, like `WifiPassword`) must not implement
22/// `PlainData`.
23///
24/// The integer and float primitives, `()` and arrays of plain data implement
25/// `PlainData`. Use [`plain_data!`](crate::plain_data) for `#[repr(C)]`
26/// structures: it implements `PlainData` only when every field type is itself
27/// plain data and the structure has no padding, which it checks at compile
28/// time.
29pub unsafe trait PlainData: Sized {}
30
31unsafe impl PlainData for u8 {}
32unsafe impl PlainData for u16 {}
33unsafe impl PlainData for u32 {}
34unsafe impl PlainData for u64 {}
35unsafe impl PlainData for u128 {}
36unsafe impl PlainData for usize {}
37unsafe impl PlainData for i8 {}
38unsafe impl PlainData for i16 {}
39unsafe impl PlainData for i32 {}
40unsafe impl PlainData for i64 {}
41unsafe impl PlainData for i128 {}
42unsafe impl PlainData for isize {}
43// Every bit pattern is a valid `f32`/`f64` (NaN payloads included).
44unsafe impl PlainData for f32 {}
45unsafe impl PlainData for f64 {}
46unsafe impl PlainData for () {}
47
48unsafe impl<T: PlainData, const N: usize> PlainData for [T; N] {}
49
50/// Declares a plain-data structure and implements [`PlainData`](crate::PlainData)
51/// for it.
52///
53/// The macro emits the structure itself, so the checked field list cannot drift
54/// from the declaration. Every field type must implement
55/// [`PlainData`](crate::PlainData), and the structure must have no padding
56/// bytes; both are checked at compile time.
57///
58/// Two forms are accepted:
59///
60/// - a named-field structure, which must be `#[repr(C)]` so that the guest and
61///   the host agree on the layout;
62/// - a tuple structure, which must be `#[repr(C)]`, or `#[repr(transparent)]`
63///   when it has a single field.
64///
65/// Other attributes (doc comments, `#[derive(..)]`, ...) may appear before or
66/// after the representation attribute. `#[repr(packed)]` on its own matches no
67/// form; combined with the `#[repr(C)]` the macro adds, rustc accepts the pair,
68/// so the macro rejects packing with a compile-time alignment check instead (a
69/// packed structure would expose misaligned field references).
70///
71/// # Safety contract
72///
73/// The structure must be `#[repr(C)]` or `#[repr(transparent)]` as required by
74/// each form, and every field type must be plain data. Padding bytes of a
75/// `#[repr(C)]` structure are never read as values: derived trait
76/// implementations compare or format fields, not padding. Because the
77/// padding check requires `size_of::<Self>()` to equal the sum of the field
78/// sizes, a `plain_data!` structure never has padding, so writing a payload
79/// never copies uninitialised memory across the host/guest boundary.
80///
81/// # Examples
82///
83/// ```
84/// use shared::plain_data;
85///
86/// plain_data! {
87///     #[repr(C)]
88///     #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89///     pub struct Example {
90///         pub version: u32,
91///         pub enabled: u8,
92///         pub reserved: [u8; 3],
93///     }
94/// }
95///
96/// // Other attributes may also come first.
97/// plain_data! {
98///     #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99///     #[repr(C)]
100///     pub struct Pair {
101///         pub first: u16,
102///         pub second: u16,
103///     }
104/// }
105///
106/// plain_data! {
107///     #[repr(C)]
108///     #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
109///     pub struct TuplePair(pub u16, pub u16);
110/// }
111///
112/// plain_data! {
113///     #[repr(transparent)]
114///     #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115///     pub struct Wrapper(pub u8);
116/// }
117/// ```
118///
119/// A field that is not plain data does not compile:
120///
121/// ```compile_fail,E0277
122/// use shared::plain_data;
123///
124/// plain_data! {
125///     #[repr(C)]
126///     pub struct Bad {
127///         pub flag: bool,
128///     }
129/// }
130/// ```
131///
132/// A structure with padding does not compile either:
133///
134/// ```compile_fail,E0080
135/// use shared::plain_data;
136///
137/// plain_data! {
138///     #[repr(C)]
139///     pub struct Padded {
140///         pub a: u8,
141///         pub b: u32,
142///     }
143/// }
144/// ```
145///
146/// A packed structure does not compile (rustc accepts `#[repr(C)]` combined
147/// with `#[repr(packed)]`, so the macro rejects it with an alignment check):
148///
149/// ```compile_fail,E0080
150/// use shared::plain_data;
151///
152/// plain_data! {
153///     #[repr(C)]
154///     #[repr(packed)]
155///     pub struct Packed {
156///         pub a: u8,
157///         pub b: u32,
158///     }
159/// }
160/// ```
161#[macro_export]
162macro_rules! plain_data {
163    // Named-field structure; `#[repr(C)]` is mandatory. Attributes before it
164    // were collected by the muncher arms below and are re-emitted first.
165    (
166        @munch [$($acc:tt)*]
167        #[repr(C)]
168        $(#[$meta:meta])*
169        $vis:vis struct $name:ident {
170            $(
171                $(#[$field_meta:meta])*
172                $field_vis:vis $field:ident : $field_ty:ty
173            ),* $(,)?
174        }
175    ) => {
176        $($acc)*
177        #[repr(C)]
178        $(#[$meta])*
179        $vis struct $name {
180            $(
181                $(#[$field_meta])*
182                $field_vis $field : $field_ty
183            ),*
184        }
185
186        const _: () = {
187            // Compile-time check: every field type accepts every bit pattern.
188            #[allow(dead_code)]
189            fn require_plain_data<T: $crate::PlainData>() {}
190            $(
191                let _: fn() = require_plain_data::<$field_ty>;
192            )*
193            // Compile-time check: no padding bytes, so a payload write never
194            // copies uninitialised memory.
195            assert!(
196                core::mem::size_of::<$name>()
197                    == 0 $(+ core::mem::size_of::<$field_ty>())*,
198                "plain_data! structure has padding bytes"
199            );
200            // Compile-time check: not packed. A packed structure has alignment
201            // 1, so its fields could be referenced misaligned.
202            let mut required_alignment = 1usize;
203            $(
204                if core::mem::align_of::<$field_ty>() > required_alignment {
205                    required_alignment = core::mem::align_of::<$field_ty>();
206                }
207            )*
208            assert!(
209                core::mem::align_of::<$name>() == required_alignment,
210                "plain_data! structure must not be packed"
211            );
212        };
213
214        // SAFETY: the structure is `#[repr(C)]`, every field type implements
215        // `PlainData` (checked above) and the structure has no padding (checked
216        // above), so every bit pattern is a valid value and no padding byte is
217        // ever read as a value.
218        unsafe impl $crate::PlainData for $name {}
219    };
220    // Tuple structure with `#[repr(C)]`; every field must be plain data.
221    (
222        @munch [$($acc:tt)*]
223        #[repr(C)]
224        $(#[$meta:meta])*
225        $vis:vis struct $name:ident (
226            $(
227                $(#[$field_meta:meta])*
228                $field_vis:vis $field_ty:ty
229            ),+ $(,)?
230        ) $(;)?
231    ) => {
232        $($acc)*
233        #[repr(C)]
234        $(#[$meta])*
235        $vis struct $name(
236            $(
237                $(#[$field_meta])*
238                $field_vis $field_ty
239            ),+
240        );
241
242        const _: () = {
243            // Compile-time check: every field type accepts every bit pattern.
244            #[allow(dead_code)]
245            fn require_plain_data<T: $crate::PlainData>() {}
246            $(
247                let _: fn() = require_plain_data::<$field_ty>;
248            )+
249            // Compile-time check: no padding bytes.
250            assert!(
251                core::mem::size_of::<$name>()
252                    == 0 $(+ core::mem::size_of::<$field_ty>())+,
253                "plain_data! structure has padding bytes"
254            );
255            // Compile-time check: not packed (see the named-field arm).
256            let mut required_alignment = 1usize;
257            $(
258                if core::mem::align_of::<$field_ty>() > required_alignment {
259                    required_alignment = core::mem::align_of::<$field_ty>();
260                }
261            )+
262            assert!(
263                core::mem::align_of::<$name>() == required_alignment,
264                "plain_data! structure must not be packed"
265            );
266        };
267
268        // SAFETY: the structure is `#[repr(C)]`, every field type implements
269        // `PlainData` (checked above) and the structure has no padding (checked
270        // above), so every bit pattern is a valid value.
271        unsafe impl $crate::PlainData for $name {}
272    };
273    // Single-field tuple structure; `#[repr(transparent)]` is mandatory.
274    (
275        @munch [$($acc:tt)*]
276        #[repr(transparent)]
277        $(#[$meta:meta])*
278        $vis:vis struct $name:ident (
279            $(#[$field_meta:meta])*
280            $field_vis:vis $field_ty:ty
281        ) $(;)?
282    ) => {
283        $($acc)*
284        #[repr(transparent)]
285        $(#[$meta])*
286        $vis struct $name(
287            $(#[$field_meta])*
288            $field_vis $field_ty
289        );
290
291        const _: () = {
292            // Compile-time check: the wrapped type accepts every bit pattern.
293            #[allow(dead_code)]
294            fn require_plain_data<T: $crate::PlainData>() {}
295            let _: fn() = require_plain_data::<$field_ty>;
296            // Compile-time check: `repr(transparent)` has no padding.
297            assert!(
298                core::mem::size_of::<$name>() == core::mem::size_of::<$field_ty>(),
299                "plain_data! structure has padding bytes"
300            );
301            assert!(
302                core::mem::align_of::<$name>() == core::mem::align_of::<$field_ty>(),
303                "plain_data! structure must not be packed"
304            );
305        };
306
307        // SAFETY: the structure is `#[repr(transparent)]` over a type that
308        // implements `PlainData` (checked above), so it has the same layout
309        // and every bit pattern is a valid value.
310        unsafe impl $crate::PlainData for $name {}
311    };
312    // Munch one leading attribute that is not the representation (a doc
313    // comment, `#[derive(..)]`, ...) and retry, so attributes may appear
314    // before `#[repr(C)]` / `#[repr(transparent)]`.
315    (
316        @munch [$($acc:tt)*]
317        #[$attr:meta] $($rest:tt)*
318    ) => {
319        $crate::plain_data!(@munch [$($acc)* #[$attr]] $($rest)*);
320    };
321    // No representation attribute found.
322    (
323        @munch [$($acc:tt)*]
324        $($rest:tt)*
325    ) => {
326        compile_error!("plain_data! requires #[repr(C)] or #[repr(transparent)]");
327    };
328    ($($tokens:tt)*) => {
329        $crate::plain_data!(@munch [] $($tokens)*);
330    };
331}
332
333#[cfg(test)]
334mod tests {
335    plain_data! {
336        #[repr(C)]
337        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
338        struct Nested {
339            a: u32,
340            b: [u8; 3],
341            reserved: u8,
342        }
343    }
344
345    plain_data! {
346        #[repr(C)]
347        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
348        struct Example {
349            nested: Nested,
350            array: [u16; 4],
351            version: u32,
352        }
353    }
354
355    // Attributes before the representation attribute are accepted too.
356    plain_data! {
357        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
358        #[repr(C)]
359        struct DerivedFirst {
360            a: u32,
361            b: u16,
362            reserved: [u8; 2],
363        }
364    }
365
366    plain_data! {
367        #[repr(transparent)]
368        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
369        struct Wrapper(pub u8);
370    }
371
372    #[test]
373    fn plain_data_structs_have_the_declared_layout() {
374        assert_eq!(core::mem::size_of::<Example>(), 20);
375        assert_eq!(core::mem::align_of::<Example>(), 4);
376        assert_eq!(core::mem::size_of::<Wrapper>(), 1);
377        assert_eq!(core::mem::size_of::<[u8; 0]>(), 0);
378    }
379
380    #[test]
381    fn plain_data_structs_have_no_padding() {
382        // The macro already rejects padding at compile time; these assertions
383        // pin the exact layouts the host and the guests agree on.
384        assert_eq!(
385            core::mem::size_of::<Nested>(),
386            core::mem::size_of::<u32>()
387                + core::mem::size_of::<[u8; 3]>()
388                + core::mem::size_of::<u8>()
389        );
390        assert_eq!(core::mem::size_of::<DerivedFirst>(), 8);
391        assert_eq!(
392            core::mem::size_of::<Example>(),
393            core::mem::size_of::<Nested>()
394                + core::mem::size_of::<[u16; 4]>()
395                + core::mem::size_of::<u32>()
396        );
397    }
398}