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
50        impl core::ops::BitOr for $name {
51            type Output = Self;
52            fn bitor(self, rhs: Self) -> Self::Output {
53                Self(self.0 | rhs.0)
54            }
55        }
56
57        impl core::ops::BitOrAssign for $name {
58            fn bitor_assign(&mut self, rhs: Self) {
59                self.0 |= rhs.0;
60            }
61        }
62
63        impl core::ops::BitAnd for $name {
64            type Output = Self;
65            fn bitand(self, rhs: Self) -> Self::Output {
66                Self(self.0 & rhs.0)
67            }
68        }
69
70        impl core::ops::BitAndAssign for $name {
71            fn bitand_assign(&mut self, rhs: Self) {
72                self.0 &= rhs.0;
73            }
74        }
75
76        impl core::ops::BitXor for $name {
77            type Output = Self;
78            fn bitxor(self, rhs: Self) -> Self::Output {
79                Self(self.0 ^ rhs.0)
80            }
81        }
82
83        impl core::ops::BitXorAssign for $name {
84            fn bitxor_assign(&mut self, rhs: Self) {
85                self.0 ^= rhs.0;
86            }
87        }
88
89        impl core::ops::Not for $name {
90            type Output = Self;
91            fn not(self) -> Self::Output {
92                Self(!self.0)
93            }
94        }
95
96        impl $crate::TpmMarshal for $name {
97            fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
98                $crate::TpmMarshal::marshal(&self.0, writer)
99            }
100        }
101
102        impl $crate::TpmUnmarshal for $name {
103            fn unmarshal(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
104                let (val, buf) = <$repr>::unmarshal(buf)?;
105                Ok((Self(val), buf))
106            }
107        }
108
109        impl $crate::TpmSized for $name {
110            const SIZE: usize = core::mem::size_of::<$repr>();
111            fn len(&self) -> usize {
112                Self::SIZE
113            }
114        }
115    };
116}
117
118#[macro_export]
119macro_rules! tpm_bool {
120    (
121        $(#[$outer:meta])*
122        $vis:vis struct $name:ident(bool);
123    ) => {
124        $(#[$outer])*
125        $vis struct $name(pub bool);
126
127        impl From<bool> for $name {
128            fn from(val: bool) -> Self {
129                Self(val)
130            }
131        }
132
133        impl From<$name> for bool {
134            fn from(val: $name) -> Self {
135                val.0
136            }
137        }
138
139        impl $crate::TpmMarshal for $name {
140            fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
141                $crate::TpmMarshal::marshal(&u8::from(self.0), writer)
142            }
143        }
144
145        impl $crate::TpmUnmarshal for $name {
146            fn unmarshal(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
147                let (val, buf) = u8::unmarshal(buf)?;
148                match val {
149                    0 => Ok((Self(false), buf)),
150                    1 => Ok((Self(true), buf)),
151                    _ => Err($crate::TpmProtocolError::InvalidBoolean),
152                }
153            }
154        }
155
156        impl $crate::TpmSized for $name {
157            const SIZE: usize = core::mem::size_of::<u8>();
158            fn len(&self) -> usize {
159                Self::SIZE
160            }
161        }
162    };
163}
164
165#[macro_export]
166macro_rules! tpm_dispatch {
167    (@const_check_sorted) => {};
168    (@const_check_sorted $prev_cmd:ident, $( $rest_cmd:ident, )*) => {
169        $crate::tpm_dispatch!(@const_check_sorted_impl $prev_cmd, $( $rest_cmd, )*);
170    };
171    (@const_check_sorted_impl $prev_cmd:ident,) => {};
172    (@const_check_sorted_impl $prev_cmd:ident, $current_cmd:ident, $( $rest_cmd:ident, )* ) => {
173        const _: () = assert!(
174            <$crate::frame::data::$prev_cmd as $crate::frame::TpmHeader>::CC as u32 <= <$crate::frame::data::$current_cmd as $crate::frame::TpmHeader>::CC as u32,
175            "TPM_DISPATCH_TABLE must be sorted by TpmCc."
176        );
177        $crate::tpm_dispatch!(@const_check_sorted_impl $current_cmd, $( $rest_cmd, )*);
178    };
179
180    ( $( ($cmd:ident, $resp:ident, $variant:ident) ),* $(,)? ) => {
181        /// A TPM command
182        #[allow(clippy::large_enum_variant)]
183        #[derive(Debug, PartialEq, Eq, Clone)]
184        pub enum TpmCommand {
185            $( $variant($crate::frame::data::$cmd), )*
186        }
187
188        impl $crate::TpmSized for TpmCommand {
189            const SIZE: usize = $crate::constant::TPM_MAX_COMMAND_SIZE as usize;
190            fn len(&self) -> usize {
191                match self {
192                    $( Self::$variant(c) => $crate::TpmSized::len(c), )*
193                }
194            }
195        }
196
197        impl $crate::frame::TpmMarshalBody for TpmCommand {
198             fn marshal_handles(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
199                 match self {
200                     $( Self::$variant(c) => $crate::frame::TpmMarshalBody::marshal_handles(c, writer), )*
201                 }
202             }
203             fn marshal_parameters(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
204                 match self {
205                     $( Self::$variant(c) => $crate::frame::TpmMarshalBody::marshal_parameters(c, writer), )*
206                 }
207             }
208        }
209
210        impl $crate::TpmMarshal for TpmCommand {
211             fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
212                 match self {
213                     $( Self::$variant(c) => $crate::TpmMarshal::marshal(c, writer), )*
214                 }
215             }
216        }
217
218        impl $crate::frame::TpmFrame for TpmCommand {
219            fn cc(&self) -> $crate::data::TpmCc {
220                match self {
221                    $( Self::$variant(c) => $crate::frame::TpmFrame::cc(c), )*
222                }
223            }
224            fn handles(&self) -> usize {
225                match self {
226                    $( Self::$variant(c) => $crate::frame::TpmFrame::handles(c), )*
227                }
228            }
229        }
230
231        impl TpmCommand {
232            /// Marshals a command body into a writer.
233            ///
234            /// # Errors
235            ///
236            /// Returns `Err(TpmProtocolError)` on a marshal failure.
237            pub fn marshal_frame(
238                &self,
239                tag: $crate::data::TpmSt,
240                sessions: &$crate::frame::TpmAuthCommands,
241                writer: &mut $crate::TpmWriter,
242            ) -> $crate::TpmResult<()> {
243                match self {
244                    $( Self::$variant(c) => $crate::frame::tpm_marshal_command(c, tag, sessions, writer), )*
245                }
246            }
247        }
248
249        /// A TPM response body
250        #[allow(clippy::large_enum_variant)]
251        #[derive(Debug, PartialEq, Eq, Clone)]
252        pub enum TpmResponse {
253            $( $variant($crate::frame::data::$resp), )*
254        }
255
256        impl $crate::TpmSized for TpmResponse {
257            const SIZE: usize = $crate::constant::TPM_MAX_COMMAND_SIZE as usize;
258            fn len(&self) -> usize {
259                match self {
260                    $( Self::$variant(r) => $crate::TpmSized::len(r), )*
261                }
262            }
263        }
264
265        impl $crate::frame::TpmMarshalBody for TpmResponse {
266             fn marshal_handles(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
267                 match self {
268                     $( Self::$variant(r) => $crate::frame::TpmMarshalBody::marshal_handles(r, writer), )*
269                 }
270             }
271             fn marshal_parameters(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
272                 match self {
273                     $( Self::$variant(r) => $crate::frame::TpmMarshalBody::marshal_parameters(r, writer), )*
274                 }
275             }
276        }
277
278        impl $crate::TpmMarshal for TpmResponse {
279             fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
280                 match self {
281                     $( Self::$variant(r) => $crate::TpmMarshal::marshal(r, writer), )*
282                 }
283             }
284        }
285
286        impl $crate::frame::TpmFrame for TpmResponse {
287            fn cc(&self) -> $crate::data::TpmCc {
288                match self {
289                    $( Self::$variant(r) => $crate::frame::TpmFrame::cc(r), )*
290                }
291            }
292            fn handles(&self) -> usize {
293                match self {
294                    $( Self::$variant(r) => $crate::frame::TpmFrame::handles(r), )*
295                }
296            }
297        }
298
299        impl TpmResponse {
300            $(
301                /// Attempts to convert the `TpmResponse` into a specific response type.
302                ///
303                /// # Errors
304                ///
305                /// Returns the original `TpmResponse` as an error if the enum variant does not match.
306                #[allow(non_snake_case, clippy::result_large_err)]
307                pub fn $variant(self) -> Result<$crate::frame::data::$resp, Self> {
308                    if let Self::$variant(r) = self {
309                        Ok(r)
310                    } else {
311                        Err(self)
312                    }
313                }
314            )*
315
316            /// Marshals a response body into a writer.
317            ///
318            /// # Errors
319            ///
320            /// Returns `Err(TpmProtocolError)` on a marshal failure.
321            pub fn marshal_frame(
322                &self,
323                rc: $crate::data::TpmRc,
324                sessions: &$crate::frame::TpmAuthResponses,
325                writer: &mut $crate::TpmWriter,
326            ) -> $crate::TpmResult<()> {
327                match self {
328                    $( Self::$variant(r) => $crate::frame::tpm_marshal_response(r, sessions, rc, writer), )*
329                }
330            }
331        }
332
333        pub(crate) static TPM_DISPATCH_TABLE: &[$crate::frame::TpmDispatch] = &[
334            $(
335                $crate::frame::TpmDispatch {
336                    cc: <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC,
337                    handles: <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::HANDLES,
338                    command_unmarshaler: |handles, params| {
339                        <$crate::frame::data::$cmd as $crate::frame::TpmUnmarshalCommand>::unmarshal_body(handles, params)
340                            .map(|(c, r)| (TpmCommand::$variant(c), r))
341                    },
342                    response_unmarshaler: |tag, buf| {
343                        <$crate::frame::data::$resp as $crate::frame::TpmUnmarshalResponse>::unmarshal_body(tag, buf)
344                            .map(|(r, rest)| (TpmResponse::$variant(r), rest))
345                    },
346                },
347            )*
348        ];
349
350        $crate::tpm_dispatch!(@const_check_sorted $( $cmd, )*);
351    };
352}
353
354#[macro_export]
355macro_rules! tpm2b {
356    ($name:ident, $capacity:expr) => {
357        pub type $name = $crate::basic::TpmBuffer<$capacity>;
358    };
359}
360
361#[macro_export]
362macro_rules! tpm2b_struct {
363    (
364        $(#[$meta:meta])*
365        $wrapper_ty:ident, $inner_ty:ty) => {
366        $(#[$meta])*
367        pub struct $wrapper_ty {
368            pub inner: $inner_ty,
369        }
370
371        impl $crate::TpmSized for $wrapper_ty {
372            const SIZE: usize = core::mem::size_of::<u16>() + <$inner_ty>::SIZE;
373            fn len(&self) -> usize {
374                core::mem::size_of::<u16>() + $crate::TpmSized::len(&self.inner)
375            }
376        }
377
378        impl $crate::TpmMarshal for $wrapper_ty
379        where
380            $inner_ty: $crate::TpmSized,
381        {
382            fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
383                let inner_len = $crate::TpmSized::len(&self.inner);
384                u16::try_from(inner_len)
385                    .map_err(|_| $crate::TpmProtocolError::IntegerTooLarge)?
386                    .marshal(writer)?;
387                $crate::TpmMarshal::marshal(&self.inner, writer)
388            }
389        }
390
391        impl $crate::TpmUnmarshal for $wrapper_ty {
392            fn unmarshal(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
393                let (size, buf_after_size) = u16::unmarshal(buf)?;
394                let size = size as usize;
395
396                if buf_after_size.len() < size {
397                    return Err($crate::TpmProtocolError::UnexpectedEnd);
398                }
399                let (inner_bytes, rest) = buf_after_size.split_at(size);
400
401                let (inner_val, tail) = <$inner_ty>::unmarshal(inner_bytes)?;
402
403                if !tail.is_empty() {
404                    return Err($crate::TpmProtocolError::TrailingData);
405                }
406
407                Ok((Self { inner: inner_val }, rest))
408            }
409        }
410
411        impl From<$inner_ty> for $wrapper_ty {
412            fn from(inner: $inner_ty) -> Self {
413                Self { inner }
414            }
415        }
416
417        impl core::ops::Deref for $wrapper_ty {
418            type Target = $inner_ty;
419            fn deref(&self) -> &Self::Target {
420                &self.inner
421            }
422        }
423
424        impl core::ops::DerefMut for $wrapper_ty {
425            fn deref_mut(&mut self) -> &mut Self::Target {
426                &mut self.inner
427            }
428        }
429    };
430}
431
432#[macro_export]
433macro_rules! tpml {
434    ($name:ident, $inner_ty:ty, $capacity:expr) => {
435        pub type $name = $crate::basic::TpmList<$inner_ty, $capacity>;
436    };
437}