1use std::cell::{Ref, RefCell, RefMut};
6use std::cmp::min;
7use std::collections::btree_map::Entry as BTreeMapEntry;
8use std::collections::hash_map::Entry as HashMapEntry;
9use std::collections::{BTreeMap, HashMap, HashSet};
10use std::ops::{Bound, Deref, DerefMut};
11use std::rc::Rc;
12
13use num_traits::FromPrimitive as _;
14use p256::elliptic_curve::sec1::ToEncodedPoint as _;
15use rsa::traits::{PrivateKeyParts as _, PublicKeyParts as _};
16use rsa::{BigUint, RsaPrivateKey};
17use tee_internal::{
18 Attribute, AttributeId, BufferOrValue, DATA_MAX_POSITION, EccCurve, Error, HandleFlags, MemRef,
19 OBJECT_ID_MAX_LEN, ObjectEnumHandle, ObjectHandle, ObjectInfo, Result as TeeResult,
20 Storage as TeeStorage, Type, Usage, ValueFields, Whence,
21};
22use thiserror::Error;
23
24use crate::ErrorWithSize;
25use crate::crypto::Rng;
26
27type P256SecretKey = p256::SecretKey;
28
29pub struct Storage {
30 persistent_objects: PersistentObjects,
31 transient_objects: TransientObjects,
32}
33
34fn is_persistent_handle(object: ObjectHandle) -> bool {
40 *object % 2 == 1
41}
42
43fn is_transient_handle(object: ObjectHandle) -> bool {
46 !is_persistent_handle(object)
47}
48
49pub enum BufferAttribute<'a> {
59 Slice(&'a [u8]),
60 Vector(Vec<u8>),
61}
62
63pub trait KeyType {
70 fn new(_max_size: u32) -> TeeResult<Self>
71 where
72 Self: Sized, {
74 unimplemented!()
75 }
76
77 fn is_valid_size(_size: u32) -> bool
78 where
79 Self: Sized, {
81 false
82 }
83
84 fn size(&self) -> u32 {
85 0
86 }
87
88 fn max_size(&self) -> u32 {
89 0
90 }
91
92 fn buffer_attribute(&self, _id: AttributeId) -> Option<BufferAttribute<'_>> {
93 None
94 }
95
96 fn value_attribute(&self, _id: AttributeId) -> Option<ValueFields> {
97 None
98 }
99
100 fn reset(&mut self) {
101 unimplemented!()
102 }
103
104 fn populate(&mut self, _attributes: &[Attribute]) -> TeeResult {
105 unimplemented!()
106 }
107
108 fn generate(&mut self, _size: u32, _params: &[Attribute]) -> TeeResult {
109 unimplemented!()
110 }
111}
112
113#[derive(Error, Debug)]
115enum ExtractAttributeError {
116 #[error("{0:?} provided twice")]
117 ProvidedTwice(AttributeId),
118
119 #[error("Unexpected attribute: {0:?}")]
120 Unexpected(AttributeId),
121}
122
123trait ExtractAttributeInto<T> {
127 fn extract_into(self, value: &mut T) -> Result<(), ExtractAttributeError>;
128}
129
130impl<'a> ExtractAttributeInto<&'a [u8]> for &'a Attribute {
131 fn extract_into(self, value: &mut &'a [u8]) -> Result<(), ExtractAttributeError> {
132 if !value.is_empty() {
133 Err(ExtractAttributeError::ProvidedTwice(self.id))
134 } else {
135 *value = self.as_memory_reference().as_slice();
136 Ok(())
137 }
138 }
139}
140
141impl ExtractAttributeInto<Option<ValueFields>> for &Attribute {
142 fn extract_into(self, value: &mut Option<ValueFields>) -> Result<(), ExtractAttributeError> {
143 if value.is_some() {
144 Err(ExtractAttributeError::ProvidedTwice(self.id))
145 } else {
146 *value = Some(*self.as_value());
147 Ok(())
148 }
149 }
150}
151
152macro_rules! extract_attributes {
169 ($attributes:expr, $($id:path => $var:ident),*) => {
170 || -> Result<(), ExtractAttributeError> {
171 for attr in $attributes {
172 match attr.id {
173 $( $id => attr.extract_into(&mut $var)?, )*
174 _ => return Err(ExtractAttributeError::Unexpected(attr.id)),
175 }
176 }
177 Ok(())
178 }()
179 };
180}
181
182#[derive(Clone)]
183pub struct SimpleSymmetricKey<const SIZE_MIN: u32, const SIZE_MAX: u32, const SIZE_MULTIPLE: u32> {
184 pub secret: Vec<u8>, }
186
187impl<const SIZE_MIN: u32, const SIZE_MAX: u32, const SIZE_MULTIPLE: u32> KeyType
188 for SimpleSymmetricKey<SIZE_MIN, SIZE_MAX, SIZE_MULTIPLE>
189{
190 fn new(max_size: u32) -> TeeResult<Self> {
191 const { assert!((SIZE_MIN % SIZE_MULTIPLE) == 0) };
194 const { assert!((SIZE_MAX % SIZE_MULTIPLE) == 0) };
195
196 if Self::is_valid_size(max_size) {
197 Ok(Self { secret: Vec::with_capacity((max_size / u8::BITS) as usize) })
198 } else {
199 Err(Error::NotSupported)
200 }
201 }
202
203 fn is_valid_size(size: u32) -> bool {
204 size >= SIZE_MIN && size <= SIZE_MAX && (size % SIZE_MULTIPLE) == 0
205 }
206
207 fn size(&self) -> u32 {
208 (self.secret.len() as u32) * u8::BITS
209 }
210
211 fn max_size(&self) -> u32 {
212 (self.secret.capacity() as u32) * u8::BITS
213 }
214
215 fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
216 if id == AttributeId::SecretValue {
217 Some(BufferAttribute::Slice(&self.secret))
218 } else {
219 None
220 }
221 }
222
223 fn reset(&mut self) {
224 self.secret.clear();
225 }
226
227 fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
228 debug_assert!(self.secret.is_empty());
229
230 let mut secret: &[u8] = &[];
231 extract_attributes!(
232 attributes,
233 AttributeId::SecretValue => secret
234 )
235 .unwrap();
236 assert!(!secret.is_empty(), "Missing attribute for secret value");
237
238 assert!(secret.len() <= self.secret.capacity());
239 self.secret.extend_from_slice(secret);
240 Ok(())
241 }
242
243 fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
244 assert!(Self::is_valid_size(size));
245 assert!(size <= self.max_size());
246 if !params.is_empty() {
247 return Err(Error::BadParameters);
248 }
249 self.secret.resize((size / u8::BITS) as usize, 0);
250 zx::cprng_draw(self.secret.as_mut_slice());
251 Ok(())
252 }
253}
254
255pub type AesKey = SimpleSymmetricKey<128, 256, 64>; pub type HmacSha1Key = SimpleSymmetricKey<80, 512, 8>;
257pub type HmacSha224Key = SimpleSymmetricKey<112, 512, 8>;
258pub type HmacSha256Key = SimpleSymmetricKey<192, 1024, 8>;
259pub type HmacSha384Key = SimpleSymmetricKey<256, 512, 8>;
260pub type HmacSha512Key = SimpleSymmetricKey<256, 512, 8>;
261
262pub struct RsaKeypair {
263 private: Option<Rc<RsaPrivateKey>>,
264 max_size: u32,
265}
266
267impl RsaKeypair {
268 pub fn private_key(&self) -> Rc<RsaPrivateKey> {
269 self.private.as_ref().unwrap().clone()
270 }
271}
272
273impl Clone for RsaKeypair {
276 fn clone(&self) -> Self {
277 let max_size = self.max_size;
278 if let Some(private) = &self.private {
279 Self { private: Some(Rc::new(private.deref().clone())), max_size }
280 } else {
281 Self { private: None, max_size }
282 }
283 }
284}
285
286impl KeyType for RsaKeypair {
287 fn new(max_size: u32) -> TeeResult<Self> {
288 if !Self::is_valid_size(max_size) {
289 return Err(Error::NotSupported);
290 }
291 Ok(Self { private: None, max_size })
292 }
293
294 fn is_valid_size(size: u32) -> bool {
295 (size % u8::BITS) == 0 && 512 <= size && size <= 4096
296 }
297
298 fn size(&self) -> u32 {
299 if let Some(private) = &self.private { (private.size() as u32) * u8::BITS } else { 0 }
300 }
301
302 fn max_size(&self) -> u32 {
303 self.max_size
304 }
305
306 fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
307 let Some(private) = &self.private else {
308 return None;
309 };
310 match id {
311 AttributeId::RsaModulus => Some(BufferAttribute::Vector(private.n().to_bytes_be())),
312 AttributeId::RsaPublicExponent => {
313 Some(BufferAttribute::Vector(private.e().to_bytes_be()))
314 }
315 AttributeId::RsaPrivateExponent => {
316 Some(BufferAttribute::Vector(private.d().to_bytes_be()))
317 }
318 AttributeId::RsaPrime1 => {
319 Some(BufferAttribute::Vector(private.primes()[0].to_bytes_be()))
320 }
321 AttributeId::RsaPrime2 => {
322 Some(BufferAttribute::Vector(private.primes()[1].to_bytes_be()))
323 }
324 AttributeId::RsaExponent1 => {
325 Some(BufferAttribute::Vector(private.dp().unwrap().to_bytes_be()))
326 }
327 AttributeId::RsaExponent2 => {
328 Some(BufferAttribute::Vector(private.dq().unwrap().to_bytes_be()))
329 }
330 AttributeId::RsaCoefficient => {
331 Some(BufferAttribute::Vector(private.crt_coefficient().unwrap().to_bytes_be()))
332 }
333 _ => None,
334 }
335 }
336
337 fn reset(&mut self) {
338 self.private = None;
339 }
340
341 fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
342 assert!(self.private.is_none());
343
344 let mut modulus: &[u8] = &[];
345 let mut public_exponent: &[u8] = &[];
346 let mut private_exponent: &[u8] = &[];
347 let mut prime1: &[u8] = &[];
348 let mut prime2: &[u8] = &[];
349 let mut exponent1: &[u8] = &[];
350 let mut exponent2: &[u8] = &[];
351 let mut coefficient: &[u8] = &[];
352 extract_attributes!(
353 attributes,
354 AttributeId::RsaModulus => modulus,
355 AttributeId::RsaPublicExponent => public_exponent,
356 AttributeId::RsaPrivateExponent => private_exponent,
357 AttributeId::RsaPrime1 => prime1,
358 AttributeId::RsaPrime2 => prime2,
359 AttributeId::RsaExponent1 => exponent1,
360 AttributeId::RsaExponent2 => exponent2,
361 AttributeId::RsaCoefficient => coefficient
362 )
363 .unwrap();
364 assert!(!modulus.is_empty(), "Missing attribute for RSA modulus");
365 assert!(!public_exponent.is_empty(), "Missing attribute for RSA public exponent");
366 assert!(!private_exponent.is_empty(), "Missing attribute for RSA private exponent");
367
368 if !prime1.is_empty()
369 || prime2.is_empty()
370 || !exponent1.is_empty()
371 || !exponent2.is_empty()
372 || !coefficient.is_empty()
373 {
374 assert!(
375 !prime1.is_empty(),
376 "TEE_ATTR_RSA_PRIME1 is required if another CRT attribute is provided"
377 );
378 assert!(
379 !prime2.is_empty(),
380 "TEE_ATTR_RSA_PRIME2 is required if another CRT attribute is provided"
381 );
382 assert!(
383 !exponent1.is_empty(),
384 "TEE_ATTR_RSA_EXPONENT1 is required if another CRT attribute is provided"
385 );
386 assert!(
387 !exponent2.is_empty(),
388 "TEE_ATTR_RSA_EXPONENT2 is required if another CRT attribute is provided"
389 );
390 assert!(
391 !coefficient.is_empty(),
392 "TEE_ATTR_RSA_COEFFICIENT is required if another CRT attribute is provided"
393 );
394 }
395
396 let len: u32 = modulus.len().try_into().unwrap();
397 assert!(u8::BITS * len <= self.max_size());
398
399 let mut private_key = RsaPrivateKey::from_components(
400 BigUint::from_bytes_be(modulus),
401 BigUint::from_bytes_be(public_exponent),
402 BigUint::from_bytes_be(private_exponent),
403 vec![BigUint::from_bytes_be(prime1), BigUint::from_bytes_be(prime2)],
404 )
405 .map_err(|_| Error::BadParameters)?;
406
407 private_key.precompute().unwrap();
410
411 if !exponent1.is_empty() {
412 if *private_key.dp().unwrap() != BigUint::from_bytes_be(exponent1) {
413 return Err(Error::BadParameters);
414 }
415 if *private_key.dq().unwrap() != BigUint::from_bytes_be(exponent2) {
416 return Err(Error::BadParameters);
417 }
418 if private_key.crt_coefficient().unwrap() != BigUint::from_bytes_be(coefficient) {
419 return Err(Error::BadParameters);
420 }
421 }
422
423 self.private = Some(Rc::new(private_key));
424 Ok(())
425 }
426
427 fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
428 assert!(Self::is_valid_size(size));
429 assert!(size <= self.max_size());
430 assert!(self.private.is_none());
431
432 let mut public_exponent: &[u8] = &[];
433 extract_attributes!(params, AttributeId::RsaPublicExponent => public_exponent)
434 .map_err(|_| Error::BadParameters)?;
435
436 let mut private_key = if public_exponent.is_empty() {
437 RsaPrivateKey::new(&mut Rng {}, size as usize)
438 } else {
439 RsaPrivateKey::new_with_exp(
440 &mut Rng {},
441 size as usize,
442 &BigUint::from_bytes_be(public_exponent),
443 )
444 }
445 .unwrap();
446
447 private_key.precompute().unwrap();
450
451 self.private = Some(Rc::new(private_key));
452
453 Ok(())
454 }
455}
456
457#[derive(Clone)]
458pub struct EccKeypair {
459 secret: Option<Box<P256SecretKey>>,
460}
461
462impl KeyType for EccKeypair {
464 fn new(max_size: u32) -> TeeResult<Self> {
465 if !Self::is_valid_size(max_size) {
466 return Err(Error::NotSupported);
467 }
468 Ok(Self { secret: None })
469 }
470
471 fn is_valid_size(size: u32) -> bool {
472 size == 256
473 }
474
475 fn size(&self) -> u32 {
476 256
477 }
478
479 fn max_size(&self) -> u32 {
480 256
481 }
482
483 fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
484 let Some(secret) = &self.secret else {
485 return None;
486 };
487 match id {
488 AttributeId::EccPrivateValue => {
489 Some(BufferAttribute::Vector(secret.to_be_bytes().as_slice().to_vec()))
490 }
491 AttributeId::EccPublicValueX => Some(BufferAttribute::Vector(
492 secret
493 .public_key()
494 .as_affine()
495 .to_encoded_point(false)
496 .x()
497 .unwrap()
498 .as_slice()
499 .to_vec(),
500 )),
501 AttributeId::EccPublicValueY => Some(BufferAttribute::Vector(
502 secret
503 .public_key()
504 .as_affine()
505 .to_encoded_point(false)
506 .y()
507 .unwrap()
508 .as_slice()
509 .to_vec(),
510 )),
511 _ => None,
512 }
513 }
514
515 fn value_attribute(&self, id: AttributeId) -> Option<ValueFields> {
516 match id {
517 AttributeId::EccCurve => Some(ValueFields { a: EccCurve::NistP256 as u32, b: 0 }),
518 _ => None,
519 }
520 }
521
522 fn reset(&mut self) {
523 self.secret = None;
524 }
525
526 fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
527 assert!(self.secret.is_none());
528
529 let mut private_value: &[u8] = &[];
530 let mut public_value_x: &[u8] = &[];
531 let mut public_value_y: &[u8] = &[];
532 let mut curve: Option<ValueFields> = None;
533 extract_attributes!(
534 attributes,
535 AttributeId::EccPrivateValue => private_value,
536 AttributeId::EccPublicValueX => public_value_x,
537 AttributeId::EccPublicValueY => public_value_y,
538 AttributeId::EccCurve => curve
539 )
540 .unwrap();
541 assert!(!private_value.is_empty(), "Missing attribute for ECC private value");
542 assert!(!public_value_x.is_empty(), "Missing attribute for ECC public value X");
543 assert!(!public_value_y.is_empty(), "Missing attribute for ECC public value Y");
544 assert!(curve.is_some(), "Missing attribute for ECC curve");
545
546 let curve = EccCurve::from_u32(curve.unwrap().a).ok_or(Error::NotSupported)?;
547 if curve != EccCurve::NistP256 {
548 return Err(Error::NotSupported);
549 }
550
551 let secret = P256SecretKey::from_be_bytes(private_value).unwrap();
552
553 let point = secret.public_key().as_affine().to_encoded_point(false);
556 if point.x().unwrap().as_slice() != public_value_x {
557 return Err(Error::BadParameters);
558 }
559 if point.y().unwrap().as_slice() != public_value_y {
560 return Err(Error::BadParameters);
561 }
562 self.secret = Some(Box::new(secret));
563 Ok(())
564 }
565
566 fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
567 assert!(Self::is_valid_size(size));
568 assert!(size <= self.max_size());
569 assert!(self.secret.is_none());
570
571 let mut curve: Option<ValueFields> = None;
572 extract_attributes!(params, AttributeId::EccCurve => curve)
573 .map_err(|_| Error::BadParameters)?;
574 assert!(curve.is_some(), "Missing attribute for ECC curve");
575
576 let curve = EccCurve::from_u32(curve.unwrap().a).ok_or(Error::NotSupported)?;
577 if curve != EccCurve::NistP256 {
578 return Err(Error::NotSupported);
579 }
580
581 self.secret = Some(Box::new(P256SecretKey::random(&mut Rng {})));
582 Ok(())
583 }
584}
585
586#[derive(Clone)]
587pub struct NoKey {}
588
589impl KeyType for NoKey {
590 fn new(max_size: u32) -> TeeResult<Self> {
591 if max_size == 0 { Ok(Self {}) } else { Err(Error::NotSupported) }
592 }
593
594 fn is_valid_size(size: u32) -> bool {
595 size == 0
596 }
597
598 fn reset(&mut self) {}
599
600 fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
601 assert!(attributes.is_empty());
602 Ok(())
603 }
604
605 fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
606 assert_eq!(size, 0);
607 assert!(params.is_empty());
608 Ok(())
609 }
610}
611
612#[derive(Clone)]
614pub enum Key {
615 Aes(AesKey),
616 HmacSha1(HmacSha1Key),
617 HmacSha224(HmacSha224Key),
618 HmacSha256(HmacSha256Key),
619 HmacSha384(HmacSha384Key),
620 HmacSha512(HmacSha512Key),
621 RsaKeypair(RsaKeypair),
622 EcdsaKeypair(EccKeypair),
623 EcdhKeypair(EccKeypair),
624 Data(NoKey),
625}
626
627macro_rules! get_key_variant {
629 ($key:ident) => {
630 match $key {
631 Key::Aes(key) => key,
632 Key::HmacSha1(key) => key,
633 Key::HmacSha224(key) => key,
634 Key::HmacSha256(key) => key,
635 Key::HmacSha384(key) => key,
636 Key::HmacSha512(key) => key,
637 Key::RsaKeypair(key) => key,
638 Key::EcdsaKeypair(key) => key,
639 Key::EcdhKeypair(key) => key,
640 Key::Data(key) => key,
641 }
642 };
643}
644
645impl Key {
646 pub fn new(type_: Type, max_size: u32) -> TeeResult<Key> {
647 match type_ {
648 Type::Aes => AesKey::new(max_size).map(Self::Aes),
649 Type::HmacSha1 => HmacSha1Key::new(max_size).map(Self::HmacSha1),
650 Type::HmacSha224 => HmacSha224Key::new(max_size).map(Self::HmacSha224),
651 Type::HmacSha256 => HmacSha256Key::new(max_size).map(Self::HmacSha256),
652 Type::HmacSha384 => HmacSha384Key::new(max_size).map(Self::HmacSha384),
653 Type::HmacSha512 => HmacSha512Key::new(max_size).map(Self::HmacSha512),
654 Type::RsaKeypair => RsaKeypair::new(max_size).map(Self::RsaKeypair),
655 Type::EcdsaKeypair => EccKeypair::new(max_size).map(Self::EcdsaKeypair),
656 Type::EcdhKeypair => EccKeypair::new(max_size).map(Self::EcdhKeypair),
657 Type::Data => NoKey::new(max_size).map(Self::Data),
658 _ => Err(Error::NotSupported),
659 }
660 }
661
662 pub fn get_type(&self) -> Type {
663 match self {
664 Key::Aes(_) => Type::Aes,
665 Key::HmacSha1(_) => Type::HmacSha1,
666 Key::HmacSha224(_) => Type::HmacSha224,
667 Key::HmacSha256(_) => Type::HmacSha256,
668 Key::HmacSha384(_) => Type::HmacSha384,
669 Key::HmacSha512(_) => Type::HmacSha512,
670 Key::RsaKeypair(_) => Type::RsaKeypair,
671 Key::EcdsaKeypair(_) => Type::EcdsaKeypair,
672 Key::EcdhKeypair(_) => Type::EcdhKeypair,
673 Key::Data(_) => Type::Data,
674 }
675 }
676}
677
678impl Deref for Key {
679 type Target = dyn KeyType;
680
681 fn deref(&self) -> &Self::Target {
682 get_key_variant!(self)
683 }
684}
685
686impl DerefMut for Key {
687 fn deref_mut(&mut self) -> &mut Self::Target {
688 get_key_variant!(self)
689 }
690}
691
692pub trait Object {
695 fn key(&self) -> &Key;
696
697 fn usage(&self) -> &Usage;
698 fn usage_mut(&mut self) -> &mut Usage;
699
700 fn flags(&self) -> &HandleFlags;
701
702 fn restrict_usage(&mut self, restriction: Usage) {
703 let usage = self.usage_mut();
704 *usage = usage.intersection(restriction)
705 }
706
707 fn get_info(&self, data_size: usize, data_position: usize) -> ObjectInfo {
708 let all_info_flags = HandleFlags::PERSISTENT
709 | HandleFlags::INITIALIZED
710 | HandleFlags::DATA_ACCESS_READ
711 | HandleFlags::DATA_ACCESS_WRITE
712 | HandleFlags::DATA_ACCESS_WRITE_META
713 | HandleFlags::DATA_SHARE_READ
714 | HandleFlags::DATA_SHARE_WRITE;
715 let flags = self.flags().intersection(all_info_flags);
716 let key_size = self.key().size();
717 let object_size = if key_size > 0 { key_size } else { data_size.try_into().unwrap() };
718 ObjectInfo {
719 object_type: self.key().get_type(),
720 max_object_size: self.key().max_size(),
721 object_size,
722 object_usage: *self.usage(),
723 data_position: data_position,
724 data_size: data_size,
725 handle_flags: flags,
726 }
727 }
728}
729
730struct TransientObject {
731 key: Key,
732 usage: Usage,
733 flags: HandleFlags,
734}
735
736impl TransientObject {
737 fn new(key: Key) -> Self {
738 TransientObject { key, usage: Usage::default(), flags: HandleFlags::empty() }
739 }
740}
741
742impl Object for TransientObject {
743 fn key(&self) -> &Key {
744 &self.key
745 }
746
747 fn usage(&self) -> &Usage {
748 &self.usage
749 }
750 fn usage_mut(&mut self) -> &mut Usage {
751 &mut self.usage
752 }
753
754 fn flags(&self) -> &HandleFlags {
755 &self.flags
756 }
757}
758
759struct TransientObjects {
761 by_handle: HashMap<ObjectHandle, Rc<RefCell<TransientObject>>>,
762 next_handle_value: u64,
763}
764
765impl TransientObjects {
766 fn new() -> Self {
767 Self {
768 by_handle: HashMap::new(),
769 next_handle_value: 2,
771 }
772 }
773
774 fn allocate(&mut self, type_: Type, max_size: u32) -> TeeResult<ObjectHandle> {
775 let key = Key::new(type_, max_size)?;
776 let handle = self.mint_handle();
777 let prev =
778 self.by_handle.insert(handle.clone(), Rc::new(RefCell::new(TransientObject::new(key))));
779 debug_assert!(prev.is_none());
780
781 Ok(handle)
782 }
783
784 fn free(&mut self, handle: ObjectHandle) {
785 if handle.is_null() {
786 return;
787 }
788 match self.by_handle.entry(handle) {
789 HashMapEntry::Occupied(entry) => {
790 let _ = entry.remove();
791 }
792 HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
793 }
794 }
795
796 fn reset(&self, handle: ObjectHandle) {
797 match self.by_handle.get(&handle) {
798 Some(obj) => {
799 let mut obj = obj.borrow_mut();
800 obj.flags.remove(HandleFlags::INITIALIZED);
801 obj.key.reset()
802 }
803 None => panic!("{handle:?} is not a valid handle"),
804 }
805 }
806
807 fn populate(&self, handle: ObjectHandle, attributes: &[Attribute]) -> TeeResult {
808 match self.by_handle.get(&handle) {
809 Some(obj) => {
810 let mut obj = obj.borrow_mut();
811 assert!(
812 !obj.flags.contains(HandleFlags::INITIALIZED),
813 "{handle:?} is already initialized"
814 );
815 obj.flags.insert(HandleFlags::INITIALIZED);
816 obj.key.populate(attributes)
817 }
818 None => panic!("{handle:?} is not a valid handle"),
819 }
820 }
821
822 fn generate_key(&self, handle: ObjectHandle, size: u32, params: &[Attribute]) -> TeeResult {
823 match self.by_handle.get(&handle) {
824 Some(obj) => {
825 let mut obj = obj.borrow_mut();
826 assert!(
827 !obj.flags.contains(HandleFlags::INITIALIZED),
828 "{handle:?} is already initialized"
829 );
830 obj.flags.insert(HandleFlags::INITIALIZED);
831 obj.key.generate(size, params)
832 }
833 None => panic!("{handle:?} is not a valid handle"),
834 }
835 }
836
837 fn get(&self, handle: ObjectHandle) -> Ref<'_, TransientObject> {
840 self.by_handle
841 .get(&handle)
842 .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
843 .borrow()
844 }
845
846 fn get_mut(&self, handle: ObjectHandle) -> RefMut<'_, TransientObject> {
849 self.by_handle
850 .get(&handle)
851 .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
852 .borrow_mut()
853 }
854
855 fn mint_handle(&mut self) -> ObjectHandle {
856 let handle_value = self.next_handle_value;
857 self.next_handle_value += 2;
858 ObjectHandle::from_value(handle_value)
859 }
860}
861
862struct PersistentObject {
863 key: Key,
864 usage: Usage,
865 base_flags: HandleFlags,
866 data: zx::Vmo,
867 data_size: usize,
868 id: Vec<u8>,
869
870 handles: HashSet<ObjectHandle>,
873}
874
875impl Object for PersistentObject {
876 fn key(&self) -> &Key {
877 &self.key
878 }
879
880 fn usage(&self) -> &Usage {
881 &self.usage
882 }
883 fn usage_mut(&mut self) -> &mut Usage {
884 &mut self.usage
885 }
886
887 fn flags(&self) -> &HandleFlags {
888 &self.base_flags
889 }
890}
891
892struct PersistentObjectView {
894 object: Rc<RefCell<PersistentObject>>,
895 flags: HandleFlags,
896 data_position: usize,
897}
898
899impl PersistentObjectView {
900 fn get_info(&self) -> ObjectInfo {
901 let obj = self.object.borrow();
902 obj.get_info(obj.data_size, self.data_position)
903 }
904
905 fn read_data<'a>(&mut self, buffer: &'a mut [u8]) -> TeeResult<&'a [u8]> {
907 let obj = self.object.borrow();
908 let read_size = min(obj.data_size - self.data_position, buffer.len());
909 let written = &mut buffer[..read_size];
910 if read_size > 0 {
911 obj.data.read(written, self.data_position as u64).unwrap();
912 }
913 self.data_position += read_size;
914 Ok(written)
915 }
916
917 fn write_data(&mut self, data: &[u8]) -> TeeResult {
919 if data.is_empty() {
920 return Ok(());
921 }
922 let mut obj = self.object.borrow_mut();
923 let write_end = self.data_position + data.len();
924
925 if write_end > DATA_MAX_POSITION {
926 return Err(Error::Overflow);
927 }
928 if write_end > obj.data_size {
929 obj.data.set_size(write_end as u64).unwrap();
930 obj.data_size = write_end;
931 }
932 obj.data.write(data, self.data_position as u64).unwrap();
933 self.data_position = write_end;
934 Ok(())
935 }
936
937 fn truncate_data(&self, size: usize) -> TeeResult {
939 let mut obj = self.object.borrow_mut();
940
941 let size = min(size, DATA_MAX_POSITION);
947 obj.data.set_size(size as u64).unwrap();
948 obj.data_size = size;
949 Ok(())
950 }
951
952 fn seek_data(&mut self, offset: isize, whence: Whence) -> TeeResult {
954 let start = match whence {
955 Whence::DataSeekCur => self.data_position,
956 Whence::DataSeekEnd => self.object.borrow().data_size,
957 Whence::DataSeekSet => 0,
958 };
959 let new_position = start.saturating_add_signed(offset);
960 if new_position > DATA_MAX_POSITION {
961 Err(Error::Overflow)
962 } else {
963 self.data_position = new_position;
964 Ok(())
965 }
966 }
967}
968
969struct EnumState {
971 id: Option<Vec<u8>>,
973}
974
975type PersistentIdMap = BTreeMap<Vec<u8>, Rc<RefCell<PersistentObject>>>;
984
985type PersistentHandleMap = HashMap<ObjectHandle, RefCell<PersistentObjectView>>;
986type PersistentEnumHandleMap = HashMap<ObjectEnumHandle, RefCell<EnumState>>;
987
988struct PersistentObjects {
990 by_id: PersistentIdMap,
991 by_handle: PersistentHandleMap,
992 enum_handles: PersistentEnumHandleMap,
993 next_handle_value: u64,
994 next_enum_handle_value: u64,
995}
996
997impl PersistentObjects {
998 fn new() -> Self {
999 Self {
1000 by_id: PersistentIdMap::new(),
1001 by_handle: PersistentHandleMap::new(),
1002 enum_handles: HashMap::new(),
1003 next_handle_value: 1, next_enum_handle_value: 1,
1005 }
1006 }
1007
1008 fn create(
1009 &mut self,
1010 key: Key,
1011 usage: Usage,
1012 flags: HandleFlags,
1013 id: &[u8],
1014 initial_data: &[u8],
1015 ) -> TeeResult<ObjectHandle> {
1016 assert!(id.len() <= OBJECT_ID_MAX_LEN);
1017
1018 let data = zx::Vmo::create_with_opts(zx::VmoOptions::RESIZABLE, initial_data.len() as u64)
1019 .unwrap();
1020 if !initial_data.is_empty() {
1021 data.write(initial_data, 0).unwrap();
1022 }
1023
1024 let flags = flags.union(HandleFlags::PERSISTENT | HandleFlags::INITIALIZED);
1025
1026 let obj = PersistentObject {
1027 key,
1028 usage,
1029 base_flags: flags,
1030 data,
1031 data_size: initial_data.len(),
1032 id: Vec::from(id),
1033 handles: HashSet::new(),
1034 };
1035
1036 let obj_ref = match self.by_id.get(id) {
1037 Some(obj_ref) => {
1041 if !flags.contains(HandleFlags::DATA_FLAG_OVERWRITE) {
1042 return Err(Error::AccessConflict);
1043 }
1044 {
1045 let mut obj_old = obj_ref.borrow_mut();
1046 for handle in obj_old.handles.iter() {
1047 let removed = self.by_handle.remove(&handle).is_some();
1048 debug_assert!(removed);
1049 }
1050 *obj_old = obj;
1051 }
1052 obj_ref.clone()
1053 }
1054 None => {
1055 let id = obj.id.clone();
1056 let obj_ref = Rc::new(RefCell::new(obj));
1057 let inserted = self.by_id.insert(id, obj_ref.clone());
1058 debug_assert!(inserted.is_none());
1059 obj_ref
1060 }
1061 };
1062 Ok(self.open_internal(obj_ref, flags))
1063 }
1064
1065 fn open(&mut self, id: &[u8], flags: HandleFlags) -> TeeResult<ObjectHandle> {
1067 assert!(id.len() <= OBJECT_ID_MAX_LEN);
1068
1069 let obj_ref = match self.by_id.get(id) {
1070 Some(obj_ref) => Ok(obj_ref),
1071 None => Err(Error::ItemNotFound),
1072 }?;
1073
1074 {
1075 let mut obj = obj_ref.borrow_mut();
1076
1077 debug_assert!(Rc::strong_count(obj_ref) >= obj.handles.len() + 1);
1082
1083 if obj.handles.is_empty() {
1089 obj.base_flags = flags.union(HandleFlags::PERSISTENT | HandleFlags::INITIALIZED);
1090 } else {
1091 let combined = flags.union(obj.base_flags);
1092 let intersection = flags.intersection(obj.base_flags);
1093
1094 if flags.contains(HandleFlags::DATA_ACCESS_READ)
1096 && !(intersection.contains(HandleFlags::DATA_SHARE_READ))
1097 {
1098 return Err(Error::AccessConflict);
1099 }
1100
1101 if combined.contains(HandleFlags::DATA_SHARE_READ)
1103 == intersection.contains(HandleFlags::DATA_SHARE_READ)
1104 {
1105 return Err(Error::AccessConflict);
1106 }
1107
1108 if flags.contains(HandleFlags::DATA_ACCESS_WRITE)
1110 && !(intersection.contains(HandleFlags::DATA_SHARE_WRITE))
1111 {
1112 return Err(Error::AccessConflict);
1113 }
1114
1115 if combined.contains(HandleFlags::DATA_SHARE_WRITE)
1117 == intersection.contains(HandleFlags::DATA_SHARE_WRITE)
1118 {
1119 return Err(Error::AccessConflict);
1120 }
1121 }
1122 }
1123
1124 Ok(self.open_internal(obj_ref.clone(), flags))
1125 }
1126
1127 fn open_internal(
1130 &mut self,
1131 object: Rc<RefCell<PersistentObject>>,
1132 flags: HandleFlags,
1133 ) -> ObjectHandle {
1134 let handle = self.mint_handle();
1135 let inserted = object.borrow_mut().handles.insert(handle);
1136 debug_assert!(inserted);
1137 let view = PersistentObjectView { object, flags, data_position: 0 };
1138 let inserted = self.by_handle.insert(handle, RefCell::new(view)).is_none();
1139 debug_assert!(inserted);
1140 handle
1141 }
1142
1143 fn close(&mut self, handle: ObjectHandle) {
1144 match self.by_handle.entry(handle) {
1148 HashMapEntry::Occupied(entry) => {
1149 {
1150 let view = entry.get().borrow_mut();
1151 let mut obj = view.object.borrow_mut();
1152 let removed = obj.handles.remove(&handle);
1153 debug_assert!(removed);
1154 }
1155 let _ = entry.remove();
1156 }
1157 HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1158 }
1159 }
1160
1161 fn close_and_delete(&mut self, handle: ObjectHandle) -> TeeResult {
1165 match self.by_handle.entry(handle) {
1168 HashMapEntry::Occupied(entry) => {
1169 {
1170 let state = entry.get().borrow();
1171 if !state.flags.contains(HandleFlags::DATA_ACCESS_WRITE_META) {
1172 return Err(Error::AccessDenied);
1173 }
1174 let obj = state.object.borrow();
1175 debug_assert_eq!(obj.handles.len(), 1);
1176 let removed = self.by_id.remove(&obj.id).is_some();
1177 debug_assert!(removed);
1178 }
1179 let _ = entry.remove();
1180 Ok(())
1181 }
1182 HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1183 }
1184 }
1185
1186 fn rename(&mut self, handle: ObjectHandle, new_id: &[u8]) -> TeeResult {
1190 match self.by_handle.entry(handle) {
1191 HashMapEntry::Occupied(handle_entry) => {
1192 let state = handle_entry.get().borrow();
1193 if !state.flags.contains(HandleFlags::DATA_ACCESS_WRITE_META) {
1194 return Err(Error::AccessDenied);
1195 }
1196 let new_id = Vec::from(new_id);
1197 match self.by_id.entry(new_id.clone()) {
1198 BTreeMapEntry::Occupied(_) => return Err(Error::AccessConflict),
1199 BTreeMapEntry::Vacant(id_entry) => {
1200 let _ = id_entry.insert(state.object.clone());
1201 }
1202 };
1203 let mut obj = state.object.borrow_mut();
1204 let removed = self.by_id.remove(&obj.id);
1205 debug_assert!(removed.is_some());
1206 obj.id = new_id;
1207 Ok(())
1208 }
1209 HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1210 }
1211 }
1212
1213 fn get(&self, handle: ObjectHandle) -> Ref<'_, PersistentObjectView> {
1216 self.by_handle
1217 .get(&handle)
1218 .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
1219 .borrow()
1220 }
1221
1222 fn get_mut(&self, handle: ObjectHandle) -> RefMut<'_, PersistentObjectView> {
1225 self.by_handle
1226 .get(&handle)
1227 .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
1228 .borrow_mut()
1229 }
1230
1231 fn allocate_enumerator(&mut self) -> ObjectEnumHandle {
1233 let enumerator = self.mint_enumerator_handle();
1234
1235 let previous =
1236 self.enum_handles.insert(enumerator.clone(), RefCell::new(EnumState { id: None }));
1237 debug_assert!(previous.is_none());
1238 enumerator
1239 }
1240
1241 fn free_enumerator(&mut self, enumerator: ObjectEnumHandle) -> () {
1243 match self.enum_handles.entry(enumerator) {
1244 HashMapEntry::Occupied(entry) => {
1245 let _ = entry.remove();
1246 }
1247 HashMapEntry::Vacant(_) => panic!("{enumerator:?} is not a valid enumerator handle"),
1248 }
1249 }
1250
1251 fn reset_enumerator(&mut self, enumerator: ObjectEnumHandle) -> () {
1253 match self.enum_handles.get(&enumerator) {
1254 Some(state) => {
1255 state.borrow_mut().id = None;
1256 }
1257 None => panic!("{enumerator:?} is not a valid enumerator handle"),
1258 }
1259 }
1260
1261 fn get_next_object<'a>(
1263 &self,
1264 enumerator: ObjectEnumHandle,
1265 id_buffer: &'a mut [u8],
1266 ) -> TeeResult<(ObjectInfo, &'a [u8])> {
1267 match self.enum_handles.get(&enumerator) {
1268 Some(state) => {
1269 let mut state = state.borrow_mut();
1270 let next = if state.id.is_none() {
1271 self.by_id.first_key_value()
1272 } else {
1273 let curr_id = state.id.as_ref().unwrap();
1277 self.by_id.range((Bound::Excluded(curr_id.clone()), Bound::Unbounded)).next()
1278 };
1279 if let Some((id, obj)) = next {
1280 assert!(id_buffer.len() >= id.len());
1281 let written = &mut id_buffer[..id.len()];
1282 written.copy_from_slice(id);
1283 state.id = Some(id.clone());
1284 Ok((obj.borrow().get_info(0, 0), written))
1285 } else {
1286 Err(Error::ItemNotFound)
1287 }
1288 }
1289 None => panic!("{enumerator:?} is not a valid enumerator handle"),
1290 }
1291 }
1292
1293 fn mint_handle(&mut self) -> ObjectHandle {
1294 let handle_value = self.next_handle_value;
1296 self.next_handle_value += 2;
1297 ObjectHandle::from_value(handle_value)
1298 }
1299
1300 fn mint_enumerator_handle(&mut self) -> ObjectEnumHandle {
1301 let handle_value = self.next_enum_handle_value;
1302 self.next_enum_handle_value += 1;
1303 ObjectEnumHandle::from_value(handle_value)
1304 }
1305}
1306
1307impl Storage {
1312 pub fn new() -> Self {
1313 Self {
1314 persistent_objects: PersistentObjects::new(),
1315 transient_objects: TransientObjects::new(),
1316 }
1317 }
1318
1319 pub fn get(&self, object: ObjectHandle) -> Rc<RefCell<dyn Object>> {
1320 if is_transient_handle(object) {
1321 self.transient_objects.by_handle.get(&object).unwrap().clone()
1322 } else {
1323 self.persistent_objects.by_handle.get(&object).unwrap().borrow().object.clone()
1324 }
1325 }
1326
1327 pub fn get_object_info(&self, object: ObjectHandle) -> ObjectInfo {
1331 if is_transient_handle(object) {
1332 self.transient_objects
1333 .get(object)
1334 .get_info(0, 0)
1335 } else {
1336 self.persistent_objects.get(object).get_info()
1337 }
1338 }
1339
1340 pub fn restrict_object_usage(&self, object: ObjectHandle, usage: Usage) {
1344 if is_transient_handle(object) {
1345 self.transient_objects.get_mut(object).restrict_usage(usage)
1346 } else {
1347 self.persistent_objects.get(object).object.borrow_mut().restrict_usage(usage)
1348 }
1349 }
1350}
1351
1352impl Storage {
1353 pub fn get_object_buffer_attribute(
1366 &self,
1367 object: ObjectHandle,
1368 attribute_id: AttributeId,
1369 buffer: &mut [u8],
1370 ) -> Result<usize, ErrorWithSize> {
1371 assert!(!attribute_id.value());
1372
1373 let copy_from_key = |obj: &dyn Object, buffer: &mut [u8]| -> Result<usize, ErrorWithSize> {
1374 if !attribute_id.public() {
1375 assert!(obj.usage().contains(Usage::EXTRACTABLE));
1376 }
1377
1378 let attr = obj.key().buffer_attribute(attribute_id);
1379 let bytes = match &attr {
1380 None => return Err(ErrorWithSize::new(Error::ItemNotFound)),
1381 Some(BufferAttribute::Slice(bytes)) => bytes,
1382 Some(BufferAttribute::Vector(bytes)) => bytes.as_slice(),
1383 };
1384 if buffer.len() < bytes.len() {
1385 Err(ErrorWithSize::short_buffer(bytes.len()))
1386 } else {
1387 let written = &mut buffer[..bytes.len()];
1388 written.copy_from_slice(bytes);
1389 Ok(written.len())
1390 }
1391 };
1392
1393 if is_transient_handle(object) {
1394 copy_from_key(self.transient_objects.get(object).deref(), buffer)
1395 } else {
1396 copy_from_key(
1397 self.persistent_objects.get(object).object.as_ref().borrow().deref(),
1398 buffer,
1399 )
1400 }
1401 }
1402
1403 pub fn get_object_value_attribute(
1411 &self,
1412 object: ObjectHandle,
1413 attribute_id: AttributeId,
1414 ) -> TeeResult<ValueFields> {
1415 assert!(!attribute_id.value());
1416
1417 let copy_from_key = |obj: &dyn Object| {
1418 if !attribute_id.public() {
1419 assert!(obj.usage().contains(Usage::EXTRACTABLE));
1420 }
1421 if let Some(value) = obj.key().value_attribute(attribute_id) {
1422 Ok(value)
1423 } else {
1424 Err(Error::ItemNotFound)
1425 }
1426 };
1427
1428 if is_transient_handle(object) {
1429 copy_from_key(self.transient_objects.get(object).deref())
1430 } else {
1431 copy_from_key(self.persistent_objects.get(object).object.borrow().deref())
1432 }
1433 }
1434
1435 pub fn close_object(&mut self, object: ObjectHandle) {
1439 if object.is_null() {
1440 return;
1441 }
1442
1443 if is_transient_handle(object) {
1444 self.transient_objects.free(object)
1445 } else {
1446 self.persistent_objects.close(object)
1447 }
1448 }
1449
1450 pub fn allocate_transient_object(
1455 &mut self,
1456 object_type: Type,
1457 max_size: u32,
1458 ) -> TeeResult<ObjectHandle> {
1459 self.transient_objects.allocate(object_type, max_size)
1460 }
1461
1462 pub fn free_transient_object(&mut self, object: ObjectHandle) {
1466 assert!(is_transient_handle(object));
1467 self.transient_objects.free(object)
1468 }
1469
1470 pub fn reset_transient_object(&mut self, object: ObjectHandle) {
1474 assert!(is_transient_handle(object));
1475 self.transient_objects.reset(object)
1476 }
1477
1478 pub fn populate_transient_object(
1484 &self,
1485 object: ObjectHandle,
1486 attrs: &[Attribute],
1487 ) -> TeeResult {
1488 assert!(is_transient_handle(object));
1489 self.transient_objects.populate(object, attrs)
1490 }
1491}
1492
1493pub fn init_ref_attribute(id: AttributeId, buffer: &mut [u8]) -> Attribute {
1494 assert!(id.memory_reference(), "Attribute ID {id:?} does not represent a memory reference");
1495 Attribute { id, content: BufferOrValue { memref: MemRef::from_mut_slice(buffer) } }
1496}
1497
1498pub fn init_value_attribute(id: AttributeId, value: ValueFields) -> Attribute {
1499 assert!(id.value(), "Attribute ID {id:?} does not represent value fields");
1500 Attribute { id, content: BufferOrValue { value } }
1501}
1502
1503impl Storage {
1504 pub fn copy_object_attributes(&mut self, _src: ObjectHandle, dest: ObjectHandle) -> TeeResult {
1505 assert!(is_transient_handle(dest));
1506 unimplemented!()
1507 }
1508
1509 pub fn generate_key(
1517 &mut self,
1518 object: ObjectHandle,
1519 key_size: u32,
1520 params: &[Attribute],
1521 ) -> TeeResult {
1522 self.transient_objects.generate_key(object, key_size, params)
1523 }
1524
1525 pub fn open_persistent_object(
1543 &mut self,
1544 storage: TeeStorage,
1545 id: &[u8],
1546 flags: HandleFlags,
1547 ) -> TeeResult<ObjectHandle> {
1548 if storage == TeeStorage::Private {
1549 self.persistent_objects.open(id, flags)
1550 } else {
1551 Err(Error::ItemNotFound)
1552 }
1553 }
1554
1555 pub fn create_persistent_object(
1565 &mut self,
1566 storage: TeeStorage,
1567 id: &[u8],
1568 flags: HandleFlags,
1569 attribute_src: ObjectHandle,
1570 initial_data: &[u8],
1571 ) -> TeeResult<ObjectHandle> {
1572 if storage != TeeStorage::Private {
1573 return Err(Error::ItemNotFound);
1574 }
1575
1576 let (key, usage, base_flags) = if attribute_src.is_null() {
1577 (Key::Data(NoKey {}), Usage::default(), HandleFlags::empty())
1578 } else if is_persistent_handle(attribute_src) {
1579 let view = self.persistent_objects.get(attribute_src);
1580 let obj = view.object.borrow();
1581 (obj.key.clone(), obj.usage, obj.base_flags)
1582 } else {
1583 unimplemented!();
1584 };
1585 let flags = base_flags.union(flags);
1586 self.persistent_objects.create(key, usage, flags, id, initial_data)
1587 }
1588
1589 pub fn close_and_delete_persistent_object(&mut self, object: ObjectHandle) -> TeeResult {
1594 assert!(is_persistent_handle(object));
1595 self.persistent_objects.close_and_delete(object)
1596 }
1597
1598 pub fn rename_persistent_object(&mut self, object: ObjectHandle, new_id: &[u8]) -> TeeResult {
1606 assert!(is_persistent_handle(object));
1607 self.persistent_objects.rename(object, new_id)
1608 }
1609
1610 pub fn allocate_persistent_object_enumerator(&mut self) -> ObjectEnumHandle {
1612 self.persistent_objects.allocate_enumerator()
1613 }
1614
1615 pub fn free_persistent_object_enumerator(&mut self, enumerator: ObjectEnumHandle) {
1619 self.persistent_objects.free_enumerator(enumerator)
1620 }
1621
1622 pub fn reset_persistent_object_enumerator(&mut self, enumerator: ObjectEnumHandle) {
1626 self.persistent_objects.reset_enumerator(enumerator)
1627 }
1628
1629 pub fn start_persistent_object_enumerator(
1636 &mut self,
1637 enumerator: ObjectEnumHandle,
1638 storage: TeeStorage,
1639 ) -> TeeResult {
1640 if storage == TeeStorage::Private {
1641 self.reset_persistent_object_enumerator(enumerator);
1642 Ok(())
1643 } else {
1644 Err(Error::ItemNotFound)
1645 }
1646 }
1647
1648 pub fn get_next_persistent_object<'a>(
1656 &self,
1657 enumerator: ObjectEnumHandle,
1658 id_buffer: &'a mut [u8],
1659 ) -> TeeResult<(ObjectInfo, &'a [u8])> {
1660 self.persistent_objects.get_next_object(enumerator, id_buffer)
1661 }
1662
1663 pub fn read_object_data<'a>(
1668 &self,
1669 object: ObjectHandle,
1670 buffer: &'a mut [u8],
1671 ) -> TeeResult<&'a [u8]> {
1672 assert!(is_persistent_handle(object));
1673 self.persistent_objects.get_mut(object).read_data(buffer)
1674 }
1675
1676 pub fn write_object_data(&self, object: ObjectHandle, buffer: &[u8]) -> TeeResult {
1687 assert!(is_persistent_handle(object));
1688 self.persistent_objects.get_mut(object).write_data(buffer)
1689 }
1690
1691 pub fn truncate_object_data(&self, object: ObjectHandle, size: usize) -> TeeResult {
1698 assert!(is_persistent_handle(object));
1699 self.persistent_objects.get(object).truncate_data(size)
1700 }
1701
1702 pub fn seek_data_object(
1710 &self,
1711 object: ObjectHandle,
1712 offset: isize,
1713 whence: Whence,
1714 ) -> TeeResult {
1715 assert!(is_persistent_handle(object));
1716 self.persistent_objects.get_mut(object).seek_data(offset, whence)
1717 }
1718}
1719
1720