Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions crates/optee-teec-build/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ impl PluginConfig {
)
.to_string();
let out_path = self.get_out_path();
if let Ok(v) = std::fs::read(&out_path)
&& v.eq(codes.as_bytes())
{
if std::fs::read(&out_path).is_ok_and(|v| v == codes.as_bytes()) {
return Ok(());
}

Expand All @@ -104,15 +102,10 @@ impl PluginConfig {
/// Uses the custom destination if set, otherwise defaults to
/// `$OUT_DIR/plugin_static.rs`.
fn get_out_path(&self) -> PathBuf {
match self.dest.as_ref() {
Some(v) => v.clone(),
None => {
let out_dir = PathBuf::from(
std::env::var("OUT_DIR").expect("Infallible when using in build.rs"),
);
out_dir.join("plugin_static.rs")
}
}
self.dest.clone().unwrap_or_else(|| {
PathBuf::from(std::env::var("OUT_DIR").expect("Infallible when using in build.rs"))
.join("plugin_static.rs")
})
}
}

Expand Down
6 changes: 1 addition & 5 deletions crates/optee-teec-systest/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ use std::{env, path::PathBuf};

fn main() {
let mut cfg = ctest::TestGenerator::new();
let path = {
let mut tmp = PathBuf::from(env::var("OPTEE_CLIENT_EXPORT").unwrap());
tmp.push("usr/include");
tmp
};
let path = PathBuf::from(env::var("OPTEE_CLIENT_EXPORT").unwrap()).join("usr/include");
cfg.language(ctest::Language::C)
.edition(2024)
.target("aarch64-unknown-linux-gnu")
Expand Down
21 changes: 8 additions & 13 deletions crates/optee-teec/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
// specific language governing permissions and limitations
// under the License.

use crate::{ConnectionMethods, Error, Operation, Param, ParamNone, Result, Session, Uuid, raw};
use crate::{
ConnectionMethods, Operation, Param, ParamNone, Result, Session, Uuid, raw, teec_check,
};
use std::{cell::RefCell, ptr, rc::Rc};

pub struct InnerContext(pub raw::TEEC_Context);
Expand Down Expand Up @@ -59,12 +61,10 @@ impl Context {
// SAFETY:
// raw_ctx is a C struct(TEEC_Context), which zero value is valid.
let mut raw_ctx = unsafe { std::mem::zeroed() };
match unsafe { raw::TEEC_InitializeContext(ptr::null_mut(), &mut raw_ctx) } {
raw::TEEC_SUCCESS => Ok(Self {
raw: Rc::new(RefCell::new(InnerContext(raw_ctx))),
}),
code => Err(Error::from_raw_error(code)),
}
teec_check(unsafe { raw::TEEC_InitializeContext(ptr::null_mut(), &mut raw_ctx) })?;
Ok(Self {
raw: Rc::new(RefCell::new(InnerContext(raw_ctx))),
})
}

/// Opens a new session with the specified trusted application.
Expand All @@ -87,12 +87,7 @@ impl Context {
/// }
/// ```
pub fn open_session(&mut self, uuid: Uuid) -> Result<Session> {
Session::new(
self,
uuid,
ConnectionMethods::LoginPublic,
None::<&mut Operation<ParamNone, ParamNone, ParamNone, ParamNone>>,
)
self.open_session_with_login(uuid, ConnectionMethods::LoginPublic)
}

pub fn open_session_with_login(
Expand Down
25 changes: 20 additions & 5 deletions crates/optee-teec/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,24 @@ use std::fmt;
/// ````
pub type Result<T> = std::result::Result<T, Error>;

/// Checks the result of a TEE client API call, converting a non-success code
/// into [`Error`].
pub(crate) fn teec_check(code: raw::TEEC_Result) -> Result<()> {
match code {
raw::TEEC_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code)),
}
}

/// Like [`teec_check`], but attaches the error origin returned by the TEE
/// client API on failure.
pub(crate) fn teec_check_with_origin(code: raw::TEEC_Result, origin: u32) -> Result<()> {
match code {
raw::TEEC_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code).with_origin(origin.into())),
}
}

