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