Skip to main content

ic_storage/memory/
mod.rs

1//! Storage memory contract and Platform-backed canister storage.
2cfg_select! {
3    target_arch = "wasm32" => {
4        mod wasm;
5        pub use wasm::DefaultMemoryImpl;
6    }
7    _ => {
8        /// Native default backing for fixture and host integration.
9        pub type DefaultMemoryImpl = VectorMemory;
10    }
11}
12
13use crate::WASM_PAGE_SIZE_BYTES;
14
15///
16/// Memory
17///
18/// Page-addressed storage with initialized reads and nonshrinking capacity.
19/// Implementations validate complete access ranges before touching backing bytes.
20///
21pub trait Memory {
22    /// Returns the number of complete accessible Wasm pages.
23    fn size(&self) -> u64;
24
25    /// Adds zero-filled pages, returning the previous size or `-1` on refusal.
26    /// Refusal leaves the existing bytes and extent unchanged.
27    fn grow(&self, pages: u64) -> i64;
28
29    /// Copies the selected backing bytes into an initialized destination.
30    ///
31    /// # Panics
32    ///
33    /// Panics or traps if the complete range is outside the backing.
34    fn read(&self, offset: u64, bytes: &mut [u8]);
35
36    /// Replaces the selected backing bytes.
37    ///
38    /// # Panics
39    ///
40    /// Panics or traps if the complete range is outside the backing.
41    fn write(&self, offset: u64, bytes: &[u8]);
42}
43
44impl<M: Memory + ?Sized> Memory for Rc<M> {
45    fn size(&self) -> u64 {
46        (**self).size()
47    }
48
49    fn grow(&self, pages: u64) -> i64 {
50        (**self).grow(pages)
51    }
52
53    fn read(&self, offset: u64, bytes: &mut [u8]) {
54        (**self).read(offset, bytes);
55    }
56
57    fn write(&self, offset: u64, bytes: &[u8]) {
58        (**self).write(offset, bytes);
59    }
60}
61
62impl<M: Memory + ?Sized> Memory for &M {
63    fn size(&self) -> u64 {
64        (**self).size()
65    }
66
67    fn grow(&self, pages: u64) -> i64 {
68        (**self).grow(pages)
69    }
70
71    fn read(&self, offset: u64, bytes: &mut [u8]) {
72        (**self).read(offset, bytes);
73    }
74
75    fn write(&self, offset: u64, bytes: &[u8]) {
76        (**self).write(offset, bytes);
77    }
78}
79
80///
81/// `VectorMemory`
82///
83/// Shared native byte backing. Clones refer to the same physical bytes.
84///
85pub type VectorMemory = Rc<RefCell<Vec<u8>>>;
86
87impl Memory for RefCell<Vec<u8>> {
88    fn size(&self) -> u64 {
89        u64::try_from(self.borrow().len()).expect("native byte length fits u64")
90            / WASM_PAGE_SIZE_BYTES
91    }
92
93    fn grow(&self, pages: u64) -> i64 {
94        let mut bytes = self.borrow_mut();
95        let length = u64::try_from(bytes.len()).expect("native byte length fits u64");
96        let old_pages = length / WASM_PAGE_SIZE_BYTES;
97        let Ok(previous) = i64::try_from(old_pages) else {
98            return -1;
99        };
100        if pages == 0 {
101            return previous;
102        }
103        // An externally supplied partial page is not advertised or completed
104        // implicitly: its tail remains the caller's data, outside this extent.
105        if !length.is_multiple_of(WASM_PAGE_SIZE_BYTES) {
106            return -1;
107        }
108        let Some(new_length) = old_pages
109            .checked_add(pages)
110            .and_then(|total| total.checked_mul(WASM_PAGE_SIZE_BYTES))
111            .and_then(|total| usize::try_from(total).ok())
112        else {
113            return -1;
114        };
115        let additional = new_length - bytes.len();
116        if bytes.try_reserve_exact(additional).is_err() {
117            return -1;
118        }
119        bytes.resize(new_length, 0);
120        previous
121    }
122
123    fn read(&self, offset: u64, bytes: &mut [u8]) {
124        let backing = self.borrow();
125        let range = native_range(offset, bytes.len(), backing.len());
126        bytes.copy_from_slice(&backing[range]);
127    }
128
129    fn write(&self, offset: u64, bytes: &[u8]) {
130        let mut backing = self.borrow_mut();
131        let range = native_range(offset, bytes.len(), backing.len());
132        backing[range].copy_from_slice(bytes);
133    }
134}
135
136// Admission precedes every copy, so overflow and out-of-range failures cannot
137// leave a partially modified native destination or backing.
138fn admit_range(offset: u64, count: usize, pages: u64) {
139    let extent = pages
140        .checked_mul(WASM_PAGE_SIZE_BYTES)
141        .expect("memory extent overflow");
142    let count = u64::try_from(count).expect("memory access length overflow");
143    let end = offset.checked_add(count).expect("memory access overflow");
144    assert!(end <= extent, "memory access outside complete pages");
145}
146
147fn native_range(offset: u64, count: usize, length: usize) -> std::ops::Range<usize> {
148    let pages = u64::try_from(length).expect("native byte length fits u64") / WASM_PAGE_SIZE_BYTES;
149    admit_range(offset, count, pages);
150    let start = usize::try_from(offset).expect("admitted native offset");
151    start..start + count
152}
153
154use std::{cell::RefCell, rc::Rc, sync::Arc};
155
156///
157/// BackingIdentity
158/// Identity of a physical backing allocation, shared by all of its wrappers.
159/// This is host custody metadata, not a virtual memory ID or durable record.
160///
161
162#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
163pub struct BackingIdentity(usize);
164
165impl BackingIdentity {
166    /// Identify an Rc-owned backing. Its allocation must remain alive through
167    /// every runtime/handle using this identity. Identify the underlying backing,
168    /// not a newly allocated wrapper or an address inside a growable byte buffer.
169    #[must_use]
170    pub fn of_rc<T: ?Sized>(backing: &Rc<T>) -> Self {
171        Self(Rc::as_ptr(backing).cast::<()>() as usize)
172    }
173
174    /// Identify an Arc-owned backing under the same contract as [`Self::of_rc`].
175    #[must_use]
176    pub fn of_arc<T: ?Sized>(backing: &Arc<T>) -> Self {
177        Self(Arc::as_ptr(backing).cast::<()>() as usize)
178    }
179}