Skip to main content

optee_utee/object/
persistent_object.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 alloc::vec::Vec;
19use optee_utee_sys as raw;
20
21use super::{DataFlag, GenericObject, ObjectHandle, ObjectStorageConstants, Whence};
22use crate::{ErrorKind, Result, tee_check};
23
24/// An object identified by an Object Identifier and including a Data Stream.
25///
26/// Contrast [TransientObject](crate::TransientObject).
27#[derive(Debug)]
28pub struct PersistentObject(ObjectHandle);
29
30impl PersistentObject {
31    /// Open an existing persistent object.
32    ///
33    /// # Parameters
34    ///
35    /// 1) `storage_id`: The storage to use which is defined in
36    ///    [ObjectStorageConstants](crate::ObjectStorageConstants).
37    /// 2) `object_id`: The object identifier. Note that this buffer cannot
38    ///    reside in shared memory.
39    /// 3) `flags`: The [DataFlag](crate::DataFlag) which determine the settings
40    ///    under which the object is opened.
41    ///
42    /// # Example
43    ///
44    /// ``` rust,no_run
45    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
46    /// # fn main() -> optee_utee::Result<()> {
47    /// let obj_id = [1u8;1];
48    /// match PersistentObject::open(
49    ///         ObjectStorageConstants::Private,
50    ///         &obj_id,
51    ///         DataFlag::ACCESS_READ) {
52    ///     Ok(object) =>
53    ///     {
54    ///         // ...
55    ///         Ok(())
56    ///     }
57    ///     Err(e) => Err(e),
58    /// }
59    /// # }
60    /// ```
61    ///
62    /// # Errors
63    ///
64    /// 1) `ItemNotFound`: If the storage denoted by storage_id does not exist
65    ///    or if the object identifier cannot be found in the storage.
66    /// 2) `Access_Conflict`: If an access right conflict was detected while
67    ///    opening the object.
68    /// 3) `OutOfMemory`: If there is not enough memory to complete the
69    ///    operation.
70    /// 4) `CorruptObject`: If the object is corrupt. The object handle SHALL
71    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
72    ///    property.
73    /// 5) `StorageNotAvailable`: If the object is stored in a storage area
74    ///    which is currently inaccessible.
75    ///
76    /// # Panics
77    ///
78    /// 1) If object_id.len() >
79    ///    [MiscellaneousConstants::TeeObjectIdMaxLen](crate::MiscellaneousConstants::TeeObjectIdMaxLen)
80    /// 2) If the Implementation detects any other error associated with this
81    ///    function which is not explicitly associated with a defined return
82    ///    code for this function.
83    pub fn open(
84        storage_id: ObjectStorageConstants,
85        object_id: &[u8],
86        flags: DataFlag,
87    ) -> Result<Self> {
88        let mut handle: raw::TEE_ObjectHandle = core::ptr::null_mut();
89        // Move as much code as possible out of unsafe blocks to maximize Rust’s
90        // safety checks.
91        let handle_mut = &mut handle;
92        tee_check(unsafe {
93            raw::TEE_OpenPersistentObject(
94                storage_id as u32,
95                object_id.as_ptr() as _,
96                object_id.len(),
97                flags.bits(),
98                handle_mut,
99            )
100        })?;
101        Ok(Self(ObjectHandle::from_raw(handle)?))
102    }
103
104    /// Create an object with initial attributes and an initial data stream
105    /// content.
106    ///
107    /// # Parameters
108    ///
109    /// 1) `storage_id`: The storage to use which is defined in
110    ///    [ObjectStorageConstants](crate::ObjectStorageConstants).
111    /// 2) `object_id`: The object identifier. Note that this buffer cannot
112    ///    reside in shared memory.
113    /// 3) `flags`: The [DataFlag](crate::DataFlag) which determine the settings
114    ///    under which the object is opened.
115    /// 4) `attributes`: A handle on a
116    ///    [PersistentObject](crate::PersistentObject) or an initialized
117    ///    [TransientObject](crate::TransientObject) from which to take the
118    ///    [PersistentObject](crate::PersistentObject) attributes.
119    ///    Can be NONE if the [PersistentObject](crate::PersistentObject)
120    ///    contains no attribute. For example,if it is a pure data object.
121    ///
122    /// # Example
123    ///
124    /// ``` rust,no_run
125    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
126    /// # fn main() -> optee_utee::Result<()> {
127    /// let obj_id = [1u8;1];
128    /// let mut init_data: [u8; 0] = [0; 0];
129    /// match PersistentObject::create(
130    ///         ObjectStorageConstants::Private,
131    ///         &obj_id,
132    ///         DataFlag::ACCESS_READ | DataFlag::ACCESS_WRITE,
133    ///         None,
134    ///         &mut init_data) {
135    ///     Ok(object) =>
136    ///     {
137    ///         // ...
138    ///         Ok(())
139    ///     }
140    ///     Err(e) => Err(e),
141    /// }
142    /// # }
143    /// ```
144    ///
145    /// # Errors
146    ///
147    /// 1) `ItemNotFound`: If the storage denoted by storage_id does not exist.
148    /// 2) `Access_Conflict`: If an access right conflict was detected while
149    ///    opening the object.
150    /// 3) `OutOfMemory`: If there is not enough memory to complete the
151    ///    operation.
152    /// 4) `StorageNoSpace`: If insufficient space is available to create the
153    ///    persistent object.
154    /// 5) `CorruptObject`: If the storage is corrupt.
155    /// 6) `StorageNotAvailable`: If the object is stored in a storage area
156    ///    which is currently inaccessible.
157    ///
158    /// # Panics
159    ///
160    /// 1) If object_id.len() >
161    ///    [MiscellaneousConstants::TeeObjectIdMaxLen](crate::MiscellaneousConstants::TeeObjectIdMaxLen).
162    /// 2) If attributes is not NONE and is not a valid handle on an initialized
163    ///    object containing the type and attributes of the object to create.
164    /// 3) If the Implementation detects any other error associated with this
165    ///    function which is not explicitly associated with a defined return
166    ///    code for this function.
167    pub fn create(
168        storage_id: ObjectStorageConstants,
169        object_id: &[u8],
170        flags: DataFlag,
171        attributes: Option<ObjectHandle>,
172        initial_data: &[u8],
173    ) -> Result<Self> {
174        let mut handle: raw::TEE_ObjectHandle = core::ptr::null_mut();
175        // Move as much code as possible out of unsafe blocks to maximize Rust’s
176        // safety checks.
177        let handle_mut = &mut handle;
178        let attributes = match attributes.as_ref() {
179            Some(a) => unsafe { *a.as_raw_ref() },
180            None => core::ptr::null_mut(),
181        };
182        tee_check(unsafe {
183            raw::TEE_CreatePersistentObject(
184                storage_id as u32,
185                object_id.as_ptr() as _,
186                object_id.len(),
187                flags.bits(),
188                attributes,
189                initial_data.as_ptr() as _,
190                initial_data.len(),
191                handle_mut,
192            )
193        })?;
194        Ok(Self(ObjectHandle::from_raw(handle)?))
195    }
196
197    /// Marks an object for deletion and closes the object.
198    ///
199    /// # Example
200    ///
201    /// ``` rust,no_run
202    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
203    /// # fn main() -> optee_utee::Result<()> {
204    /// let obj_id = [1u8;1];
205    /// match PersistentObject::open (
206    ///         ObjectStorageConstants::Private,
207    ///         &obj_id,
208    ///         DataFlag::ACCESS_READ) {
209    ///     Ok(mut object) =>
210    ///     {
211    ///         object.close_and_delete()?;
212    ///         Ok(())
213    ///     }
214    ///     Err(e) => Err(e),
215    /// }
216    /// # }
217    /// ```
218    ///
219    /// # Errors
220    ///
221    /// 1) `StorageNotAvailable`: If the object is stored in a storage area
222    ///    which is currently inaccessible.
223    ///
224    /// # Panics
225    ///
226    /// 1) If object is not a valid opened object.
227    /// 2) If the Implementation detects any other error associated with this
228    ///    function which is not explicitly associated with a defined return
229    ///    code for this function.
230    ///
231    /// # Breaking Changes
232    ///
233    /// Now we no longer need to call `core::mem::forget` after successfully calling
234    /// `close_and_delete`, and code like this will now produce a compilation error.
235    /// ``` rust,compile_fail
236    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
237    /// # fn main() -> optee_utee::Result<()> {
238    /// # let obj_id = [0_u8];
239    /// let mut obj = PersistentObject::open (
240    ///         ObjectStorageConstants::Private,
241    ///         &obj_id,
242    ///         DataFlag::ACCESS_READ,
243    /// )?;
244    /// obj.close_and_delete()?;
245    /// core::mem::forget(obj); // will get compilation error in this line
246    /// //                ^^^ value used here after move
247    /// # Ok(())
248    /// # }
249    pub fn close_and_delete(self) -> Result<()> {
250        let result =
251            tee_check(unsafe { raw::TEE_CloseAndDeletePersistentObject1(*self.as_raw_ref()) });
252        // According to `GPD_TEE_Internal_Core_API_Specification_v1.3.1`:
253        // At 5.7.4 TEE_CloseAndDeletePersistentObject1:
254        // Deleting an object is atomic; once this function returns, the object
255        // is definitely deleted and no more open handles for the object exist.
256        //
257        // So we must forget the raw_handle to prevent calling TEE_CloseObject
258        // on it (no matter the result of TEE_CloseAndDeletePersistentObject1).
259        self.0.forget();
260        result
261    }
262
263    /// Changes the identifier of an object.
264    /// The object SHALL have been opened with the
265    /// [DataFlag::ACCESS_WRITE_META](crate::DataFlag::ACCESS_WRITE_META) right,
266    /// which means access to the object is exclusive.
267    ///
268    /// # Example
269    ///
270    /// ``` rust,no_run
271    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
272    /// # fn main() -> optee_utee::Result<()> {
273    /// let obj_id = [1u8;1];
274    /// let new_obj_id = [2u8;1];
275    /// match PersistentObject::open (
276    ///         ObjectStorageConstants::Private,
277    ///         &obj_id,
278    ///         DataFlag::ACCESS_WRITE_META) {
279    ///     Ok(mut object) =>
280    ///     {
281    ///         object.rename(&new_obj_id)?;
282    ///         Ok(())
283    ///     }
284    ///     Err(e) => Err(e),
285    /// }
286    /// # }
287    /// ```
288    ///
289    /// # Errors
290    ///
291    /// 1) `AccessConflict`: If an object with the same identifier already
292    ///    exists.
293    /// 2) `CorruptObject`: If the object is corrupt. The object handle SHALL
294    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
295    ///    property.
296    /// 3) `StorageNotAvailable`: If the object is stored in a storage area
297    ///    which is currently inaccessible.
298    ///
299    /// # Panics
300    ///
301    /// 1) If object is not a valid handle on a persistent object that has been
302    ///    opened with the write-meta access right.
303    /// 2) If new_object_id resides in shared memory.
304    /// 3) If new_object_id.len() >
305    ///    [MiscellaneousConstants::TeeObjectIdMaxLen](crate::MiscellaneousConstants::TeeObjectIdMaxLen).
306    /// 4) If the Implementation detects any other error associated with this
307    ///    function which is not explicitly associated with a defined return
308    ///    code for this function.
309    pub fn rename(&mut self, new_object_id: &[u8]) -> Result<()> {
310        tee_check(unsafe {
311            raw::TEE_RenamePersistentObject(
312                *self.0.as_raw_ref(),
313                new_object_id.as_ptr() as _,
314                new_object_id.len(),
315            )
316        })
317    }
318
319    /// Read requested size from the data stream associate with the object into
320    /// the buffer.
321    ///
322    /// # Parameters
323    ///
324    /// 1) `buffer`: A pre-allocated TA-private buffer for saving the object's
325    ///    data stream. Client-shared memory must not be passed here; use
326    ///    [`Self::read_remaining_to_vec`] and copy the result to the client instead.
327    /// 2) `count`: The returned value contains the number of bytes read.
328    /// # Example
329    ///
330    /// ``` rust,no_run
331    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
332    /// # fn main() -> optee_utee::Result<()> {
333    /// let obj_id = [1u8;1];
334    /// match PersistentObject::open (
335    ///         ObjectStorageConstants::Private,
336    ///         &obj_id,
337    ///         DataFlag::ACCESS_READ) {
338    ///     Ok(mut object) =>
339    ///     {
340    ///         let mut read_buf = [0u8;16];
341    ///         object.read(&mut read_buf)?;
342    ///         Ok(())
343    ///     }
344    ///     Err(e) => Err(e),
345    /// }
346    /// # }
347    /// ```
348    ///
349    /// # Errors
350    ///
351    /// 1) `CorruptObject`: If the object is corrupt. The object handle SHALL
352    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
353    ///    property.
354    /// 2) `StorageNotAvailable`: If the object is stored in a storage area
355    ///    which is currently inaccessible.
356    ///
357    /// # Panics
358    ///
359    /// 1) If object is not a valid handle on a persistent object opened with
360    ///    the read access right.
361    /// 2) If the Implementation detects any other error associated with this
362    ///    function which is not explicitly associated with a defined return
363    ///    code for this function.
364    pub fn read(&mut self, buf: &mut [u8]) -> Result<u32> {
365        let mut count: usize = 0;
366        tee_check(unsafe {
367            raw::TEE_ReadObjectData(
368                *self.as_raw_ref(),
369                buf.as_mut_ptr() as _,
370                buf.len(),
371                &mut count,
372            )
373        })?;
374        Ok(count as u32)
375    }
376
377    /// Reads the remaining data from the current cursor into a new TA-private vector.
378    ///
379    /// This method does not rewind the cursor. To read the entire object, first
380    /// call `seek(0, Whence::DataSeekSet)`.
381    ///
382    /// The allocation is sized using the object's current metadata. The returned
383    /// vector contains only the bytes actually read, and the data position advances
384    /// accordingly. At or beyond the end of the object, returns an empty vector.
385    /// Concurrent growth after the metadata query is not included in this read.
386    ///
387    /// Returns errors from [`GenericObject::info`] or [`Self::read`], or
388    /// [`ErrorKind::OutOfMemory`] if the allocation fails.
389    pub fn read_remaining_to_vec(&mut self) -> Result<Vec<u8>> {
390        let info = self.info()?;
391        let size = info.data_size().saturating_sub(info.raw.dataPosition);
392        let mut data = Vec::new();
393        if size != 0 {
394            data.try_reserve_exact(size)
395                .map_err(|_| ErrorKind::OutOfMemory)?;
396            data.resize(size, 0);
397            let count = self.read(&mut data)?;
398            data.truncate(count as usize);
399        }
400        Ok(data)
401    }
402
403    /// Write the passed in buffer data into from the data stream associate with
404    /// the object.
405    ///
406    /// # Parameters
407    ///
408    /// 1) `buffer`: A pre-allocated buffer for saving the object's data stream.
409    ///
410    /// # Example
411    ///
412    /// ``` rust,no_run
413    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
414    /// # fn main() -> optee_utee::Result<()> {
415    /// let obj_id = [1u8;1];
416    /// match PersistentObject::open (
417    ///         ObjectStorageConstants::Private,
418    ///         &obj_id,
419    ///         DataFlag::ACCESS_WRITE) {
420    ///     Ok(mut object) =>
421    ///     {
422    ///         let write_buf = [1u8;16];
423    ///         object.write(& write_buf)?;
424    ///         Ok(())
425    ///     }
426    ///     Err(e) => Err(e),
427    /// }
428    /// # }
429    /// ```
430    ///
431    /// # Errors
432    ///
433    /// 1) `StorageNoSpace`: If insufficient storage space is available.
434    /// 2) `Overflow`: If the value of the data position indicator resulting
435    ///    from this operation would be greater than
436    ///    [MiscellaneousConstants::TeeDataMaxPosition](crate::MiscellaneousConstants::TeeDataMaxPosition).
437    /// 3) `CorruptObject`: If the object is corrupt. The object handle SHALL
438    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
439    ///    property.
440    /// 4) `StorageNotAvailable`: If the object is stored in a storage area
441    ///    which is currently inaccessible.
442    ///
443    /// # Panics
444    ///
445    /// 1) If object is not a valid handle on a persistent object opened with
446    ///    the write access right
447    /// 2) If the Implementation detects any other error associated with this
448    ///    function which is not explicitly associated with a defined return
449    ///    code for this function.
450    pub fn write(&mut self, buf: &[u8]) -> Result<()> {
451        tee_check(unsafe {
452            raw::TEE_WriteObjectData(*self.as_raw_ref(), buf.as_ptr() as _, buf.len())
453        })
454    }
455
456    /// Change the size of a data stream associate with the object.
457    ///
458    /// # Example
459    ///
460    /// ``` rust,no_run
461    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag};
462    /// # fn main() -> optee_utee::Result<()> {
463    /// let obj_id = [1u8;1];
464    /// match PersistentObject::open (
465    ///         ObjectStorageConstants::Private,
466    ///         &obj_id,
467    ///         DataFlag::ACCESS_WRITE) {
468    ///     Ok(mut object) =>
469    ///     {
470    ///         object.truncate(1u32)?;
471    ///         Ok(())
472    ///     }
473    ///     Err(e) => Err(e),
474    /// }
475    /// # }
476    /// ```
477    ///
478    /// # Errors
479    ///
480    /// 1) `StorageNoSpace`: If insufficient storage space is available.
481    /// 2) `CorruptObject`: If the object is corrupt. The object handle SHALL
482    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
483    ///    property.
484    /// 3) `StorageNotAvailable`: If the object is stored in a storage area
485    ///    which is currently inaccessible.
486    ///
487    /// # Panics
488    ///
489    /// 1) If object is not a valid handle on a persistent object opened with
490    ///    the write access right.
491    /// 2) If the Implementation detects any other error associated with this
492    ///    function which is not explicitly associated with a defined return
493    ///    code for this function.
494    pub fn truncate(&mut self, size: u32) -> Result<()> {
495        tee_check(unsafe { raw::TEE_TruncateObjectData(*self.as_raw_ref(), size as usize) })
496    }
497
498    /// Set the data position indicator associate with the object.
499    ///
500    /// # Parameters
501    /// 1) `whence`: Defined in [Whence](crate::Whence).
502    /// 2) `offset`: The bytes shifted based on `whence`.
503    ///
504    /// # Example
505    ///
506    /// ``` rust,no_run
507    /// # use optee_utee::{PersistentObject, ObjectStorageConstants, DataFlag, Whence};
508    /// # fn main() -> optee_utee::Result<()> {
509    /// let obj_id = [1u8;1];
510    /// match PersistentObject::open(
511    ///         ObjectStorageConstants::Private,
512    ///         &obj_id,
513    ///         DataFlag::ACCESS_WRITE) {
514    ///     Ok(mut object) =>
515    ///     {
516    ///         object.seek(0i32, Whence::DataSeekSet)?;
517    ///         Ok(())
518    ///     }
519    ///     Err(e) => Err(e),
520    /// }
521    /// # }
522    /// ```
523    ///
524    /// # Errors
525    ///
526    /// 1) `Overflow`: If data position indicator is greater than
527    ///    [MiscellaneousConstants::TeeDataMaxPosition](crate::MiscellaneousConstants::TeeDataMaxPosition).
528    /// 2) `CorruptObject`: If the object is corrupt. The object handle SHALL
529    ///    behave based on the `gpd.ta.doesNotCloseHandleOnCorruptObject`
530    ///    property.
531    /// 3) `StorageNotAvailable`: If the object is stored in a storage area
532    ///    which is currently inaccessible.
533    ///
534    /// # Panics
535    ///
536    /// 1) If object is not a valid handle on a persistent object.
537    /// 2) If the Implementation detects any other error associated with this
538    ///    function which is not explicitly associated with a defined return
539    ///    code for this function.
540    pub fn seek(&mut self, offset: i32, whence: Whence) -> Result<()> {
541        tee_check(unsafe {
542            raw::TEE_SeekObjectData(*self.as_raw_ref(), offset.into(), whence.into())
543        })
544    }
545}
546
547impl GenericObject for PersistentObject {
548    unsafe fn as_raw_ref(&self) -> &optee_utee_sys::TEE_ObjectHandle {
549        unsafe { self.0.as_raw_ref() }
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    extern crate std;
556
557    use optee_utee_sys::{
558        mock_api,
559        mock_utils::{SERIAL_TEST_LOCK, object::MockHandle},
560    };
561
562    use super::*;
563
564    #[test]
565    fn test_read_remaining_to_vec() {
566        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
567        // Full read, nonzero position, short read, empty object, EOF, and beyond EOF.
568        for (size, position, bytes) in [
569            (4, 0, &b"data"[..]),
570            (4, 2, &b"ta"[..]),
571            (4, 0, &b"da"[..]),
572            (0, 0, &b""[..]),
573            (4, 4, &b""[..]),
574            (4, 6, &b""[..]),
575        ] {
576            let mut raw_handle = MockHandle::new();
577            let handle = raw_handle.as_handle();
578            let info = mock_api::TEE_GetObjectInfo1_context();
579            let read = mock_api::TEE_ReadObjectData_context();
580            let close = mock_api::TEE_CloseObject_context();
581            info.expect().times(1).return_once_st(move |_, info| {
582                unsafe {
583                    (*info).dataSize = size;
584                    (*info).dataPosition = position;
585                }
586                raw::TEE_SUCCESS
587            });
588            if position < size {
589                read.expect()
590                    .times(1)
591                    .return_once_st(move |_, buf, len, count| {
592                        assert_eq!(len, size - position);
593                        unsafe {
594                            core::ptr::copy_nonoverlapping(bytes.as_ptr(), buf.cast(), bytes.len());
595                            *count = bytes.len();
596                        }
597                        raw::TEE_SUCCESS
598                    });
599            } else {
600                read.expect().never();
601            }
602            close.expect().times(1).return_once_st(|_| ());
603            let mut object = PersistentObject(ObjectHandle::from_raw(handle).unwrap());
604            assert_eq!(object.read_remaining_to_vec().unwrap(), bytes);
605        }
606    }
607
608    #[test]
609    fn test_read_remaining_to_vec_errors() {
610        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
611        for (info_error, size, expected) in [
612            (
613                raw::TEE_ERROR_STORAGE_NOT_AVAILABLE,
614                4,
615                raw::TEE_ERROR_STORAGE_NOT_AVAILABLE,
616            ),
617            (raw::TEE_SUCCESS, 4, raw::TEE_ERROR_CORRUPT_OBJECT),
618            (raw::TEE_SUCCESS, usize::MAX, raw::TEE_ERROR_OUT_OF_MEMORY),
619        ] {
620            let mut raw_handle = MockHandle::new();
621            let handle = raw_handle.as_handle();
622            let info = mock_api::TEE_GetObjectInfo1_context();
623            let read = mock_api::TEE_ReadObjectData_context();
624            let close = mock_api::TEE_CloseObject_context();
625            info.expect().times(1).return_once_st(move |_, info| {
626                unsafe { (*info).dataSize = size };
627                info_error
628            });
629            if info_error == raw::TEE_SUCCESS && size == 4 {
630                read.expect()
631                    .times(1)
632                    .return_once_st(|_, _, _, _| raw::TEE_ERROR_CORRUPT_OBJECT);
633            } else {
634                read.expect().never();
635            }
636            close.expect().times(1).return_once_st(|_| ());
637            let mut object = PersistentObject(ObjectHandle::from_raw(handle).unwrap());
638            assert_eq!(
639                object.read_remaining_to_vec().unwrap_err().raw_code(),
640                expected
641            );
642        }
643    }
644
645    #[test]
646    // If a persistent object is successfully created, TEE_CloseObject will be
647    // called when it is dropped.
648    fn test_create_and_drop() {
649        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
650
651        let mut raw_handle = MockHandle::new();
652        let handle = raw_handle.as_handle();
653        let fn1 = mock_api::TEE_CreatePersistentObject_context();
654        let fn2 = mock_api::TEE_CloseObject_context();
655
656        fn1.expect()
657            .return_once_st(move |_, _, _, _, _, _, _, obj| {
658                unsafe { *obj = handle.clone() };
659                raw::TEE_SUCCESS
660            });
661        fn2.expect().return_once_st(move |obj| {
662            debug_assert_eq!(obj, handle);
663        });
664
665        let _obj = PersistentObject::create(
666            ObjectStorageConstants::Private,
667            &[],
668            DataFlag::ACCESS_WRITE,
669            None,
670            &[],
671        )
672        .expect("it should be ok");
673    }
674
675    #[test]
676    // https://github.com/apache/teaclave-trustzone-sdk/issues/288
677    fn test_create_with_attribute() {
678        use std::sync::{Arc, Mutex};
679
680        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
681
682        let mut raw_handle = MockHandle::new();
683        let mut attr_raw_handle = MockHandle::new();
684        let handle = raw_handle.as_handle();
685        let attr_handle = attr_raw_handle.as_handle();
686        let fn1 = mock_api::TEE_CreatePersistentObject_context();
687        let fn2 = mock_api::TEE_CloseObject_context();
688        let attribute_has_drop = Arc::new(Mutex::new(false));
689
690        fn1.expect().return_once_st({
691            let attribute_has_drop = attribute_has_drop.clone();
692            move |_, _, _, _, attr, _, _, obj| {
693                assert_eq!(attr, attr_handle);
694                let value: bool = *attribute_has_drop.lock().unwrap();
695                assert!(!value);
696                unsafe { *obj = handle.clone() };
697                raw::TEE_SUCCESS
698            }
699        });
700        fn2.expect()
701            .returning_st(move |obj| {
702                if obj == attr_handle {
703                    let mut value = attribute_has_drop.lock().unwrap();
704                    *value = true;
705                    return;
706                }
707                assert_eq!(obj, handle);
708            })
709            .times(2);
710
711        let _obj = PersistentObject::create(
712            ObjectStorageConstants::Private,
713            &[],
714            DataFlag::ACCESS_WRITE,
715            Some(ObjectHandle::from_raw(attr_handle).unwrap()),
716            &[],
717        )
718        .expect("it should be ok");
719    }
720
721    #[test]
722    fn test_create_failed() {
723        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
724
725        static RETURN_CODE: raw::TEE_Result = raw::TEE_ERROR_BAD_STATE;
726        let fn1 = mock_api::TEE_CreatePersistentObject_context();
727
728        fn1.expect().return_const_st(RETURN_CODE);
729
730        let err = PersistentObject::create(
731            ObjectStorageConstants::Private,
732            &[],
733            DataFlag::ACCESS_WRITE,
734            None,
735            &[],
736        )
737        .expect_err("it should be err");
738
739        assert_eq!(err.raw_code(), RETURN_CODE);
740    }
741
742    #[test]
743    // If a persistent object successfully `close_and_delete`, it should not
744    // call `TEE_CloseObject` anymore.
745    fn test_create_and_successfully_close_delete() {
746        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
747
748        let mut raw_handle = MockHandle::new();
749        let handle = raw_handle.as_handle();
750        let fn1 = mock_api::TEE_CreatePersistentObject_context();
751        let fn2 = mock_api::TEE_CloseAndDeletePersistentObject1_context();
752
753        fn1.expect()
754            .return_once_st(move |_, _, _, _, _, _, _, obj| {
755                unsafe { *obj = handle.clone() };
756                raw::TEE_SUCCESS
757            });
758        fn2.expect().return_once_st(move |obj| {
759            debug_assert_eq!(obj, handle);
760            raw::TEE_SUCCESS
761        });
762
763        let obj = PersistentObject::create(
764            ObjectStorageConstants::Private,
765            &[],
766            DataFlag::ACCESS_WRITE,
767            None,
768            &[],
769        )
770        .expect("it should be ok");
771
772        obj.close_and_delete().expect("it should be ok");
773    }
774
775    #[test]
776    // Even a persistent object failed at `close_and_delete`, `TEE_CloseObject`
777    // should not be called.
778    fn test_create_and_failed_close_delete() {
779        let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
780
781        let mut raw_handle = MockHandle::new();
782        let handle = raw_handle.as_handle();
783        let fn1 = mock_api::TEE_CreatePersistentObject_context();
784        let fn2 = mock_api::TEE_CloseAndDeletePersistentObject1_context();
785
786        fn1.expect()
787            .return_once_st(move |_, _, _, _, _, _, _, obj| {
788                unsafe { *obj = handle.clone() };
789                raw::TEE_SUCCESS
790            });
791        fn2.expect().return_once_st(move |obj| {
792            debug_assert_eq!(obj, handle);
793            raw::TEE_ERROR_BUSY
794        });
795
796        let obj = PersistentObject::create(
797            ObjectStorageConstants::Private,
798            &[],
799            DataFlag::ACCESS_WRITE,
800            None,
801            &[],
802        )
803        .expect("it should be ok");
804
805        obj.close_and_delete().expect_err("it should be err");
806    }
807}