Skip to content

Commit 2dfc315

Browse files
authored
Merge pull request #471 from Superhepper/size_t-handling
Improves handling of ```size_t``` FFI values.
2 parents aa68349 + 041d204 commit 2dfc315

File tree

17 files changed

+238
-798
lines changed

17 files changed

+238
-798
lines changed

tss-esapi/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ picky-asn1-x509 = { version = "0.12.0", optional = true }
3232
cfg-if = "1.0.0"
3333
strum = { version = "0.25.0", optional = true }
3434
strum_macros = { version = "0.25.0", optional = true }
35+
paste = "1.0.14"
3536

3637
[dev-dependencies]
3738
env_logger = "0.9.0"

tss-esapi/src/constants/command_code.rs

+3-59
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,11 @@
22
// SPDX-License-Identifier: Apache-2.0
33
mod structure;
44

5-
use crate::{
6-
traits::{Marshall, UnMarshall},
7-
tss2_esys::TPM2_CC,
8-
Error, Result, ReturnCode, WrapperErrorKind,
9-
};
5+
use crate::{traits::impl_mu_simple, tss2_esys::TPM2_CC, Error, Result, WrapperErrorKind};
106
use log::error;
117
use num_derive::{FromPrimitive, ToPrimitive};
128
use num_traits::{FromPrimitive, ToPrimitive};
13-
use std::convert::{TryFrom, TryInto};
9+
use std::convert::TryFrom;
1410
use structure::CommandCodeStructure;
1511

1612
/// Enum representing the command code constants.
@@ -155,56 +151,4 @@ impl From<CommandCode> for TPM2_CC {
155151
}
156152
}
157153

158-
impl Marshall for CommandCode {
159-
const BUFFER_SIZE: usize = std::mem::size_of::<TPM2_CC>();
160-
161-
fn marshall_offset(
162-
&self,
163-
marshalled_data: &mut [u8],
164-
offset: &mut std::os::raw::c_ulong,
165-
) -> Result<()> {
166-
ReturnCode::ensure_success(
167-
unsafe {
168-
crate::tss2_esys::Tss2_MU_TPM2_CC_Marshal(
169-
(*self).into(),
170-
marshalled_data.as_mut_ptr(),
171-
marshalled_data.len().try_into().map_err(|e| {
172-
error!("Failed to convert size of buffer to TSS size_t type: {}", e);
173-
Error::local_error(WrapperErrorKind::InvalidParam)
174-
})?,
175-
offset,
176-
)
177-
},
178-
|ret| {
179-
error!("Failed to marshal CommandCode: {}", ret);
180-
},
181-
)?;
182-
Ok(())
183-
}
184-
}
185-
186-
impl UnMarshall for CommandCode {
187-
fn unmarshall_offset(
188-
marshalled_data: &[u8],
189-
offset: &mut std::os::raw::c_ulong,
190-
) -> Result<Self> {
191-
let mut dest = TPM2_CC::default();
192-
193-
ReturnCode::ensure_success(
194-
unsafe {
195-
crate::tss2_esys::Tss2_MU_TPM2_CC_Unmarshal(
196-
marshalled_data.as_ptr(),
197-
marshalled_data.len().try_into().map_err(|e| {
198-
error!("Failed to convert length of marshalled data: {}", e);
199-
Error::local_error(WrapperErrorKind::InvalidParam)
200-
})?,
201-
offset,
202-
&mut dest,
203-
)
204-
},
205-
|ret| error!("Failed to unmarshal SensitiveCreate: {}", ret),
206-
)?;
207-
208-
CommandCode::try_from(dest)
209-
}
210-
}
154+
impl_mu_simple!(CommandCode, TPM2_CC);

tss-esapi/src/ffi.rs

+59-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
// Copyright 2022 Contributors to the Parsec project.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
pub(crate) mod data_zeroize;
4+
pub mod data_zeroize;
55

6-
use crate::ffi::data_zeroize::FfiDataZeroize;
6+
use crate::{ffi::data_zeroize::FfiDataZeroize, Error, Result, WrapperErrorKind};
7+
use log::error;
78
use mbox::MBox;
8-
use std::ops::Deref;
9+
use std::{convert::TryFrom, ops::Deref};
910

