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        macro_rules! tpm_command_parser {
147            ($value:ty, $name:ident) => {
148                (
149                    <$value as $crate::message::TpmHeader>::COMMAND,
150                    <$value as $crate::message::TpmHeader>::NO_SESSIONS,
151                    <$value as $crate::message::TpmHeader>::WITH_SESSIONS,
152                    <$value as $crate::message::TpmHeader>::HANDLES,
153                    |buf| <$value>::parse(buf).map(|(c, r)| (TpmCommandBody::$name(c), r)),
154                )
155            };
156        }
157
158        macro_rules! tpm_response_parser {
159            ($rsp_ty:ty, $enum_variant:ident) => {
160                (
161                    <$rsp_ty as $crate::message::TpmHeader>::COMMAND,
162                    <$rsp_ty as $crate::message::TpmHeader>::WITH_SESSIONS,
163                    |buf| {
164                        <$rsp_ty>::parse(buf)
165                            .map(|(r, rest)| (TpmResponseBody::$enum_variant(r), rest))
166                    },
167                )
168            };
169        }
170
171        /// A TPM command
172        #[derive(Debug, PartialEq, Eq, Clone)]
173        pub enum TpmCommandBody {
174            $( $variant($cmd), )*
175        }
176
177        /// A TPM response body
178        #[allow(clippy::large_enum_variant)]
179        #[derive(Debug, PartialEq, Eq, Clone)]
180        pub enum TpmResponseBody {
181            $( $variant($resp), )*
182        }
183
184        impl TpmResponseBody {
185            $(
186                /// Attempts to convert the `TpmResponseBody` into a specific response type.
187                ///
188                /// # Errors
189                ///
190                /// Returns the original `TpmResponseBody` as an error if the enum variant does not match.
191                #[allow(non_snake_case, clippy::result_large_err)]
192                pub fn $variant(self) -> Result<$resp, Self> {
193                    if let Self::$variant(r) = self {
194                        Ok(r)
195                    } else {
196                        Err(self)
197                    }
198                }
199            )*
200        }
201
202        pub type TpmCommandParser = for<'a> fn(&'a [u8]) -> $crate::TpmResult<(TpmCommandBody, &'a [u8])>;
203        pub type TpmResponseParser = for<'a> fn(&'a [u8]) -> $crate::TpmResult<(TpmResponseBody, &'a [u8])>;
204
205        pub(crate) static PARSE_COMMAND_MAP: &[($crate::data::TpmCc, bool, bool, usize, TpmCommandParser)] =
206            &[$(tpm_command_parser!($cmd, $variant),)*];
207
208        pub(crate) static PARSE_RESPONSE_MAP: &[($crate::data::TpmCc, bool, TpmResponseParser)] =
209            &[$(tpm_response_parser!($resp, $variant),)*];
210
211        const _: () = {
212            let mut i = 1;
213            while i < PARSE_COMMAND_MAP.len() {
214                if PARSE_COMMAND_MAP[i - 1].0 as u32 > PARSE_COMMAND_MAP[i].0 as u32 {
215                    panic!("PARSE_COMMAND_MAP must be sorted by TpmCc.");
216                }
217                i += 1;
218            }
219        };
220
221        const _: () = {
222            let mut i = 1;
223            while i < PARSE_RESPONSE_MAP.len() {
224                if PARSE_RESPONSE_MAP[i - 1].0 as u32 > PARSE_RESPONSE_MAP[i].0 as u32 {
225                    panic!("PARSE_RESPONSE_MAP must be sorted by TpmCc.");
226                }
227                i += 1;
228            }
229        };
230    };
231}
232
233#[macro_export]
234macro_rules! tpm_handle {
235    (
236        $(#[$meta:meta])*
237        $name:ident
238    ) => {
239        $(#[$meta])*
240        pub struct $name(pub u32);
241
242        impl From<u32> for $name {
243            fn from(val: u32) -> Self {
244                Self(val)
245            }
246        }
247
248        impl From<$name> for u32 {
249            fn from(val: $name) -> Self {
250                val.0
251            }
252        }
253
254        impl $crate::TpmBuild for $name {
255            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
256                $crate::TpmBuild::build(&self.0, writer)
257            }
258        }
259
260        impl $crate::TpmParse for $name {
261            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
262                let (val, buf) = u32::parse(buf)?;
263                Ok((Self(val), buf))
264            }
265        }
266
267        impl $crate::TpmSized for $name {
268            const SIZE: usize = core::mem::size_of::<u32>();
269            fn len(&self) -> usize {
270                Self::SIZE
271            }
272        }
273
274        impl core::fmt::Display for $name {
275            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
276                core::fmt::Display::fmt(&self.0, f)
277            }
278        }
279
280        impl core::fmt::LowerHex for $name {
281            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
282                core::fmt::LowerHex::fmt(&self.0, f)
283            }
284        }
285
286        impl core::fmt::UpperHex for $name {
287            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
288                core::fmt::UpperHex::fmt(&self.0, f)
289            }
290        }
291    };
292}
293
294#[macro_export]
295macro_rules! tpm2b {
296    ($name:ident, $capacity:expr) => {
297        pub type $name = $crate::TpmBuffer<$capacity>;
298    };
299}
300
301#[macro_export]
302macro_rules! tpm2b_struct {
303    (
304        $(#[$meta:meta])*
305        $wrapper_ty:ident, $inner_ty:ty) => {
306        $(#[$meta])*
307        pub struct $wrapper_ty {
308            pub inner: $inner_ty,
309        }
310
311        impl $crate::TpmSized for $wrapper_ty {
312            const SIZE: usize = core::mem::size_of::<u16>() + <$inner_ty>::SIZE;
313            fn len(&self) -> usize {
314                core::mem::size_of::<u16>() + $crate::TpmSized::len(&self.inner)
315            }
316        }
317
318        impl $crate::TpmBuild for $wrapper_ty {
319            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
320                let inner_len = $crate::TpmSized::len(&self.inner);
321                u16::try_from(inner_len)
322                    .map_err(|_| $crate::TpmErrorKind::ValueTooLarge)?
323                    .build(writer)?;
324                $crate::TpmBuild::build(&self.inner, writer)
325            }
326        }
327
328        impl $crate::TpmParse for $wrapper_ty {
329            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
330                let (inner_bytes, rest) = $crate::parse_tpm2b(buf)?;
331                let (inner_val, tail) = <$inner_ty>::parse(inner_bytes)?;
332
333                if !tail.is_empty() {
334                    return Err($crate::TpmErrorKind::TrailingData);
335                }
336
337                Ok((Self { inner: inner_val }, rest))
338            }
339        }
340
341        impl From<$inner_ty> for $wrapper_ty {
342            fn from(inner: $inner_ty) -> Self {
343                Self { inner }
344            }
345        }
346
347        impl core::ops::Deref for $wrapper_ty {
348            type Target = $inner_ty;
349            fn deref(&self) -> &Self::Target {
350                &self.inner
351            }
352        }
353
354        impl core::ops::DerefMut for $wrapper_ty {
355            fn deref_mut(&mut self) -> &mut Self::Target {
356                &mut self.inner
357            }
358        }
359    };
360}
361
362#[macro_export]
363macro_rules! tpml {
364    ($name:ident, $inner_ty:ty, $capacity:expr) => {
365        pub type $name = $crate::TpmList<$inner_ty, $capacity>;
366    };
367}