tpm: save almost 8KB stack space

The largest possible PTM response is only 16 bytes. Size the output
buffer correctly.

In the socket read function, rely on the caller to provide a
sufficiently large buffer. That eliminates another large stack variable.

In total this saves almost 8KB stack space.

Signed-off-by: Wei Liu <liuwe@microsoft.com>
This commit is contained in:
Wei Liu 2023-01-30 22:01:42 +00:00 committed by Rob Bradford
parent 8e996ff2fe
commit 6e22f23831
2 changed files with 11 additions and 11 deletions

View File

@ -216,7 +216,16 @@ impl Emulator {
))
})?;
let mut output = [0_u8; TPM_CRB_BUFFER_MAX];
// The largest response is 16 bytes so far.
if msg_len_out > 16 {
return Err(Error::RunControlCmd(anyhow!(
"Response size is too large for Cmd {:02X?}, max 16 wanted {}",
cmd,
msg_len_out
)));
}
let mut output = [0u8; 16];
// Every Control Cmd gets atleast a result code in response. Read it
let read_size = self.control_socket.read(&mut output).map_err(|e| {

View File

@ -3,7 +3,6 @@
// SPDX-License-Identifier: Apache-2.0
//
use crate::TPM_CRB_BUFFER_MAX;
use anyhow::anyhow;
use std::io::Read;
use std::os::unix::io::{AsRawFd, RawFd};
@ -122,23 +121,15 @@ impl SocketDev {
}
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let newbuf: &mut [u8] = &mut [0; TPM_CRB_BUFFER_MAX];
if self.stream.is_none() {
return Err(Error::ReadFromSocket(anyhow!(
"Stream for tpm socket was not initialized"
)));
}
let mut socket = self.stream.as_ref().unwrap();
let size: usize = socket.read(newbuf).map_err(|e| {
let size: usize = socket.read(buf).map_err(|e| {
Error::ReadFromSocket(anyhow!("Failed to read from socket. Error Code {:?}", e))
})?;
if buf.len() < size {
return Err(Error::ReadFromSocket(anyhow!(
"Input buffer is of insufficient size"
)));
}
buf[0..size].clone_from_slice(&newbuf[0..size]);
Ok(size)
}
}