/// The error type for TEE operations of [`Context`] and [`Session`].
///
/// [`Context`]: struct.Context.html
Expand Down Expand Up @@ -127,7 +145,7 @@ impl ErrorKind {

impl Error {
pub fn new(kind: ErrorKind) -> Error {
Error { kind, origin: None }
kind.into()
}
/// Creates a new instance of an `Error` from a particular TEE error code.
///
Expand All @@ -140,10 +158,7 @@ impl Error {
/// assert_eq!(error.kind(), ErrorKind::Security);
/// ```
pub fn from_raw_error(code: u32) -> Error {
Error {
kind: ErrorKind::from(code),
origin: None,
}
ErrorKind::from(code).into()
}

pub fn with_origin(mut self, origin: ErrorOrigin) -> Self {
Expand Down
10 changes: 3 additions & 7 deletions crates/optee-teec/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,8 @@ impl<'a, 'b> PluginParameters<'a, 'b> {
if out_len > self.buf.len() {
return Err(ErrorKind::BadParameters.into());
}
match self.out_len.as_mut() {
None => Err(ErrorKind::BadState.into()),
Some(v) => {
**v = out_len;
Ok(())
}
}
let v = self.out_len.as_mut().ok_or(ErrorKind::BadState)?;
**v = out_len;
Ok(())
}
}
1 change: 1 addition & 0 deletions crates/optee-teec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

pub use self::context::Context;
pub use self::error::{Error, ErrorKind, ErrorOrigin, Result};
pub(crate) use self::error::{teec_check, teec_check_with_origin};
pub use self::extension::*;
pub use self::operation::Operation;
pub use self::parameter::{Param, ParamNone, ParamTmpRef, ParamType, ParamTypes, ParamValue};
Expand Down
3 changes: 1 addition & 2 deletions crates/optee-teec/src/parameter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ pub struct ParamNone;

impl Param for ParamNone {
fn to_raw(&mut self) -> raw::TEEC_Parameter {
let raw: raw::TEEC_Parameter = unsafe { mem::zeroed() };
raw
unsafe { mem::zeroed() }
}

fn param_type(&self) -> ParamType {
Expand Down
64 changes: 31 additions & 33 deletions crates/optee-teec/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// under the License.

use super::context::InnerContext;
use crate::{Context, Error, Operation, Param, Result, Uuid, raw};
use crate::{Context, Operation, Param, Result, Uuid, raw, teec_check_with_origin};
use std::{cell::RefCell, ptr, rc::Rc};

/// Session login methods.
Expand Down Expand Up @@ -66,31 +66,29 @@ impl Session {
// block to maximize Rust's safety checks and leverage the compiler's
// validation.
let mut err_origin: u32 = 0;
let raw_operation = match operation {
Some(o) => o.as_mut_raw_ptr(),
None => ptr::null_mut(),
};
let raw_operation = operation.map_or(ptr::null_mut(), |o| o.as_mut_raw_ptr());
let inner_ctx = context.inner_context();
let raw_ctx = &mut inner_ctx.borrow_mut().0;
let raw_uuid = uuid.as_raw_ptr();

match unsafe {
raw::TEEC_OpenSession(
raw_ctx,
&mut raw_session,
raw_uuid,
login as u32,
ptr::null(),
raw_operation,
&mut err_origin,
)
} {
raw::TEEC_SUCCESS => Ok(Self {
raw: raw_session,
_ctx: context.inner_context(),
}),
code => Err(Error::from_raw_error(code).with_origin(err_origin.into())),
}
teec_check_with_origin(
unsafe {
raw::TEEC_OpenSession(
raw_ctx,
&mut raw_session,
raw_uuid,
login as u32,
ptr::null(),
raw_operation,
&mut err_origin,
)
},
err_origin,
)?;
Ok(Self {
raw: raw_session,
_ctx: context.inner_context(),
})
}

/// Invokes a command with an operation with this session.
Expand All @@ -100,17 +98,17 @@ impl Session {
operation: &mut Operation<A, B, C, D>,
) -> Result<()> {
let mut err_origin: u32 = 0;
match unsafe {
raw::TEEC_InvokeCommand(
&mut self.raw,
command_id,
operation.as_mut_raw_ptr(),
&mut err_origin,
)
} {
raw::TEEC_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code).with_origin(err_origin.into())),
}
teec_check_with_origin(
unsafe {
raw::TEEC_InvokeCommand(
&mut self.raw,
command_id,
operation.as_mut_raw_ptr(),
&mut err_origin,
)
},
err_origin,
)
}
}

Expand Down
9 changes: 5 additions & 4 deletions crates/optee-utee-build/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,11 @@ impl Builder {

impl Builder {
fn write_header_file(&self, out: PathBuf) -> Result<(), Error> {
let out_header_file_name = out.join(match self.header_file_name.as_ref() {
Some(v) => v.as_str(),
None => DEFAULT_HEADER_FILE_NAME,
});
let out_header_file_name = out.join(
self.header_file_name
.as_deref()
.unwrap_or(DEFAULT_HEADER_FILE_NAME),
);
let mut buffer = File::create(out_header_file_name.clone())?;
let header_codes = HeaderFileGenerator::new().generate(&self.ta_config)?;
buffer.write_all(header_codes.as_bytes())?;
Expand Down
51 changes: 16 additions & 35 deletions crates/optee-utee/src/arithmetical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.

use crate::{Error, Result};
use crate::{Result, tee_check};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::{cmp::max, fmt};
Expand Down Expand Up @@ -45,35 +45,28 @@ impl BigInt {
}

pub fn convert_from_octet_string(&mut self, buffer: &[u8], sign: i32) -> Result<()> {
match unsafe {
tee_check(unsafe {
raw::TEE_BigIntConvertFromOctetString(
self.0.as_mut_ptr(),
buffer.as_ptr(),
buffer.len(),
sign,
)
} {
raw::TEE_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code)),
}
})
}

pub fn convert_to_octet_string(&self) -> Result<Vec<u8>> {
let mut buffer_size: usize = (self.0.len() - 2) * 4;
let mut tmp_vec = vec![0u8; buffer_size];
match unsafe {
tee_check(unsafe {
raw::TEE_BigIntConvertToOctetString(
tmp_vec.as_mut_ptr(),
&mut buffer_size,
self.data_ptr(),
)
} {
raw::TEE_SUCCESS => {
tmp_vec.truncate(buffer_size);
Ok(tmp_vec)
}
code => Err(Error::from_raw_error(code)),
}
})?;
tmp_vec.truncate(buffer_size);
Ok(tmp_vec)
}

pub fn convert_from_s32(&mut self, short_val: i32) {
Expand All @@ -82,10 +75,8 @@ impl BigInt {

pub fn convert_to_s32(&self) -> Result<i32> {
let mut short_val: i32 = 0;
match unsafe { raw::TEE_BigIntConvertToS32(&mut short_val as _, self.data_ptr()) } {
raw::TEE_SUCCESS => Ok(short_val),
code => Err(Error::from_raw_error(code)),
}
tee_check(unsafe { raw::TEE_BigIntConvertToS32(&mut short_val as _, self.data_ptr()) })?;
Ok(short_val)
}

/* return negative number if self < target,
Expand Down Expand Up @@ -114,19 +105,14 @@ impl BigInt {
}

pub fn set_bit(&mut self, bit_index: u32, set: bool) -> Result<()> {
match unsafe { raw::TEE_BigIntSetBit(self.0.as_mut_ptr(), bit_index, set) } {
raw::TEE_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code)),
}
tee_check(unsafe { raw::TEE_BigIntSetBit(self.0.as_mut_ptr(), bit_index, set) })
}

pub fn abs(&self) -> Result<Self> {
let bits = Self::get_bit_count(self);
let mut res = Self::new(bits);
match unsafe { raw::TEE_BigIntAbs(res.0.as_mut_ptr(), self.data_ptr()) } {
raw::TEE_SUCCESS => Ok(res),
code => Err(Error::from_raw_error(code)),
}
tee_check(unsafe { raw::TEE_BigIntAbs(res.0.as_mut_ptr(), self.data_ptr()) })?;
Ok(res)
}

pub fn add(op1: &Self, op2: &Self) -> Self {
Expand Down Expand Up @@ -238,29 +224,24 @@ impl BigInt {

pub fn exp_mod(op1: &Self, op2: &Self, n: &Self, context: &BigIntFMMContext) -> Result<Self> {
let mut res = Self::new(Self::get_bit_count(n));
match unsafe {
tee_check(unsafe {
raw::TEE_BigIntExpMod(
res.0.as_mut_ptr(),
op1.data_ptr(),
op2.data_ptr(),
n.data_ptr(),
context.data_ptr(),
)
} {
raw::TEE_SUCCESS => Ok(res),
code => Err(Error::from_raw_error(code)),
}
})?;
Ok(res)
}

pub fn relative_prime(op1: &Self, op2: &Self) -> bool {
unsafe { raw::TEE_BigIntRelativePrime(op1.data_ptr(), op2.data_ptr()) }
}

pub fn assign(&mut self, op2: &Self) -> Result<()> {
match unsafe { raw::TEE_BigIntAssign(self.0.as_mut_ptr(), op2.data_ptr()) } {
raw::TEE_SUCCESS => Ok(()),
code => Err(Error::from_raw_error(code)),
}
tee_check(unsafe { raw::TEE_BigIntAssign(self.0.as_mut_ptr(), op2.data_ptr()) })
}

pub fn compute_extended_gcd(op1: &Self, op2: &Self) -> (Self, Self, Self) {
Expand Down
Loading
Loading