Skip to main content

ic_storage/runtime/custody/
mod.rs

1//! Process-local backing claims, retained by every issued runtime handle.
2use super::RuntimeConstructionError;
3use crate::{BackingIdentity, Memory, VectorMemory};
4use std::{
5    collections::BTreeSet,
6    rc::Rc,
7    sync::{Mutex, PoisonError},
8};
9
10/// Host boundary for a backing whose aliases can be identified consistently.
11///
12/// All wrappers and clones over the same physical backing must return the same
13/// stable identity; independent backings must have different identities. Keep
14/// its identity allocation alive for the backing's complete runtime/handle
15/// lifetime. A wrapper delegates to its underlying backing's implementation.
16/// Obtaining the identity must not read, grow or write backing memory or create
17/// a manager/runtime; use a retained heap identity, not persisted contents.
18/// Implementing Memory alone does not establish this custody contract. Raw IO
19/// and unmanaged managers over a claimed backing remain prohibited; this is not
20/// an isolation boundary against arbitrary linked code or a dishonest backing.
21///
22pub trait MemoryBacking: Memory {
23    /// Return the physical backing identity under the trait's host contract.
24    fn backing_identity(&self) -> BackingIdentity;
25}
26
27impl MemoryBacking for VectorMemory {
28    fn backing_identity(&self) -> BackingIdentity {
29        BackingIdentity::of_rc(self)
30    }
31}
32
33impl<M: MemoryBacking> MemoryBacking for Rc<M> {
34    fn backing_identity(&self) -> BackingIdentity {
35        self.as_ref().backing_identity()
36    }
37}
38
39static CLAIMS: Mutex<BTreeSet<BackingIdentity>> = Mutex::new(BTreeSet::new());
40
41fn with_claims<T>(operation: impl FnOnce(&mut BTreeSet<BackingIdentity>) -> T) -> T {
42    let mut claims = CLAIMS.lock().unwrap_or_else(PoisonError::into_inner);
43
44    operation(&mut claims)
45}
46
47pub(super) struct BackingClaim(BackingIdentity);
48
49impl BackingClaim {
50    pub fn acquire(memory: &impl MemoryBacking) -> Result<Self, RuntimeConstructionError> {
51        let identity = memory.backing_identity();
52
53        if with_claims(|claims| claims.insert(identity)) {
54            Ok(Self(identity))
55        } else {
56            Err(RuntimeConstructionError::BackingAlreadyClaimed)
57        }
58    }
59}
60
61impl Drop for BackingClaim {
62    fn drop(&mut self) {
63        with_claims(|claims| claims.remove(&self.0));
64    }
65}