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    (@const_check_sorted) => {};
146    (@const_check_sorted $prev_cmd:ty, $( $rest_cmd:ty, )*) => {
147        $crate::tpm_dispatch!(@const_check_sorted_impl $prev_cmd, $( $rest_cmd, )*);
148    };
149    (@const_check_sorted_impl $prev_cmd:ty,) => {};
150    (@const_check_sorted_impl $prev_cmd:ty, $current_cmd:ty, $( $rest_cmd:ty, )* ) => {
151        const _: () = assert!(
152            <$prev_cmd as $crate::message::TpmHeader>::CC as u32 <= <$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($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(TpmErrorKind)` 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($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<$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(TpmErrorKind)` 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: <$cmd as $crate::message::TpmHeader>::CC,
261                    handles: <$cmd as $crate::message::TpmHeader>::HANDLES,
262                    command_parser: |handles, params| {
263                        <$cmd as $crate::message::TpmCommandBodyParse>::parse_body(handles, params)
264                            .map(|(c, r)| (TpmCommandBody::$variant(c), r))
265                    },
266                    response_parser: |tag, buf| {
267                        <$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! tpm_handle {
280    (
281        $(#[$meta:meta])*
282        $name:ident
283    ) => {
284        $(#[$meta])*
285        pub struct $name(pub u32);
286
287        impl From<u32> for $name {
288            fn from(val: u32) -> Self {
289                Self(val)
290            }
291        }
292
293        impl From<$name> for u32 {
294            fn from(val: $name) -> Self {
295                val.0
296            }
297        }
298
299        impl $crate::TpmBuild for $name {
300            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
301                $crate::TpmBuild::build(&self.0, writer)
302            }
303        }
304
305        impl $crate::TpmParse for $name {
306            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
307                let (val, buf) = u32::parse(buf)?;
308                Ok((Self(val), buf))
309            }
310        }
311
312        impl $crate::TpmSized for $name {
313            const SIZE: usize = core::mem::size_of::<u32>();
314            fn len(&self) -> usize {
315                Self::SIZE
316            }
317        }
318
319        impl core::fmt::Display for $name {
320            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
321                core::fmt::Display::fmt(&self.0, f)
322            }
323        }
324
325        impl core::fmt::LowerHex for $name {
326            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
327                core::fmt::LowerHex::fmt(&self.0, f)
328            }
329        }
330
331        impl core::fmt::UpperHex for $name {
332            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
333                core::fmt::UpperHex::fmt(&self.0, f)
334            }
335        }
336    };
337}
338
339#[macro_export]
340macro_rules! tpm2b {
341    ($name:ident, $capacity:expr) => {
342        pub type $name = $crate::TpmBuffer<$capacity>;
343    };
344}
345
346#[macro_export]
347macro_rules! tpm2b_struct {
348    (
349        $(#[$meta:meta])*
350        $wrapper_ty:ident, $inner_ty:ty) => {
351        $(#[$meta])*
352        pub struct $wrapper_ty {
353            pub inner: $inner_ty,
354        }
355
356        impl $crate::TpmSized for $wrapper_ty {
357            const SIZE: usize = core::mem::size_of::<u16>() + <$inner_ty>::SIZE;
358            fn len(&self) -> usize {
359                core::mem::size_of::<u16>() + $crate::TpmSized::len(&self.inner)
360            }
361        }
362
363        impl $crate::TpmBuild for $wrapper_ty {
364            fn build(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
365                let inner_len = $crate::TpmSized::len(&self.inner);
366                u16::try_from(inner_len)
367                    .map_err(|_| $crate::TpmErrorKind::Capacity(u16::MAX.into()))?
368                    .build(writer)?;
369                $crate::TpmBuild::build(&self.inner, writer)
370            }
371        }
372
373        impl $crate::TpmParse for $wrapper_ty {
374            fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
375                let (inner_bytes, rest) = $crate::parse_tpm2b(buf)?;
376                let (inner_val, tail) = <$inner_ty>::parse(inner_bytes)?;
377
378                if !tail.is_empty() {
379                    return Err($crate::TpmErrorKind::TrailingData);
380                }
381
382                Ok((Self { inner: inner_val }, rest))
383            }
384        }
385
386        impl From<$inner_ty> for $wrapper_ty {
387            fn from(inner: $inner_ty) -> Self {
388                Self { inner }
389            }
390        }
391
392        impl core::ops::Deref for $wrapper_ty {
393            type Target = $inner_ty;
394            fn deref(&self) -> &Self::Target {
395                &self.inner
396            }
397        }
398
399        impl core::ops::DerefMut for $wrapper_ty {
400            fn deref_mut(&mut self) -> &mut Self::Target {
401                &mut self.inner
402            }
403        }
404    };
405}
406
407#[macro_export]
408macro_rules! tpml {
409    ($name:ident, $inner_ty:ty, $capacity:expr) => {
410        pub type $name = $crate::TpmList<$inner_ty, $capacity>;
411    };
412}