Skip to main content

optee_utee/
extension.rs

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