tpm2_protocol/macro/
mod.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5pub mod r#enum;
6pub mod integer;
7pub mod r#struct;
8
9#[macro_export]
10macro_rules! tpm_bitflags {
11    (
12        $(#[$outer:meta])*
13        $vis:vis struct $name:ident($repr:ty) {
14            $(
15                $(#[$inner:meta])*
16                const $field:ident = $value:expr, $string_name:literal;
17            )*
18        }
19    ) => {
20        $(#[$outer])*
21        $vis struct $name($repr);
22
23        impl $name {
24            $(
25                $(#[$inner])*
26                pub const $field: Self = Self($value);
27            )*
28
29            #[must_use]
30            pub const fn bits(&self) -> $repr {
31                self.0
32            }
33
34            #[must_use]
35            pub const fn from_bits_truncate(bits: $repr) -> Self {
36                Self(bits)
37            }
38
39            #[must_use]
40            pub const fn empty() -> Self {
41                Self(0)
42            }
43
44            #[must_use]
45            pub const fn contains(&self, other: Self) -> bool {
46                (self.0 & other.0) == other.0
47            }
48
49            pub fn flag_names(&self) -> impl Iterator<Item = &'static str> + '_ {
50                [
51                    $(
52                        (Self::$field, $string_name),
53                    )*
54                ]
55                .into_iter()
56                .filter(move |(flag, _)| self.contains(*flag))
57                .map(|(_, name)| name)
58            }
59        }
60
61        impl core::ops::BitOr for $name {
62            type Output = Self;
63            fn bitor(self, rhs: Self) -> Self::Output {
64                Self(self.0 | rhs.0)
65            }
66        }
67
68        impl core::ops::BitOrAssign for $name {
69            fn bitor_assign(&mut self, rhs: Self) {
70                self.0 |= rhs.0;
71            }
72        }
73
74        impl $crate::TpmBuild for $name {
75            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
76                $crate::TpmBuild::build(&self.0, writer)
77            }
78        }
79
80        impl $crate::TpmParse for $name {
81            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
82                let (val, buf) = <$repr>::parse(buf)?;
83                Ok((Self(val), buf))
84            }
85        }
86
87        impl $crate::TpmSized for $name {
88            const SIZE: usize = core::mem::size_of::<$repr>();
89            fn len(&self) -> usize {
90                Self::SIZE
91            }
92        }
93    };
94}
95
96#[macro_export]
97macro_rules! tpm_bool {
98    (
99        $(#[$outer:meta])*
100        $vis:vis struct $name:ident(bool);
101    ) => {
102        $(#[$outer])*
103        $vis struct $name(pub bool);
104
105        impl From<bool> for $name {
106            fn from(val: bool) -> Self {
107                Self(val)
108            }
109        }
110
111        impl From<$name> for bool {
112            fn from(val: $name) -> Self {
113                val.0
114            }
115        }
116
117        impl $crate::TpmBuild for $name {
118            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
119                $crate::TpmBuild::build(&u8::from(self.0), writer)
120            }
121        }
122
123        impl $crate::TpmParse for $name {
124            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
125                let (val, buf) = u8::parse(buf)?;
126                match val {
127                    0 => Ok((Self(false), buf)),
128                    1 => Ok((Self(true), buf)),
129                    _ => Err($crate::TpmErrorKind::NotDiscriminant (stringify!($name), TpmNotDiscriminant::Unsigned(u64::from(val)))),
130                }
131            }
132        }
133
134        impl $crate::TpmSized for $name {
135            const SIZE: usize = core::mem::size_of::<u8>();
136            fn len(&self) -> usize {
137                Self::SIZE
138            }
139        }
140    };
141}
142
143#[macro_export]
144macro_rules! tpm_dispatch {
145    ( $( ($cmd:ident, $resp:ident, $variant:ident) ),* $(,)? ) => {
146        /// A TPM command
147        #[allow(clippy::large_enum_variant)]
148        #[derive(Debug, PartialEq, Eq, Clone)]
149        pub enum TpmCommandBody {
150            $( $variant($cmd), )*
151        }
152
153        impl TpmCommandBody {
154            #[must_use]
155            pub fn cc(&self) -> $crate::data::TpmCc {
156                match self {
157                    $( Self::$variant(c) => c.cc(), )*
158                }
159            }
160        }
161
162        /// A TPM response body
163        #[allow(clippy::large_enum_variant)]
164        #[derive(Debug, PartialEq, Eq, Clone)]
165        pub enum TpmResponseBody {
166            $( $variant($resp), )*
167        }
168
169        impl TpmResponseBody {
170            #[must_use]
171            pub fn cc(&self) -> $crate::data::TpmCc {
172                match self {
173                    $( Self::$variant(r) => r.cc(), )*
174                }
175            }
176
177            $(
178                /// Attempts to convert the `TpmResponseBody` into a specific response type.
179                ///
180                /// # Errors
181                ///
182                /// Returns the original `TpmResponseBody` as an error if the enum variant does not match.
183                #[allow(non_snake_case, clippy::result_large_err)]
184                pub fn $variant(self) -> Result<$resp, Self> {
185                    if let Self::$variant(r) = self {
186                        Ok(r)
187                    } else {
188                        Err(self)
189                    }
190                }
191            )*
192        }
193
194        pub(crate) static TPM_DISPATCH_TABLE: &[$crate::message::TpmDispatch] = &[
195            $(
196                $crate::message::TpmDispatch {
197                    cc: <$cmd as $crate::message::TpmHeader>::CC,
198                    handles: <$cmd as $crate::message::TpmHeader>::HANDLES,
199                    command_parser: |handles, params| {
200                        <$cmd as $crate::message::TpmCommandBodyParse>::parse_body(handles, params)
201                            .map(|(c, r)| (TpmCommandBody::$variant(c), r))
202                    },
203                    response_parser: |tag, buf| {
204                        <$resp as $crate::message::TpmResponseBodyParse>::parse_body(tag, buf)
205                            .map(|(r, rest)| (TpmResponseBody::$variant(r), rest))
206                    },
207                },
208            )*
209        ];
210
211        const _: () = {
212            let mut i = 1;
213            while i < TPM_DISPATCH_TABLE.len() {
214                if TPM_DISPATCH_TABLE[i - 1].cc as u32 > TPM_DISPATCH_TABLE[i].cc as u32 {
215                    panic!("TPM_DISPATCH_TABLE must be sorted by TpmCc.");
216                }
217                i += 1;
218            }
219        };
220    };
221}
222
223#[macro_export]
224macro_rules! tpm_handle {
225    (
226        $(#[$meta:meta])*
227        $name:ident
228    ) => {
229        $(#[$meta])*
230        pub struct $name(pub u32);
231
232        impl From<u32> for $name {
233            fn from(val: u32) -> Self {
234                Self(val)
235            }
236        }
237
238        impl From<$name> for u32 {
239            fn from(val: $name) -> Self {
240                val.0
241            }
242        }
243
244        impl $crate::TpmBuild for $name {
245            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
246                $crate::TpmBuild::build(&self.0, writer)
247            }
248        }
249
250        impl $crate::TpmParse for $name {
251            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
252                let (val, buf) = u32::parse(buf)?;
253                Ok((Self(val), buf))
254            }
255        }
256
257        impl $crate::TpmSized for $name {
258            const SIZE: usize = core::mem::size_of::<u32>();
259            fn len(&self) -> usize {
260                Self::SIZE
261            }
262        }
263
264        impl core::fmt::Display for $name {
265            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
266                core::fmt::Display::fmt(&self.0, f)
267            }
268        }
269
270        impl core::fmt::LowerHex for $name {
271            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
272                core::fmt::LowerHex::fmt(&self.0, f)
273            }
274        }
275
276        impl core::fmt::UpperHex for $name {
277            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
278                core::fmt::UpperHex::fmt(&self.0, f)
279            }
280        }
281    };
282}
283
284#[macro_export]
285macro_rules! tpm2b {
286    ($name:ident, $capacity:expr) => {
287        pub type $name = $crate::TpmBuffer<$capacity>;
288    };
289}
290
291#[macro_export]
292macro_rules! tpm2b_struct {
293    (
294        $(#[$meta:meta])*
295        $wrapper_ty:ident, $inner_ty:ty) => {
296        $(#[$meta])*
297        pub struct $wrapper_ty {
298            pub inner: $inner_ty,
299        }
300
301        impl $crate::TpmSized for $wrapper_ty {
302            const SIZE: usize = core::mem::size_of::<u16>() + <$inner_ty>::SIZE;
303            fn len(&self) -> usize {
304                core::mem::size_of::<u16>() + $crate::TpmSized::len(&self.inner)
305            }
306        }
307
308        impl $crate::TpmBuild for $wrapper_ty {
309            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
310                let inner_len = $crate::TpmSized::len(&self.inner);
311                u16::try_from(inner_len)
312                    .map_err(|_| $crate::TpmErrorKind::Capacity(u16::MAX.into()))?
313                    .build(writer)?;
314                $crate::TpmBuild::build(&self.inner, writer)
315            }
316        }
317
318        impl $crate::TpmParse for $wrapper_ty {
319            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
320                let (inner_bytes, rest) = $crate::parse_tpm2b(buf)?;
321                let (inner_val, tail) = <$inner_ty>::parse(inner_bytes)?;
322
323                if !tail.is_empty() {
324                    return Err($crate::TpmErrorKind::TrailingData);
325                }
326
327                Ok((Self { inner: inner_val }, rest))
328            }
329        }
330
331        impl From<$inner_ty> for $wrapper_ty {
332            fn from(inner: $inner_ty) -> Self {
333                Self { inner }
334            }
335        }
336
337        impl core::ops::Deref for $wrapper_ty {
338            type Target = $inner_ty;
339            fn deref(&self) -> &Self::Target {
340                &self.inner
341            }
342        }
343
344        impl core::ops::DerefMut for $wrapper_ty {
345            fn deref_mut(&mut self) -> &mut Self::Target {
346                &mut self.inner
347            }
348        }
349    };
350}
351
352#[macro_export]
353macro_rules! tpml {
354    ($name:ident, $inner_ty:ty, $capacity:expr) => {
355        pub type $name = $crate::TpmList<$inner_ty, $capacity>;
356    };
357}