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