1mod admission;
2#[cfg(test)]
3mod admission_tests;
4mod adoption;
5#[cfg(test)]
6mod adoption_tests;
7mod allocations;
8mod backing;
9mod config;
10mod diagnostics;
11mod error;
12mod layout;
13mod policy;
14
15#[cfg(test)]
16mod allocation_tests;
17#[cfg(test)]
18mod growth_tests;
19#[cfg(test)]
20#[expect(
21 unsafe_code,
22 reason = "exercise raw reads with valid uninitialized destinations"
23)]
24mod read_tests;
25#[cfg(test)]
26mod request_tests;
27#[cfg(test)]
28mod tests;
29
30pub use admission::{BootstrapAdmission, BootstrapAdmissionError};
31pub use adoption::RuntimeAdoptionError;
32
33pub use allocations::{
34 AllocationBinding, MemoryAllocation, MemoryAllocationSummary, MemoryAllocations,
35 MemoryBindingSummary,
36};
37pub use backing::RuntimeMemory;
38pub use config::MemoryManagerConfig;
39pub use error::{
40 MemoryResolutionError, RuntimeBootstrapError, RuntimeConstructionError, RuntimeDiagnosticError,
41 RuntimeGrowError, RuntimeOpenError,
42};
43pub use layout::MemoryManagerLayoutError;
44pub use policy::GenericAllocationPolicy;
45
46use crate::{
47 CommittedAllocations, LedgerCommitStore, PolicyIdentity, RuntimeBootstrapPolicy,
48 STABLE_CELL_VALUE_OFFSET, StableCellLedgerError,
49 requests::SealedDeclarationSnapshot,
50 slot::MEMORY_MANAGER_LEDGER_ID,
51 stable_cell::{EncodedLedgerRecord, decode_stable_cell_commit_store_from_memory},
52};
53use ic_stable_structures::{
54 Cell, Memory,
55 memory_manager::{MemoryId, MemoryManager},
56};
57
58use std::rc::Rc;
59
60enum RuntimeLifecycle {
61 Unbootstrapped,
62 Bootstrapped {
63 committed_allocations: CommittedAllocations,
64 binding: RuntimeBootstrapBinding,
65 },
66}
67
68struct RuntimeBootstrapBinding {
69 source: SealedDeclarationSnapshot,
70 policy_identity: PolicyIdentity,
71 pool: crate::MemoryAllocationPool,
72}
73
74pub struct MemoryRuntime<M: Memory> {
100 memory_manager: MemoryManager<Rc<M>>,
101 growth: Rc<backing::GrowthState<M>>,
104 lifecycle: RuntimeLifecycle,
105}
106
107impl<M: Memory> MemoryRuntime<M> {
108 pub fn new(memory: M) -> Result<Self, RuntimeConstructionError> {
128 Self::construct(memory, None)
129 }
130
131 pub fn new_with_config(
140 memory: M,
141 config: MemoryManagerConfig,
142 ) -> Result<Self, RuntimeConstructionError> {
143 Self::construct(memory, Some(config))
144 }
145
146 fn construct(
147 memory: M,
148 requested: Option<MemoryManagerConfig>,
149 ) -> Result<Self, RuntimeConstructionError> {
150 if cfg!(target_endian = "big") {
151 return Err(MemoryManagerLayoutError::UnsupportedByteOrder.into());
152 }
153 let (bucket_size_pages, allocated_buckets) = if memory.size() == 0 {
154 if memory.grow(1) == -1 {
158 return Err(RuntimeGrowError::BackingRefused {
159 additional_pages: 1,
160 }
161 .into());
162 }
163 (requested.unwrap_or_default().bucket_size_pages(), 0)
164 } else {
165 let measured = layout::read(&memory)?;
166 let actual = measured.bucket_pages;
167 if let Some(config) = requested {
168 check_bucket_size(actual, config)?;
169 }
170 (actual, measured.allocated_buckets)
171 };
172 let backing = Rc::new(memory);
173 let growth = Rc::new(backing::GrowthState {
174 backing: Rc::clone(&backing),
175 bucket_size_pages,
176 allocated_buckets: std::cell::RefCell::new(allocated_buckets),
177 open_slots: [const { std::cell::Cell::new(0) }; 4],
178 });
179 Ok(Self {
180 memory_manager: MemoryManager::init_with_bucket_size(
181 Rc::clone(&backing),
182 bucket_size_pages,
183 ),
184 growth,
185 lifecycle: RuntimeLifecycle::Unbootstrapped,
186 })
187 }
188
189 #[must_use]
191 pub fn memory_manager_config(&self) -> MemoryManagerConfig {
192 MemoryManagerConfig::from_validated(self.growth.bucket_size_pages)
194 }
195
196 #[must_use]
198 pub const fn is_bootstrapped(&self) -> bool {
199 matches!(self.lifecycle, RuntimeLifecycle::Bootstrapped { .. })
200 }
201
202 pub fn bootstrap<P: RuntimeBootstrapPolicy>(
217 &mut self,
218 declarations: &SealedDeclarationSnapshot,
219 pool: &crate::MemoryAllocationPool,
220 policy: &P,
221 ) -> Result<&CommittedAllocations, RuntimeBootstrapError<P::Error>> {
222 let policy_identity = policy.runtime_bootstrap_identity();
223 match &self.lifecycle {
224 RuntimeLifecycle::Unbootstrapped => {
225 self.bootstrap_unbootstrapped(declarations, pool, policy, policy_identity)?;
226 }
227 RuntimeLifecycle::Bootstrapped { binding, .. } => {
228 binding.validate(declarations, pool, &policy_identity)?;
229 }
230 }
231 match &self.lifecycle {
232 RuntimeLifecycle::Bootstrapped {
233 committed_allocations,
234 ..
235 } => Ok(committed_allocations),
236 RuntimeLifecycle::Unbootstrapped => {
237 unreachable!("successful bootstrap publishes committed allocations")
238 }
239 }
240 }
241
242 fn validate_pool_custody(
243 &self,
244 occupied: &[bool; crate::constants::MAX_ALLOCATIONS],
245 pool: &crate::MemoryAllocationPool,
246 ) -> Result<(), super::MemoryResolutionError> {
247 for id in 0..crate::MEMORY_MANAGER_INVALID_ID {
248 if pool.contains(id) && self.memory_size_pages(id) != 0 && !occupied[usize::from(id)] {
249 return Err(super::MemoryResolutionError::UnmanagedAllocation { id });
250 }
251 }
252 Ok(())
253 }
254
255 fn bootstrap_unbootstrapped<P: RuntimeBootstrapPolicy>(
256 &mut self,
257 declarations: &SealedDeclarationSnapshot,
258 pool: &crate::MemoryAllocationPool,
259 policy: &P,
260 policy_identity: PolicyIdentity,
261 ) -> Result<(), RuntimeBootstrapError<P::Error>> {
262 let mut memory = self
263 .memory(MEMORY_MANAGER_LEDGER_ID)
264 .expect("governance memory is not publicly leasable");
265 let mut record = decode_stable_cell_commit_store_from_memory(&memory)?;
266 let recovered = record.recover_or_genesis()?;
267 let occupied = recovered.ledger().occupied_slots();
268 self.validate_pool_custody(&occupied, pool)?;
269 if memory.size() == 0 {
270 memory = write_ledger_cell(memory, &LedgerCommitStore::default())?;
273 }
274 let mut admission = BootstrapAdmission::new(recovered.ledger(), declarations, pool);
275 let preparation = policy.prepare_bootstrap(&mut admission);
276 let historical = admission.complete()?;
277 preparation.map_err(RuntimeBootstrapError::AdmissionPolicy)?;
278 let resolved = declarations.resolve(&recovered, &occupied, historical, pool)?;
279 let (generation, resolved) = {
280 let (staged, resolved) = crate::ledger::stage_generation(recovered, resolved, policy)?;
281 record.commit_generation(&staged)?;
282 (staged.current_generation(), resolved)
283 };
284 drop(write_ledger_cell(memory, &record)?);
285 let committed = CommittedAllocations::from_persisted(resolved, generation);
286 self.lifecycle = RuntimeLifecycle::Bootstrapped {
287 committed_allocations: committed,
288 binding: RuntimeBootstrapBinding {
289 source: declarations.clone(),
290 policy_identity,
291 pool: pool.clone(),
292 },
293 };
294 Ok(())
295 }
296
297 pub const fn committed_allocations(&self) -> Result<&CommittedAllocations, RuntimeOpenError> {
299 match &self.lifecycle {
300 RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
301 RuntimeLifecycle::Bootstrapped {
302 committed_allocations,
303 ..
304 } => Ok(committed_allocations),
305 }
306 }
307
308 pub fn open_memory(&self, stable_key: &str) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
313 self.memory(self.memory_id(stable_key)?)
314 }
315
316 pub fn memory_id(&self, stable_key: &str) -> Result<u8, RuntimeOpenError> {
319 crate::key::validate(stable_key)?;
320 if crate::is_ic_memory_stable_key(stable_key) {
321 return Err(RuntimeOpenError::ReservedStableKey {
322 stable_key: stable_key.to_string(),
323 });
324 }
325 let declaration = crate::capability::declaration_for_key(
326 self.committed_allocations()?.declarations(),
327 stable_key,
328 )
329 .ok_or_else(|| RuntimeOpenError::StableKeyNotCommitted(stable_key.to_string()))?;
330 Ok(declaration.slot().id())
331 }
332
333 fn memory(&self, id: u8) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
334 let word = &self.growth.open_slots[usize::from(id / 64)];
335 let mask = 1_u64 << (id % 64);
336 if word.get() & mask != 0 {
337 return Err(RuntimeOpenError::AlreadyOpen { id });
338 }
339 let memory = self.memory_manager.get(MemoryId::new(id));
340 word.set(word.get() | mask);
341 Ok(RuntimeMemory {
342 memory,
343 growth: Rc::clone(&self.growth),
344 id,
345 })
346 }
347
348 fn memory_size_pages(&self, id: u8) -> u64 {
350 self.memory_manager.get(MemoryId::new(id)).size()
351 }
352
353 fn ledger_record_from_memory(&self) -> Result<LedgerCommitStore, StableCellLedgerError> {
354 let memory = self
357 .memory_manager
358 .get(MemoryId::new(MEMORY_MANAGER_LEDGER_ID));
359 decode_stable_cell_commit_store_from_memory(&memory)
360 }
361}
362
363impl RuntimeBootstrapBinding {
364 fn validate<P>(
365 &self,
366 declarations: &SealedDeclarationSnapshot,
367 pool: &crate::MemoryAllocationPool,
368 policy_identity: &PolicyIdentity,
369 ) -> Result<(), RuntimeBootstrapError<P>> {
370 if &self.source != declarations {
371 return Err(RuntimeBootstrapError::DeclarationSnapshotMismatch);
372 }
373 if &self.pool != pool {
374 return Err(RuntimeBootstrapError::AllocationPoolMismatch);
375 }
376 if &self.policy_identity != policy_identity {
377 return Err(RuntimeBootstrapError::PolicyIdentityMismatch {
378 established: self.policy_identity,
379 requested: *policy_identity,
380 });
381 }
382 Ok(())
383 }
384}
385
386fn write_ledger_cell<M: Memory, P>(
387 memory: RuntimeMemory<M>,
388 record: &LedgerCommitStore,
389) -> Result<RuntimeMemory<M>, RuntimeBootstrapError<P>> {
390 let encoded = EncodedLedgerRecord::new(record).map_err(|value_size| {
391 RuntimeBootstrapError::StableCellLedgerWriteTooLarge { value_size }
392 })?;
393 let value_size = encoded.len();
394 let required_bytes = STABLE_CELL_VALUE_OFFSET + value_size as u64;
396 let available_bytes = memory.size().saturating_mul(crate::WASM_PAGE_SIZE_BYTES);
397 if required_bytes > available_bytes {
398 let grow_by = (required_bytes - available_bytes).div_ceil(crate::WASM_PAGE_SIZE_BYTES);
399 memory.grow(grow_by)?;
400 }
401 Ok(Cell::new(memory, encoded).into_memory())
402}
403
404const fn check_bucket_size(
405 actual: u16,
406 requested: MemoryManagerConfig,
407) -> Result<(), RuntimeConstructionError> {
408 if actual != requested.bucket_size_pages() {
409 return Err(RuntimeConstructionError::BucketSizeMismatch {
410 persisted: actual,
411 requested: requested.bucket_size_pages(),
412 });
413 }
414 Ok(())
415}