1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::{Error, ErrorKind, Result, Uuid};
#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned, vec::Vec};
use optee_utee_sys as raw;
pub struct LoadablePlugin {
uuid: Uuid,
}
pub struct LoadablePluginCommand<'a> {
plugin: &'a LoadablePlugin,
cmd_id: u32,
sub_cmd_id: u32,
buffer: Vec<u8>,
}
impl LoadablePlugin {
pub fn new(uuid: &Uuid) -> Self {
Self {
uuid: uuid.to_owned(),
}
}
/// Invoke plugin with given request data, use when you want to post something into REE.
/// ``` rust,no_run
/// # use optee_utee::{LoadablePlugin, Uuid};
/// # fn main() -> optee_utee::Result<()> {
/// # let uuid = Uuid::parse_str("").unwrap();
/// # let command_id = 0;
/// # let subcommand_id = 0;
/// # let request_data = [0_u8; 0];
/// let plugin = LoadablePlugin::new(&uuid);
/// let result = plugin.invoke(command_id, subcommand_id, &request_data)?;
/// # Ok(())
/// # }
/// ```
/// Caution: the size of the shared buffer is set to the len of data, you could get a
/// ShortBuffer error if Plugin return more data than shared buffer, in that case,
/// use invoke_with_capacity and set the capacity manually.
pub fn invoke(&self, command_id: u32, subcommand_id: u32, data: &[u8]) -> Result<Vec<u8>> {
self.invoke_with_capacity(command_id, subcommand_id, data.len())
.chain_write_body(data)
.call()
}
/// Construct a command with shared buffer up to capacity size, write the buffer and call it
/// manually, use when you need to control details of the invoking process.
/// ```no_run
/// # use optee_utee::{Uuid, LoadablePlugin};
/// # fn main() -> optee_utee::Result<()> {
/// # let plugin = LoadablePlugin::new(&Uuid::parse_str("").unwrap());
/// # let request_data = [0_u8; 0];
/// # let command_id = 0;
/// # let sub_command_id = 0;
/// # let capacity = 0;
/// let mut cmd = plugin.invoke_with_capacity(command_id, sub_command_id, capacity);
/// cmd.write_body(&request_data);
/// let result = cmd.call()?;
/// # Ok(())
/// # }
/// ```
/// You can also imply a wrapper for performance, for example, imply a std::io::Write so
/// serde_json can write to the buffer directly.
/// ```no_run
/// # use optee_utee::{LoadablePluginCommand, Uuid, LoadablePlugin, trace_println};
/// # use optee_utee::ErrorKind;
/// # fn main() -> optee_utee::Result<()> {
/// # let command_id = 0;
/// # let subcommand_id = 0;
/// # let capacity = 0;
/// # let plugin = LoadablePlugin::new(&Uuid::parse_str("").unwrap());
/// struct Wrapper<'a, 'b>(&'b mut LoadablePluginCommand<'a>);
/// impl<'a, 'b> std::io::Write for Wrapper<'a, 'b> {
/// fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
/// self.0.write_body(buf);
/// Ok(buf.len())
/// }
/// fn flush(&mut self) -> std::io::Result<()> {
/// Ok(())
/// }
/// }
/// // serialize data into command directly
/// let request_data = serde_json::json!({
/// "age": 100,
/// "name": "name"
/// });
/// let mut cmd = plugin.invoke_with_capacity(command_id, subcommand_id, capacity);
/// serde_json::to_writer(Wrapper(&mut cmd), &request_data).map_err(|err| {
/// trace_println!("serde error: {:?}", err);
/// ErrorKind::Unknown
/// })?;
/// let result = cmd.call()?;
///
/// # Ok(())
/// # }
/// ```
/// Notice: the shared buffer could grow to fit the request data automatically.
pub fn invoke_with_capacity(
&self,
command_id: u32,
subcommand_id: u32,
capacity: usize,
) -> LoadablePluginCommand<'_> {
LoadablePluginCommand::new_with_capacity(self, command_id, subcommand_id, capacity)
}
}
impl<'a> LoadablePluginCommand<'a> {
// use this to write request body if needed
pub fn write_body(&mut self, data: &[u8]) {
self.buffer.extend_from_slice(data);
}
// same with write_body, but chainable
pub fn chain_write_body(mut self, data: &[u8]) -> Self {
self.write_body(data);
self
}
// invoke the command, and get result from it
pub fn call(self) -> Result<Vec<u8>> {
let mut outlen: usize = 0;
let mut buffer = self.buffer;
buffer.resize(buffer.capacity(), 0); // resize to capacity first
match unsafe {
raw::tee_invoke_supp_plugin(
self.plugin.uuid.as_raw_ptr(),
self.cmd_id,
self.sub_cmd_id,
// convert the pointer manually, as in some platform c_char is i8
buffer.as_mut_slice().as_mut_ptr() as *mut _,
buffer.len(),
&mut outlen as *mut usize,
)
} {
raw::TEE_SUCCESS => {
if outlen > buffer.len() {
return Err(ErrorKind::ShortBuffer.into());
}
buffer.resize(outlen, 0);
Ok(buffer)
}
code => Err(Error::from_raw_error(code)),
}
}
}
impl<'a> LoadablePluginCommand<'a> {
fn new_with_capacity(
plugin: &'a LoadablePlugin,
cmd_id: u32,
sub_cmd_id: u32,
capacity: usize,
) -> Self {
Self {
plugin,
cmd_id,
sub_cmd_id,
buffer: Vec::with_capacity(capacity),
}
}
}
#[cfg(test)]
pub mod test_loadable_plugin {
extern crate std;
use super::*;
use alloc::string::ToString;
use optee_utee_sys::{mock_api, mock_utils::SERIAL_TEST_LOCK};
use rand::distributions::Alphanumeric;
use rand::Rng;
fn generate_random_bytes(len: usize) -> Vec<u8> {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect()
}
fn generate_test_pairs(
request_size: usize,
response_size: usize,
) -> (u32, u32, Vec<u8>, Vec<u8>) {
let cmd: u32 = rand::random();
let sub_cmd: u32 = rand::random();
let random_request: Vec<u8> = generate_random_bytes(request_size);
let random_response: Vec<u8> = generate_random_bytes(response_size);
(cmd, sub_cmd, random_request, random_response)
}
fn random_uuid() -> Uuid {
Uuid::new_raw(
rand::random(),
rand::random(),
rand::random(),
rand::random(),
)
}
fn expect_success_request(
ctx: &mock_api::extension::__tee_invoke_supp_plugin::Context,
exp_uuid: &Uuid,
exp_cmd: u32,
exp_sub_cmd: u32,
exp_request: &[u8],
exp_response: &[u8],
) {
let exp_request = exp_request.to_vec();
let exp_response = exp_response.to_vec();
let exp_uuid = exp_uuid.to_string();
ctx.expect()
.return_once_st(move |uuid, cmd, sub_cmd, buf, len, outlen| {
let request_uuid = Uuid::from(unsafe { *uuid }).to_string();
debug_assert_eq!(exp_uuid, request_uuid);
debug_assert_eq!(cmd, exp_cmd);
debug_assert_eq!(sub_cmd, exp_sub_cmd);
debug_assert_eq!(
unsafe { core::slice::from_raw_parts(buf as *mut u8, exp_request.len()) },
exp_request.as_slice()
);
debug_assert!(len >= exp_response.len());
let buffer: &mut [u8] =
unsafe { core::slice::from_raw_parts_mut(buf as *mut u8, len) };
buffer[0..exp_response.len()].copy_from_slice(&exp_response);
unsafe { *outlen = exp_response.len() };
raw::TEE_SUCCESS
});
}
#[test]
fn test_invoke() {
let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
let uuid: Uuid = random_uuid();
let plugin = LoadablePlugin::new(&uuid);
const REQUEST_LEN: usize = 32;
let run_test = |request_size: usize, response_size: usize| {
let (cmd, sub_cmd, request, exp_response) =
generate_test_pairs(request_size, response_size);
let fn1 = mock_api::extension::tee_invoke_supp_plugin_context();
expect_success_request(&fn1, &uuid, cmd, sub_cmd, &request, &exp_response);
let response = plugin.invoke(cmd, sub_cmd, &request).expect("should be ok");
std::println!("*TA*: response is {:?}", response);
debug_assert_eq!(response, exp_response);
};
// test calling with output size less than input
run_test(REQUEST_LEN, REQUEST_LEN / 2);
// test calling with output size equals to input
run_test(REQUEST_LEN, REQUEST_LEN);
// test calling with output size greater than input.
// Mark: Without explicitly setting the response size, this function
// must not be called with a response size larger than the request size.
{
let (cmd, sub_cmd, request, exp_response) =
generate_test_pairs(REQUEST_LEN, 2 * REQUEST_LEN);
let fn1 = mock_api::extension::tee_invoke_supp_plugin_context();
fn1.expect().return_once_st(move |_, _, _, _, _, outlen| {
unsafe { *outlen = exp_response.len() };
raw::TEE_SUCCESS
});
let err = plugin
.invoke(cmd, sub_cmd, &request)
.expect_err("should be err");
debug_assert_eq!(err.kind(), ErrorKind::ShortBuffer);
}
}
// This test is equivalent to test_invoke, with the added verification that
// capacity permits the response size to be larger than the request.
#[test]
fn test_invoke_with_capacity() {
let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
let uuid: Uuid = random_uuid();
let plugin = LoadablePlugin::new(&uuid);
const RESPONSE_LEN: usize = 32;
let run_test = |request_size: usize, response_size: usize| {
let (cmd, sub_cmd, request, exp_response) =
generate_test_pairs(request_size, response_size);
let fn1 = mock_api::extension::tee_invoke_supp_plugin_context();
expect_success_request(&fn1, &uuid, cmd, sub_cmd, &request, &exp_response);
let response = plugin
.invoke_with_capacity(cmd, sub_cmd, exp_response.len())
.chain_write_body(&request)
.call()
.unwrap();
std::println!("*TA*: response is {:?}", response);
debug_assert_eq!(response, exp_response);
};
// test calling with output size less than input
run_test(2 * RESPONSE_LEN, RESPONSE_LEN);
// test calling with output size equals to input
run_test(RESPONSE_LEN, RESPONSE_LEN);
// test calling with output size greater than input
run_test(RESPONSE_LEN / 2, RESPONSE_LEN);
}
#[test]
fn test_invoke_with_writer() {
let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
let uuid: Uuid = random_uuid();
let plugin = LoadablePlugin::new(&uuid);
let fn1 = mock_api::extension::tee_invoke_supp_plugin_context();
// impl a writer for Command
struct Wrapper<'a, 'b>(&'b mut LoadablePluginCommand<'a>);
impl<'a, 'b> std::io::Write for Wrapper<'a, 'b> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write_body(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
// serialize data into command directly
let test_data = serde_json::json!({
"code": 100,
"message": "error"
});
let mut exp_request = serde_json::to_vec(&test_data).unwrap();
let buffer_len = exp_request.len() * 2;
let (cmd, sub_cmd, _, exp_response) = generate_test_pairs(0, buffer_len);
let mut plugin_cmd = plugin.invoke_with_capacity(cmd, sub_cmd, buffer_len);
exp_request.resize(exp_response.len(), 0);
expect_success_request(&fn1, &uuid, cmd, sub_cmd, &exp_request, &exp_response);
serde_json::to_writer(Wrapper(&mut plugin_cmd), &test_data).unwrap();
let response = plugin_cmd.call().unwrap();
std::println!("*TA*: response is {:?}", response);
debug_assert_eq!(response, exp_response);
}
#[test]
fn test_invoke_with_no_data() {
let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
let uuid: Uuid = random_uuid();
let plugin = LoadablePlugin::new(&uuid);
let fn1 = mock_api::extension::tee_invoke_supp_plugin_context();
const OUTPUT_LEN: usize = 50;
let (cmd, sub_cmd, request, exp_response) = generate_test_pairs(0, OUTPUT_LEN);
expect_success_request(&fn1, &uuid, cmd, sub_cmd, &request, &exp_response);
let response = plugin
.invoke_with_capacity(cmd, sub_cmd, OUTPUT_LEN)
.call()
.unwrap();
std::println!("*TA*: response is {:?}", response);
debug_assert_eq!(response, exp_response);
}
}