1011
/// Function that takes ownership of data that has been
1112
/// allocated with C memory allocation functions in TSS while also
@@ -26,7 +27,61 @@ where
2627
owned_ffi_data
2728
}
2829

29-
pub(crate) fn to_owned_bytes(ffi_bytes_ptr: *mut u8, size: usize) -> Vec<u8> {
30+
/// Function that takes ownership of bytes that are stored in a
31+
/// buffer that has been allocated with C memory allocation functions in TSS.
32+
///
33+
/// # Arguments
34+
/// * `ffi_bytes_ptr` - A pointer to the FFI buffer.
35+
/// * `size` - The number of bytes to read from the buffer.
36+
///
37+
/// # Returns
38+
/// The owned bytes in the form of a `Vec<u8>` object.
39+
pub fn to_owned_bytes(ffi_bytes_ptr: *mut u8, size: usize) -> Vec<u8> {
3040
let ffi_bytes = unsafe { MBox::<[u8]>::from_raw_parts(ffi_bytes_ptr, size) };
3141
return Vec::<u8>::from(ffi_bytes.as_ref());
3242
}
43+
44+
/// Type used for handling `size_t` variables
45+
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46+
pub struct FfiSizeType(crate::tss2_esys::size_t);
47+
48+
impl FfiSizeType {
49+
/// Returns an unsafe mutable pointer to the `size_t` value.
50+
pub(crate) fn as_mut_ptr(&mut self) -> *mut crate::tss2_esys::size_t {
51+
&mut self.0
52+
}
53+
}
54+
55+
impl From<crate::tss2_esys::size_t> for FfiSizeType {
56+
fn from(value: crate::tss2_esys::size_t) -> Self {
57+
Self(value)
58+
}
59+
}
60+
61+
impl From<FfiSizeType> for crate::tss2_esys::size_t {
62+
fn from(ffi: FfiSizeType) -> crate::tss2_esys::size_t {
63+
ffi.0
64+
}
65+
}
66+
67+
impl TryFrom<usize> for FfiSizeType {
68+
type Error = Error;
69+
fn try_from(native: usize) -> Result<Self> {
70+
crate::tss2_esys::size_t::try_from(native)
71+
.map(FfiSizeType)
72+
.map_err(|err| {
73+
error!("Failed to convert `usize` to `size_t`: {}", err);
74+
Error::local_error(WrapperErrorKind::UnsupportedParam)
75+
})
76+
}
77+
}
78+
79+
impl TryFrom<FfiSizeType> for usize {
80+
type Error = Error;
81+
fn try_from(ffi: FfiSizeType) -> Result<usize> {
82+
usize::try_from(ffi.0).map_err(|err| {
83+
error!("Failed to convert `size_t` to `usize`: {}", err);
84+
Error::local_error(WrapperErrorKind::UnsupportedParam)
85+
})
86+
}
87+
}
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,13 @@
11
// Copyright 2021 Contributors to the Parsec project.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
use log::error;
54
use tss_esapi_sys::TPMI_ST_COMMAND_TAG;
65

76
use crate::{
8-
constants::StructureTag,
9-
traits::{Marshall, UnMarshall},
10-
tss2_esys::TPMI_ST_ATTEST,
11-
Error, Result, ReturnCode, WrapperErrorKind,
7+
constants::StructureTag, traits::impl_mu_simple, tss2_esys::TPMI_ST_ATTEST, Error, Result,
8+
WrapperErrorKind,
129
};
13-
use std::convert::{TryFrom, TryInto};
10+
use std::convert::TryFrom;
1411

1512
/// Type of attestation.
1613
///
@@ -75,60 +72,7 @@ impl TryFrom<TPMI_ST_ATTEST> for AttestationType {
7572
}
7673
}
7774

