1mod admission;
2#[cfg(test)]
3mod admission_tests;
4mod adoption;
5#[cfg(test)]
6mod adoption_tests;
7mod allocations;
8mod backing;
9mod config;
10mod custody;
11mod diagnostics;
12mod error;
13#[cfg(any(test, feature = "test-support"))]
14#[path = "../testing/diagnostics.rs"]
15pub mod fixture_diagnostics;
16#[cfg(test)]
17mod fixtures;
18mod layout;
19mod policy;
20
21#[cfg(all(test, not(target_arch = "wasm32")))]
22mod allocation_tests;
23#[cfg(test)]
24mod custody_tests;
25#[cfg(test)]
26mod growth_tests;
27#[cfg(test)]
28#[expect(
29 unsafe_code,
30 reason = "exercise raw reads with valid uninitialized destinations"
31)]
32mod read_tests;
33#[cfg(test)]
34mod request_tests;
35#[cfg(test)]
36mod tests;
37
38pub use admission::{BootstrapAdmission, BootstrapAdmissionError};
39pub use adoption::RuntimeAdoptionError;
40
41pub use allocations::{
42 MemoryAllocation, MemoryAllocationSummary, MemoryAllocations, MemoryBindingSummary,
43};
44pub use backing::RuntimeMemory;
45pub use config::MemoryManagerConfig;
46pub use custody::{BackingIdentity, MemoryBacking};
47pub use error::{
48 MemoryResolutionError, RuntimeBootstrapError, RuntimeConstructionError, RuntimeDiagnosticError,
49 RuntimeGrowError, RuntimeOpenError,
50};
51pub use layout::MemoryManagerLayoutError;
52pub use policy::GenericAllocationPolicy;
53
54use crate::{
55 LedgerCommitStore, PolicyIdentity, RuntimeBootstrapPolicy, STABLE_CELL_VALUE_OFFSET,
56 StableCellLedgerError,
57 requests::SealedDeclarationSnapshot,
58 slot::MEMORY_MANAGER_LEDGER_ID,
59 stable_cell::{EncodedLedgerRecord, decode_stable_cell_commit_store_from_memory},
60};
61use ic_platform::stable_structures::{
62 Cell, Memory,
63 memory_manager::{MemoryId, MemoryManager},
64};
65
66use std::rc::Rc;
67
68enum RuntimeLifecycle {
69 Unbootstrapped,
70 Bootstrapped {
71 allocations: Vec<crate::AllocationDeclaration>,
72 generation: u64,
73 binding: RuntimeBootstrapBinding,
74 },
75}
76
77struct RuntimeBootstrapBinding {
78 source: SealedDeclarationSnapshot,
79 policy_identity: PolicyIdentity,
80 pool: crate::MemoryAllocationPool,
81}
82
83pub struct MemoryRuntime<M: Memory> {
110 memory_manager: MemoryManager<Rc<M>>,
111 growth: Rc<backing::GrowthState<M>>,
114 lifecycle: RuntimeLifecycle,
115}
116
117impl<M: Memory> MemoryRuntime<M> {
118 pub fn new(memory: M) -> Result<Self, RuntimeConstructionError>
140 where
141 M: MemoryBacking,
142 {
143 Self::construct(memory, None)
144 }
145
146 pub fn new_with_config(
155 memory: M,
156 config: MemoryManagerConfig,
157 ) -> Result<Self, RuntimeConstructionError>
158 where
159 M: MemoryBacking,
160 {
161 Self::construct(memory, Some(config))
162 }
163
164 fn construct(
165 memory: M,
166 requested: Option<MemoryManagerConfig>,
167 ) -> Result<Self, RuntimeConstructionError>
168 where
169 M: MemoryBacking,
170 {
171 let claim = custody::BackingClaim::acquire(&memory)?;
172 if cfg!(target_endian = "big") {
173 return Err(MemoryManagerLayoutError::UnsupportedByteOrder.into());
174 }
175 let bucket_size_pages = if memory.size() == 0 {
176 if memory.grow(1) == -1 {
180 return Err(RuntimeGrowError::BackingRefused {
181 additional_pages: 1,
182 }
183 .into());
184 }
185 requested.unwrap_or_default().bucket_size_pages()
186 } else {
187 let measured = layout::read(&memory)?;
188 let actual = measured.bucket_pages;
189 if let Some(config) = requested {
190 check_bucket_size(actual, config)?;
191 }
192 actual
193 };
194 let backing = Rc::new(memory);
195 let memory_manager =
196 MemoryManager::init_with_bucket_size(Rc::clone(&backing), bucket_size_pages);
197 let growth = Rc::new(backing::GrowthState {
198 backing: Rc::clone(&backing),
199 bucket_size_pages,
200 authority: std::cell::RefCell::new(layout::ManagerAuthority::capture(backing.as_ref())),
201 _claim: claim,
202 open_slots: [const { std::cell::Cell::new(0) }; 4],
203 });
204 Ok(Self {
205 memory_manager,
206 growth,
207 lifecycle: RuntimeLifecycle::Unbootstrapped,
208 })
209 }
210
211 #[must_use]
213 pub fn memory_manager_config(&self) -> MemoryManagerConfig {
214 MemoryManagerConfig::from_validated(self.growth.bucket_size_pages)
216 }
217
218 #[must_use]
220 pub const fn is_bootstrapped(&self) -> bool {
221 matches!(self.lifecycle, RuntimeLifecycle::Bootstrapped { .. })
222 }
223
224 pub fn bootstrap<P: RuntimeBootstrapPolicy>(
239 &mut self,
240 declarations: &SealedDeclarationSnapshot,
241 pool: &crate::MemoryAllocationPool,
242 policy: &P,
243 ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
244 match &self.lifecycle {
245 RuntimeLifecycle::Unbootstrapped => self.bootstrap_unbootstrapped(
246 declarations,
247 pool,
248 policy,
249 policy.runtime_bootstrap_identity(),
250 ),
251 RuntimeLifecycle::Bootstrapped { .. } => {
252 self.verify_bootstrap(declarations, pool, policy)
253 }
254 }
255 }
256
257 pub fn verify_bootstrap<P: RuntimeBootstrapPolicy>(
266 &self,
267 declarations: &SealedDeclarationSnapshot,
268 pool: &crate::MemoryAllocationPool,
269 policy: &P,
270 ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
271 let RuntimeLifecycle::Bootstrapped {
272 binding,
273 generation,
274 ..
275 } = &self.lifecycle
276 else {
277 return Err(RuntimeBootstrapError::NotBootstrapped);
278 };
279 binding.validate(declarations, pool, &policy.runtime_bootstrap_identity())?;
280 Ok(*generation)
281 }
282
283 fn validate_pool_custody(
284 &self,
285 occupied: &[bool; crate::constants::MAX_ALLOCATIONS],
286 pool: &crate::MemoryAllocationPool,
287 ) -> Result<(), super::MemoryResolutionError> {
288 for id in 0..crate::MEMORY_MANAGER_INVALID_ID {
289 if pool.contains(id) && self.memory_size_pages(id) != 0 && !occupied[usize::from(id)] {
290 return Err(super::MemoryResolutionError::UnmanagedAllocation { id });
291 }
292 }
293 Ok(())
294 }
295
296 fn bootstrap_unbootstrapped<P: RuntimeBootstrapPolicy>(
297 &mut self,
298 declarations: &SealedDeclarationSnapshot,
299 pool: &crate::MemoryAllocationPool,
300 policy: &P,
301 policy_identity: PolicyIdentity,
302 ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
303 self.growth.verify()?;
304 let mut memory = self
305 .memory(MEMORY_MANAGER_LEDGER_ID)
306 .expect("governance memory is not publicly leasable");
307 let mut record = decode_stable_cell_commit_store_from_memory(&memory)?;
308 let recovered = record.recover_or_genesis()?;
309 let occupied = recovered.ledger().occupied_slots();
310 self.validate_pool_custody(&occupied, pool)?;
311 if memory.size() == 0 {
312 memory = write_ledger_cell(memory, &LedgerCommitStore::default())?;
315 }
316 let mut admission = BootstrapAdmission::new(recovered.ledger(), declarations, pool);
317 let preparation = policy.prepare_bootstrap(&mut admission);
318 let historical = admission.complete()?;
319 preparation.map_err(RuntimeBootstrapError::AdmissionPolicy)?;
320 let resolved = declarations.resolve(&recovered, &occupied, historical, pool)?;
321 let (generation, resolved) = {
322 let (staged, resolved) = crate::ledger::stage_generation(recovered, resolved, policy)?;
323 record.commit_generation(&staged)?;
324 (staged.current_generation(), resolved)
325 };
326 drop(write_ledger_cell(memory, &record)?);
327 let mut allocations = resolved;
329 allocations.retain(|declaration| {
330 !crate::is_ic_memory_stable_key(declaration.stable_key().as_str())
331 });
332 self.lifecycle = RuntimeLifecycle::Bootstrapped {
333 allocations,
334 generation,
335 binding: RuntimeBootstrapBinding {
336 source: declarations.clone(),
337 policy_identity,
338 pool: pool.clone(),
339 },
340 };
341 Ok(generation)
342 }
343
344 pub fn committed_allocations(
347 &self,
348 ) -> Result<&[crate::AllocationDeclaration], RuntimeOpenError> {
349 match &self.lifecycle {
350 RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
351 RuntimeLifecycle::Bootstrapped { allocations, .. } => Ok(allocations),
352 }
353 }
354
355 pub const fn committed_generation(&self) -> Result<u64, RuntimeOpenError> {
357 match &self.lifecycle {
358 RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
359 RuntimeLifecycle::Bootstrapped { generation, .. } => Ok(*generation),
360 }
361 }
362
363 pub const fn allocation_pool(&self) -> Result<&crate::MemoryAllocationPool, RuntimeOpenError> {
366 match &self.lifecycle {
367 RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
368 RuntimeLifecycle::Bootstrapped { binding, .. } => Ok(&binding.pool),
369 }
370 }
371
372 pub fn open_memory(&self, stable_key: &str) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
379 self.memory(self.memory_id(stable_key)?)
380 }
381
382 pub fn memory_id(&self, stable_key: &str) -> Result<u8, RuntimeOpenError> {
385 crate::key::validate(stable_key)?;
386 if crate::is_ic_memory_stable_key(stable_key) {
387 return Err(RuntimeOpenError::ReservedStableKey {
388 stable_key: stable_key.to_string(),
389 });
390 }
391 let declaration =
392 crate::declaration::declaration_for_key(self.committed_allocations()?, stable_key)
393 .ok_or_else(|| RuntimeOpenError::StableKeyNotCommitted(stable_key.to_string()))?;
394 Ok(declaration.slot().id())
395 }
396
397 fn memory(&self, id: u8) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
398 let word = &self.growth.open_slots[usize::from(id / 64)];
399 let mask = 1_u64 << (id % 64);
400 if word.get() & mask != 0 {
401 return Err(RuntimeOpenError::AlreadyOpen { id });
402 }
403 self.growth.verify()?;
404 let memory = self.memory_manager.get(MemoryId::new(id));
405 word.set(word.get() | mask);
406 Ok(RuntimeMemory {
407 memory,
408 growth: Rc::clone(&self.growth),
409 id,
410 })
411 }
412
413 fn memory_size_pages(&self, id: u8) -> u64 {
415 self.memory_manager.get(MemoryId::new(id)).size()
416 }
417
418 fn ledger_record_from_memory(&self) -> Result<LedgerCommitStore, StableCellLedgerError> {
419 let memory = self
422 .memory_manager
423 .get(MemoryId::new(MEMORY_MANAGER_LEDGER_ID));
424 decode_stable_cell_commit_store_from_memory(&memory)
425 }
426}
427
428impl RuntimeBootstrapBinding {
429 fn validate<P>(
430 &self,
431 declarations: &SealedDeclarationSnapshot,
432 pool: &crate::MemoryAllocationPool,
433 policy_identity: &PolicyIdentity,
434 ) -> Result<(), RuntimeBootstrapError<P>> {
435 if &self.source != declarations {
436 return Err(RuntimeBootstrapError::DeclarationSnapshotMismatch);
437 }
438 if &self.pool != pool {
439 return Err(RuntimeBootstrapError::AllocationPoolMismatch);
440 }
441 if &self.policy_identity != policy_identity {
442 return Err(RuntimeBootstrapError::PolicyIdentityMismatch {
443 established: self.policy_identity,
444 requested: *policy_identity,
445 });
446 }
447 Ok(())
448 }
449}
450
451fn write_ledger_cell<M: Memory, P>(
452 memory: RuntimeMemory<M>,
453 record: &LedgerCommitStore,
454) -> Result<RuntimeMemory<M>, RuntimeBootstrapError<P>> {
455 let encoded = EncodedLedgerRecord::new(record).map_err(|value_size| {
456 RuntimeBootstrapError::StableCellLedgerWriteTooLarge { value_size }
457 })?;
458 let value_size = encoded.len();
459 let required_bytes = STABLE_CELL_VALUE_OFFSET + value_size as u64;
461 let available_bytes = memory.size().saturating_mul(crate::WASM_PAGE_SIZE_BYTES);
462 if required_bytes > available_bytes {
463 let grow_by = (required_bytes - available_bytes).div_ceil(crate::WASM_PAGE_SIZE_BYTES);
464 memory.grow(grow_by)?;
465 }
466 Ok(Cell::new(memory, encoded).into_memory())
467}
468
469const fn check_bucket_size(
470 actual: u16,
471 requested: MemoryManagerConfig,
472) -> Result<(), RuntimeConstructionError> {
473 if actual != requested.bucket_size_pages() {
474 return Err(RuntimeConstructionError::BucketSizeMismatch {
475 persisted: actual,
476 requested: requested.bucket_size_pages(),
477 });
478 }
479 Ok(())
480}