Skip to main content

optee_utee/object/
object_handle.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 optee_utee_sys as raw;
19
20use super::GenericObject;
21
22/// An opaque handle on an object.
23#[derive(Debug)]
24pub struct ObjectHandle(raw::TEE_ObjectHandle);
25
26impl ObjectHandle {
27    pub fn from_raw(raw: raw::TEE_ObjectHandle) -> crate::Result<ObjectHandle> {
28        if raw.is_null() {
29            return Err(crate::ErrorKind::BadParameters.into());
30        }
31        Ok(Self(raw))
32    }
33
34    /// Forget the inner handle to prevent a double-free, this function would be
35    /// called when the inner handle is(or will be) freed externally.
36    ///
37    /// Example:
38    /// ``` rust,no_run
39    /// # use optee_utee::ObjectHandle;
40    /// # use optee_utee_sys as raw;
41    /// # fn main() -> optee_utee::Result<()> {
42    /// # let external_handle = core::ptr::null_mut();
43    /// // `external_handle` is a handle that is constructed and controlled
44    /// // externally.
45    /// // `handle` is valid, and will call TEE_CloseObject on
46    /// // `external_handle` when it is dropping, which is not allowed
47    /// // as the `external_handle` is externally controlled.
48    /// let mut handle = ObjectHandle::from_raw(external_handle)?;
49    /// // ... Some operation
50    /// // forget the inner handle, so it won't call TEE_CloseObject on
51    /// // `external_handle`
52    /// handle.forget();
53    /// # Ok(())
54    /// # }
55    /// ```
56    pub fn forget(mut self) {
57        self.0 = core::ptr::null_mut();
58    }
59}
60
61// functions for internal usage
62impl ObjectHandle {
63    pub(crate) fn new_null() -> Self {
64        Self(core::ptr::null_mut())
65    }
66
67    pub(crate) fn is_null(&self) -> bool {
68        self.0.is_null()
69    }
70}
71
72impl Drop for ObjectHandle {
73    fn drop(&mut self) {
74        if !self.is_null() {
75            unsafe { raw::TEE_CloseObject(self.0) }
76        }
77    }
78}
79
80impl GenericObject for ObjectHandle {
81    unsafe fn as_raw_ref(&self) -> &raw::TEE_ObjectHandle {
82        &self.0
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    extern crate std;
89
90    use optee_utee_sys::{
91        mock_api,
92        mock_utils::{SERIAL_TEST_LOCK, object::MockHandle},
93    };
94
95    use super::*;
96
97    /// Ensures `ObjectHandle` can be safely constructed from a raw handle
98    /// and automatically calls `TEE_CloseObject` when dropped.
99    #[test]
100    fn test_from_raw() {
101        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
102
103        let mut raw_handle = MockHandle::new();
104        let handle = raw_handle.as_handle();
105        let fn1 = mock_api::TEE_CloseObject_context();
106
107        fn1.expect().return_once_st(move |obj| {
108            debug_assert_eq!(obj, handle.clone());
109        });
110
111        let obj = ObjectHandle::from_raw(handle.clone()).expect("it should be ok");
112        assert_eq!(unsafe { *obj.as_raw_ref() }, handle);
113    }
114
115    /// Ensures `ObjectHandle` can call `forget` to prevent automatically
116    /// calls `TEE_CloseObject` when dropped.
117    #[test]
118    fn test_forget() {
119        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
120
121        let mut raw_handle = MockHandle::new();
122        let handle = raw_handle.as_handle();
123
124        let obj = ObjectHandle::from_raw(handle.clone()).expect("it should be ok");
125        assert_eq!(unsafe { *obj.as_raw_ref() }, handle);
126
127        obj.forget();
128    }
129
130    #[test]
131    fn test_new_null() {
132        let obj = ObjectHandle::new_null();
133        assert!(obj.is_null());
134    }
135}