78-
impl Marshall for AttestationType {
79-
const BUFFER_SIZE: usize = std::mem::size_of::<TPMI_ST_ATTEST>();
80-
81-
fn marshall_offset(
82-
&self,
83-
marshalled_data: &mut [u8],
84-
offset: &mut std::os::raw::c_ulong,
85-
) -> Result<()> {
86-
ReturnCode::ensure_success(
87-
unsafe {
88-
crate::tss2_esys::Tss2_MU_TPM2_ST_Marshal(
89-
(*self).into(),
90-
marshalled_data.as_mut_ptr(),
91-
marshalled_data.len().try_into().map_err(|e| {
92-
error!("Failed to convert size of buffer to TSS size_t type: {}", e);
93-
Error::local_error(WrapperErrorKind::InvalidParam)
94-
})?,
95-
offset,
96-
)
97-
},
98-
|ret| {
99-
error!("Failed to marshal AttestationType: {}", ret);
100-
},
101-
)?;
102-
103-
Ok(())
104-
}
105-
}
106-
107-
impl UnMarshall for AttestationType {
108-
fn unmarshall_offset(
109-
marshalled_data: &[u8],
110-
offset: &mut std::os::raw::c_ulong,
111-
) -> Result<Self> {
112-
let mut dest = TPMI_ST_ATTEST::default();
113-
114-
ReturnCode::ensure_success(
115-
unsafe {
116-
crate::tss2_esys::Tss2_MU_TPM2_ST_Unmarshal(
117-
marshalled_data.as_ptr(),
118-
marshalled_data.len().try_into().map_err(|e| {
119-
error!("Failed to convert length of marshalled data: {}", e);
120-
Error::local_error(WrapperErrorKind::InvalidParam)
121-
})?,
122-
offset,
123-
&mut dest,
124-
)
125-
},
126-
|ret| error!("Failed to unmarshal AttestationType: {}", ret),
127-
)?;
128-
129-
AttestationType::try_from(dest)
130-
}
131-
}
75+
impl_mu_simple!(AttestationType, TPMI_ST_ATTEST, TPM2_ST);
13276

13377
/// Type of command tag.
13478
///
@@ -175,57 +119,4 @@ impl TryFrom<TPMI_ST_COMMAND_TAG> for CommandTag {
175119
}
176120
}
177121

178-
impl Marshall for CommandTag {
179-
const BUFFER_SIZE: usize = std::mem::size_of::<TPMI_ST_COMMAND_TAG>();
180-
181-
fn marshall_offset(
182-
&self,
183-
marshalled_data: &mut [u8],
184-
offset: &mut std::os::raw::c_ulong,
185-
) -> Result<()> {
186-
ReturnCode::ensure_success(
187-
unsafe {
188-
crate::tss2_esys::Tss2_MU_TPM2_ST_Marshal(
189-
(*self).into(),
190-
marshalled_data.as_mut_ptr(),
191-
marshalled_data.len().try_into().map_err(|e| {
192-
error!("Failed to convert size of buffer to TSS size_t type: {}", e);
193-
Error::local_error(WrapperErrorKind::InvalidParam)
194-
})?,
195-
offset,
196-
)
197-
},
198-
|ret| {
199-
error!("Failed to marshal CommandTag: {}", ret);
200-
},
201-
)?;
202-
203-
Ok(())
204-
}
205-
}
206-
207-
impl UnMarshall for CommandTag {
208-
fn unmarshall_offset(
209-
marshalled_data: &[u8],
210-
offset: &mut std::os::raw::c_ulong,
211-
) -> Result<Self> {
212-
let mut dest = TPMI_ST_COMMAND_TAG::default();
213-
214-
ReturnCode::ensure_success(
215-
unsafe {
216-
crate::tss2_esys::Tss2_MU_TPM2_ST_Unmarshal(
217-
marshalled_data.as_ptr(),
218-
marshalled_data.len().try_into().map_err(|e| {
219-
error!("Failed to convert length of marshalled data: {}", e);
220-
Error::local_error(WrapperErrorKind::InvalidParam)
221-
})?,
222-
offset,
223-
&mut dest,
224-
)
225-
},
226-
|ret| error!("Failed to unmarshal CommandTag: {}", ret),
227-
)?;
228-
229-
CommandTag::try_from(dest)
230-
}
231-
}
122+
impl_mu_simple!(CommandTag, TPMI_ST_COMMAND_TAG, TPM2_ST);

tss-esapi/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
missing_copy_implementations,
3030
rustdoc::broken_intra_doc_links,
3131
)]
32+
3233
//! # TSS 2.0 Rust Wrapper over Enhanced System API
3334
//! This crate exposes the functionality of the TCG Software Stack Enhanced System API to
3435
//! Rust developers, both directly through FFI bindings and through more Rust-tailored interfaces

tss-esapi/src/macros/mod.rs

-2
This file was deleted.

tss-esapi/src/structures/algorithm/symmetric/sensitive_create.rs

+3-65
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33
use crate::{
44
structures::{Auth, SensitiveData},
5-
traits::{Marshall, UnMarshall},
5+
traits::{impl_mu_standard, Marshall},
66
tss2_esys::{TPM2B_SENSITIVE_CREATE, TPMS_SENSITIVE_CREATE},
77
Error, Result, ReturnCode, WrapperErrorKind,
88
};
@@ -62,70 +62,8 @@ impl TryFrom<TPMS_SENSITIVE_CREATE> for SensitiveCreate {
6262
}
6363
}
6464

65-
impl Marshall for SensitiveCreate {
66-
const BUFFER_SIZE: usize = std::mem::size_of::<TPMS_SENSITIVE_CREATE>();
67-
68-
/// Produce a marshalled [TPMS_SENSITIVE_CREATE]
69-
///
70-
/// Note: for [TPM2B_SENSITIVE_CREATE] marshalling use [SensitiveCreateBuffer][`crate::structures::SensitiveCreateBuffer]
71-
fn marshall(&self) -> Result<Vec<u8>> {
72-
let mut buffer = vec![0; Self::BUFFER_SIZE];
73-
let mut offset = 0;
74-
75-
ReturnCode::ensure_success(
76-
unsafe {
77-
crate::tss2_esys::Tss2_MU_TPMS_SENSITIVE_CREATE_Marshal(
78-
&self.clone().into(),
79-
buffer.as_mut_ptr(),
80-
Self::BUFFER_SIZE.try_into().map_err(|e| {
81-
error!("Failed to convert size of buffer to TSS size_t type: {}", e);
82-
Error::local_error(WrapperErrorKind::InvalidParam)
83-
})?,
84-
&mut offset,
85-
)
86-
},
87-
|ret| {
88-
error!("Failed to marshal SensitiveCreate: {}", ret);
89-
},
90-
)?;
91-
92-
let checked_offset = usize::try_from(offset).map_err(|e| {
93-
error!("Failed to parse offset as usize: {}", e);
94-
Error::local_error(WrapperErrorKind::InvalidParam)
95-
})?;
96-
97-
buffer.truncate(checked_offset);
98-
99-
Ok(buffer)
100-
}
101-
}
102-
103-
impl UnMarshall for SensitiveCreate {
104-
/// Unmarshall the structure from [`TPMS_SENSITIVE_CREATE`]
105-
///
106-
/// Note: for [TPM2B_SENSITIVE_CREATE] unmarshalling use [SensitiveCreateBuffer][`crate::structures::SensitiveCreateBuffer]
107-
fn unmarshall(marshalled_data: &[u8]) -> Result<Self> {
108-
let mut dest = TPMS_SENSITIVE_CREATE::default();
109-
let mut offset = 0;
110-
111-
ReturnCode::ensure_success(
112-
unsafe {
113-
crate::tss2_esys::Tss2_MU_TPMS_SENSITIVE_CREATE_Unmarshal(
114-
marshalled_data.as_ptr(),
115-
marshalled_data.len().try_into().map_err(|e| {
116-
error!("Failed to convert length of marshalled data: {}", e);
117-
Error::local_error(WrapperErrorKind::InvalidParam)
118-
})?,
119-
&mut offset,
120-
&mut dest,
121-
)
122-
},
123-
|ret| error!("Failed to unmarshal SensitiveCreate: {}", ret),
124-
)?;
125-
126-
SensitiveCreate::try_from(dest)
127-
}
128-
}
65+
// Implement marshalling traits.
66+
impl_mu_standard!(SensitiveCreate, TPMS_SENSITIVE_CREATE);
12967

13068
impl TryFrom<TPM2B_SENSITIVE_CREATE> for SensitiveCreate {
13169
type Error = Error;

0 commit comments

Comments
 (0)