memory.rs
cdk-rsx/crates/cdk-rsx-platform/src/memory.rs
1//! Byte backings and sparse retained loans, independent of the module engine.2mod error;3pub mod page_pool;4mod region;5pub use error::{MemoryError, MemoryResult};6use error::{MemoryError as Error, MemoryResult as Result};7pub use region::{RetainedBounds, RetainedRegion, RetainedRegionMut};89/// A physical byte address space with pinned, independently owned Store windows.10/// Growing initializes new bytes to zero; releasing a Store run may return it11/// to another owner without shrinking the physical address high-water.12/// Mutation failure aborts execution; the host owns rollback. Native backends13/// used outside tests must supply an equivalent boundary or terminate on failure.14/// This trait does not promise power-loss durability for native files.15///16/// # Safety17///18/// This value owns exclusive authority over its Store windows for its lifetime.19/// A sparse backend may share its physical image with disjoint runtime pages;20/// its byte operations and region loans must reject those holes. Store pages21/// stay pinned across calls until explicit whole-extent release. Their payload22/// bytes, lengths and allocation identity cannot change23/// through another live value, shared alias, raw API or interior-mutable handle.24/// A wrapper must preserve that authority; `Clone` may copy the image into an25/// independent backing, but must not create another writer to the same bytes.26/// Sharing counters or failure controls is allowed when they cannot mutate the27/// backing outside its mutable methods. The owning client must end its loans before returning the backing capability.28///29/// Successful reads and byte loans must faithfully expose initialized bytes at30/// the requested in-bounds addresses. Successful writes change exactly their31/// range; growth preserves old bytes and zeroes the newly admitted range. No32/// other owner changes live Store bytes. Claims may initialize newly acquired33/// runs; releases end Store authority over those bytes. Direct loans obey their documented34/// lifetimes, bounds and aliasing rules. A mutation failure must follow the35/// host's abort and whole-execution restoration boundary before reuse.36///37/// Store may reuse checked metadata between synchronous scopes under this38/// authority. Backend authors must not implement this trait for an unguarded39/// shared address space, even when each individual operation uses a `RefCell`.40///41/// ```compile_fail42/// use cdk_rsx_platform::memory::{Memory, MemoryResult as Result};43/// struct Unchecked;44/// impl Memory for Unchecked {45/// fn len(&self) -> u64 { 0 }46/// fn grow_to(&mut self, _: u64) -> Result<()> { Ok(()) }47/// fn read(&self, _: u64, _: &mut [u8]) -> Result<()> { Ok(()) }48/// fn write(&mut self, _: u64, _: &[u8]) -> Result<()> { Ok(()) }49/// }50/// ```51pub unsafe trait Memory {52 /// Abort this execution. IC backends trap directly; the native default53 /// unwinds to a test-host snapshot boundary. Never continue using a native54 /// store after catching this panic without restoring its complete image.55 fn abort(&self, error: Error) -> ! {56 std::panic::panic_any(error)57 }5859 /// Format the shared retained page authority without touching Store roots.60 /// Hosts whose bootstrap already initialized it may use the default.61 fn initialize_retained_storage(&mut self) -> Result<()> {62 Ok(())63 }6465 /// Validate the saved retained extent authority before interpreting Store.66 /// A host bootstrap may have already performed this check.67 fn validate_retained_storage(&self) -> Result<()> {68 Ok(())69 }7071 /// Claim one pinned physically contiguous retained extent. Bytes and72 /// alignment are whole 64 KiB pages; successful claims are initialized.73 fn allocate_retained_extent(&mut self, _bytes: u64, _alignment: u64) -> Result<u64> {74 Err(Error::InvalidInput(75 "retained extent allocation unavailable",76 ))77 }7879 /// Release the exact live extent after all Store links and loans detach.80 /// `false` retains ownership for a backend that cannot return the run.81 fn release_retained_extent(&mut self, _offset: u64, _bytes: u64) -> Result<bool> {82 Err(Error::InvalidInput("retained extent release unavailable"))83 }8485 /// Resolve an admitted physical address to its exact Store-owned run.86 /// Queries grant no payload reference and never allocate.87 fn retained_extent_containing(&self, _offset: u64) -> Result<Option<(u64, u64)>> {88 Err(Error::InvalidInput("retained extent authority unavailable"))89 }9091 /// Claimed Store bytes, distinct from the address high-water in `len`.92 /// The reserved retained anchor counts; shared provider controls do not.93 fn retained_allocated_bytes(&self) -> Result<u64> {94 Ok(self.len())95 }9697 fn len(&self) -> u64;98 fn grow_to(&mut self, new_len: u64) -> Result<()>;99 fn read(&self, offset: u64, out: &mut [u8]) -> Result<()>;100 fn write(&mut self, offset: u64, bytes: &[u8]) -> Result<()>;101 /// Read a bounded range during an immutable borrow. Direct-memory backends102 /// can lend bytes to this callback; other backends reuse the supplied scratch.103 /// Scratch is opaque reusable workspace; its length need not equal `len`.104 /// Only the requested range is read and lent to the callback, which cannot105 /// retain a slice after this borrow or mutate the memory.106 fn with_bytes<T>(107 &self,108 offset: u64,109 len: usize,110 scratch: &mut Vec<u8>,111 f: impl FnOnce(&[u8]) -> Result<T>,112 ) -> Result<T> {113 if scratch.len() < len {114 scratch.resize(len, 0);115 }116 let bytes = &mut scratch[..len];117 self.read(offset, bytes)?;118 f(bytes)119 }120121 /// Lend an address-space capability whose individual windows are bounded.122 ///123 /// The default uses a whole-arena slice and rejects lengths above124 /// `isize::MAX`. Backends and wrappers supporting larger retained arenas125 /// must override or forward both region methods without constructing that slice.126 fn with_retained_region<T>(127 &self,128 f: impl FnOnce(RetainedRegion<'_>) -> Result<T>,129 ) -> Result<T> {130 let len = usize::try_from(self.len()).map_err(|_| Error::Capacity)?;131 if len > isize::MAX as usize {132 return Err(Error::Capacity);133 }134 self.with_retained_bytes(0, len, |bytes| f(RetainedRegion::from_slice(bytes)))135 }136 /// Exclusive address-space capability; windows borrow this capability.137 ///138 /// Like `with_retained_region`, the default uses a whole-arena slice and is139 /// limited to `isize::MAX`. Large-memory wrappers must forward this method too.140 fn with_retained_region_mut<T>(141 &mut self,142 f: impl FnOnce(RetainedRegionMut<'_>) -> Result<T>,143 ) -> Result<T> {144 let len = usize::try_from(self.len()).map_err(|_| Error::Capacity)?;145 if len > isize::MAX as usize {146 return Err(Error::Capacity);147 }148 self.with_retained_bytes_mut(0, len, |bytes| f(RetainedRegionMut::from_slice(bytes)))149 }150151 /// Lend retained bytes directly, without a scratch copy. Copying backends152 /// deliberately do not implement this capability. The callback cannot keep153 /// the slice, and the borrow excludes growth or mutation while it is live.154 /// No host-pointer alignment beyond `u8` is promised.155 ///156 /// ```compile_fail157 /// use cdk_rsx_platform::memory::{Memory, VecMemory};158 /// let memory = VecMemory::from_bytes(vec![0; 8]);159 /// let escaped = memory.with_retained_bytes(0, 8, |bytes| Ok(bytes));160 /// ```161 fn with_retained_bytes<T>(162 &self,163 _offset: u64,164 _len: usize,165 _f: impl FnOnce(&[u8]) -> Result<T>,166 ) -> Result<T> {167 Err(Error::InvalidInput("direct retained access unavailable"))168 }169170 /// Exclusively lend retained bytes in place. There is no write-back copy or171 /// local rollback: changes are immediate and the host rolls back a trap.172 /// The callback cannot reenter, grow or release this backing while borrowed.173 /// No host-pointer alignment beyond `u8` is promised.174 ///175 /// ```compile_fail176 /// use cdk_rsx_platform::memory::{Memory, VecMemory};177 /// let mut memory = VecMemory::from_bytes(vec![0; 8]);178 /// memory.with_retained_bytes_mut(0, 8, |bytes| {179 /// memory.grow_to(65_536)?;180 /// bytes[0] = 1;181 /// Ok(())182 /// }).unwrap();183 /// ```184 fn with_retained_bytes_mut<T>(185 &mut self,186 _offset: u64,187 _len: usize,188 _f: impl FnOnce(&mut [u8]) -> Result<T>,189 ) -> Result<T> {190 Err(Error::InvalidInput("direct retained access unavailable"))191 }192193 /// Lend a disjoint retained source and destination for copying or reshaping194 /// a collection after allocation. Both ranges stay fixed for the callback;195 /// overlapping ranges are rejected, including through a copying backend.196 fn with_retained_pair<T>(197 &mut self,198 _source: (u64, usize),199 _target: (u64, usize),200 _f: impl FnOnce(&[u8], &mut [u8]) -> Result<T>,201 ) -> Result<T> {202 Err(Error::InvalidInput("direct retained access unavailable"))203 }204205 fn is_empty(&self) -> bool {206 self.len() == 0207 }208}209210/// Native byte-image backing for provider tests and encoded byte stores.211/// Cloning copies bytes into an independent image. Growth may relocate the Vec212/// only outside a borrowed byte window. This is not a typed retained-pointer213/// image: serializing these bytes never rebases native pointers.214#[derive(Clone, Debug, Default)]215pub struct VecMemory {216 bytes: Vec<u8>,217 // Transient mode only; the provider table itself persists in `bytes`.218 // Stable/plain byte images do not install a retained provider.219 sparse: bool,220}221impl VecMemory {222 pub fn new() -> Self {223 Self::default()224 }225 /// Create a plain byte image. Retained initialization requires a whole-page226 /// length, including an empty image.227 pub fn from_bytes(bytes: Vec<u8>) -> Self {228 Self {229 bytes,230 sparse: false,231 }232 }233 /// Admit an existing sparse byte image after validating its page authority.234 /// Unlike plain `from_bytes`, this never guesses an application root format.235 pub fn reopen_retained(bytes: Vec<u8>) -> Result<Self> {236 if bytes.len() < page_pool::PAGE_BYTES237 || !bytes.len().is_multiple_of(page_pool::PAGE_BYTES)238 || bytes.len() / page_pool::PAGE_BYTES > page_pool::MAX_PAGES239 {240 return Err(Error::UnsupportedFormat);241 }242 let memory = Self {243 bytes,244 sparse: true,245 };246 memory.validate_retained_storage()?;247 if !memory.bounds().pool().installed().map_err(pool_error)? {248 return Err(Error::UnsupportedFormat);249 }250 Ok(memory)251 }252 pub fn into_bytes(self) -> Vec<u8> {253 self.bytes254 }255 pub fn as_bytes(&self) -> &[u8] {256 &self.bytes257 }258 fn bounds(&self) -> VecBounds {259 VecBounds {260 pointer: self.bytes.as_ptr().cast_mut(),261 pages: self.bytes.len() / page_pool::PAGE_BYTES,262 }263 }264 fn check_range(&self, offset: u64, len: usize) -> Result<core::ops::Range<usize>> {265 let start = usize::try_from(offset).map_err(|_| Error::Bounds)?;266 let end = start.checked_add(len).ok_or(Error::Bounds)?;267 if end > self.bytes.len() || (self.sparse && !self.bounds().contains(start..end)) {268 return Err(Error::Bounds);269 }270 Ok(start..end)271 }272}273274fn native_pool_config() -> page_pool::Config {275 page_pool::Config {276 reserved_pages: 1,277 max_pages: page_pool::MAX_PAGES,278 alignment_origin: 0,279 protected: None,280 }281}282fn pool_error(error: page_pool::PoolError) -> Error {283 match error {284 page_pool::PoolError::Exhausted => Error::Capacity,285 page_pool::PoolError::Invalid => Error::Bounds,286 page_pool::PoolError::Corrupt => Error::Corrupt("retained page authority"),287 }288}289struct VecBacking<'a>(&'a mut Vec<u8>);290// SAFETY: the Vec is exclusively borrowed for this short provider operation;291// no payload pointer survives a relocation and control_ptr is reacquired.292// Retained initialization/reopen admit only whole-page images; extent claims293// preserve that length invariant, so newly exposed pages are entirely zero.294unsafe impl page_pool::Backing for VecBacking<'_> {295 fn control_ptr(&self) -> *mut u8 {296 self.0.as_ptr().cast_mut()297 }298 fn pages(&self) -> usize {299 self.0.len() / page_pool::PAGE_BYTES300 }301 fn grow_to(&mut self, pages: usize) -> bool {302 let Some(len) = pages.checked_mul(page_pool::PAGE_BYTES) else {303 return false;304 };305 if len > self.0.len() {306 if self.0.try_reserve_exact(len - self.0.len()).is_err() {307 return false;308 }309 self.0.resize(len, 0);310 }311 true312 }313 unsafe fn zero(&mut self, bytes: core::ops::Range<usize>) {314 self.0[bytes].fill(0);315 }316}317#[derive(Clone, Copy)]318struct VecBounds {319 pointer: *mut u8,320 pages: usize,321}322// SAFETY: used only for read-only provider queries during an owning image loan.323// Mutation/growth methods are unreachable and no table reference is retained.324unsafe impl page_pool::Backing for VecBounds {325 fn control_ptr(&self) -> *mut u8 {326 self.pointer327 }328 fn pages(&self) -> usize {329 self.pages330 }331 fn grow_to(&mut self, _: usize) -> bool {332 false333 }334 unsafe fn zero(&mut self, _: core::ops::Range<usize>) {335 unreachable!()336 }337}338impl VecBounds {339 fn pool(self) -> page_pool::Pool<Self> {340 // SAFETY: initialization/format is checked before this mode is enabled.341 unsafe { page_pool::Pool::attach(self, native_pool_config()) }342 }343}344// SAFETY: each accepted window is wholly inside the Store root or pages345// exclusively owned by Store. The native callback borrow pins the Vec.346unsafe impl RetainedBounds for VecBounds {347 fn contains(&self, bytes: core::ops::Range<usize>) -> bool {348 if bytes.start > bytes.end || bytes.end > self.pages * page_pool::PAGE_BYTES {349 return false;350 }351 if bytes.end <= page_pool::ROOT_BYTES {352 return true;353 }354 if bytes.start < page_pool::PAGE_BYTES {355 return false;356 }357 if self.pages > page_pool::MAX_PAGES || self.pool().committed_pages() != self.pages {358 return false;359 }360 let end_page = bytes.end.div_ceil(page_pool::PAGE_BYTES);361 self.pool().contains(362 page_pool::Owner::Store,363 bytes.start / page_pool::PAGE_BYTES..end_page,364 )365 }366}367// SAFETY: The Vec is owned, clones copy its bytes, and mutation requires this value's exclusive borrow.368unsafe impl Memory for VecMemory {369 fn initialize_retained_storage(&mut self) -> Result<()> {370 if self.sparse {371 return Err(Error::InvalidInput("retained provider already initialized"));372 }373 // A preserved partial tail would become nonzero "new" page contents374 // on later growth. Reject before formatting or changing image mode.375 if !self.bytes.len().is_multiple_of(page_pool::PAGE_BYTES) {376 return Err(Error::InvalidInput("retained image is not page aligned"));377 }378 // SAFETY: formatting owns an uninstalled image and no payload loan.379 let mut pool = unsafe {380 page_pool::Pool::initialize(VecBacking(&mut self.bytes), native_pool_config())381 }382 .map_err(pool_error)?;383 pool.install_store().map_err(pool_error)?;384 self.sparse = true;385 Ok(())386 }387 fn validate_retained_storage(&self) -> Result<()> {388 if !self.sparse || !self.bytes.len().is_multiple_of(page_pool::PAGE_BYTES) {389 return Err(Error::UnsupportedFormat);390 }391 self.bounds().pool().validate().map_err(pool_error)392 }393 fn allocate_retained_extent(&mut self, bytes: u64, alignment: u64) -> Result<u64> {394 let page = page_pool::PAGE_BYTES as u64;395 if !self.sparse396 || bytes == 0397 || !bytes.is_multiple_of(page)398 || !alignment.is_multiple_of(page)399 {400 return Err(Error::Bounds);401 }402 let count = usize::try_from(bytes / page).map_err(|_| Error::Capacity)?;403 let alignment = usize::try_from(alignment / page).map_err(|_| Error::Capacity)?;404 // SAFETY: this backend owns initialized provider controls exclusively.405 let mut pool =406 unsafe { page_pool::Pool::attach(VecBacking(&mut self.bytes), native_pool_config()) };407 let run = pool408 .claim(page_pool::Owner::Store, count, alignment)409 .map_err(pool_error)?;410 Ok(run.address() as u64)411 }412 fn release_retained_extent(&mut self, offset: u64, bytes: u64) -> Result<bool> {413 let page = page_pool::PAGE_BYTES as u64;414 if !self.sparse || !offset.is_multiple_of(page) || !bytes.is_multiple_of(page) {415 return Err(Error::Bounds);416 }417 let run = page_pool::Run {418 start: usize::try_from(offset / page).map_err(|_| Error::Bounds)?,419 count: usize::try_from(bytes / page).map_err(|_| Error::Bounds)?,420 };421 let mut pool =422 unsafe { page_pool::Pool::attach(VecBacking(&mut self.bytes), native_pool_config()) };423 // SAFETY: Store has detached this exact currently owned whole run.424 unsafe { pool.release(page_pool::Owner::Store, run) }.map_err(pool_error)?;425 Ok(true)426 }427 fn retained_extent_containing(&self, offset: u64) -> Result<Option<(u64, u64)>> {428 if !self.sparse {429 return Err(Error::UnsupportedFormat);430 }431 let page =432 usize::try_from(offset / page_pool::PAGE_BYTES as u64).map_err(|_| Error::Bounds)?;433 Ok(self434 .bounds()435 .pool()436 .containing(page_pool::Owner::Store, page)437 .map(|run| (run.address() as u64, run.bytes() as u64)))438 }439 fn retained_allocated_bytes(&self) -> Result<u64> {440 if !self.sparse {441 return Ok(self.len());442 }443 Ok(page_pool::ROOT_BYTES as u64444 + self445 .bounds()446 .pool()447 .allocated_pages(page_pool::Owner::Store) as u64448 * page_pool::PAGE_BYTES as u64)449 }450 fn with_retained_region<T>(451 &self,452 f: impl FnOnce(RetainedRegion<'_>) -> Result<T>,453 ) -> Result<T> {454 if !self.sparse {455 return f(RetainedRegion::from_slice(&self.bytes));456 }457 let bounds = self.bounds();458 // SAFETY: the callback borrow prevents native Vec relocation; bounds459 // grants only initialized Store windows, excluding provider/runtime.460 f(unsafe {461 RetainedRegion::from_raw_parts_with_bounds(self.bytes.as_ptr(), self.len(), &bounds)?462 })463 }464 fn with_retained_region_mut<T>(465 &mut self,466 f: impl FnOnce(RetainedRegionMut<'_>) -> Result<T>,467 ) -> Result<T> {468 if !self.sparse {469 return f(RetainedRegionMut::from_slice(&mut self.bytes));470 }471 let bounds = self.bounds();472 let len = self.len();473 f(unsafe {474 RetainedRegionMut::from_raw_parts_with_bounds(self.bytes.as_mut_ptr(), len, &bounds)?475 })476 }477 fn len(&self) -> u64 {478 self.bytes.len() as u64479 }480 fn grow_to(&mut self, new_len: u64) -> Result<()> {481 let size = usize::try_from(new_len).map_err(|_| Error::Capacity)?;482 if self.sparse && size > self.bytes.len() {483 return Err(Error::InvalidInput("retained growth requires extent claim"));484 }485 if size > self.bytes.len() {486 self.bytes487 .try_reserve_exact(size - self.bytes.len())488 .map_err(|_| Error::Capacity)?;489 self.bytes.resize(size, 0);490 }491 Ok(())492 }493 fn read(&self, offset: u64, out: &mut [u8]) -> Result<()> {494 let range = self.check_range(offset, out.len())?;495 out.copy_from_slice(&self.bytes[range]);496 Ok(())497 }498 fn with_bytes<T>(499 &self,500 offset: u64,501 len: usize,502 _scratch: &mut Vec<u8>,503 f: impl FnOnce(&[u8]) -> Result<T>,504 ) -> Result<T> {505 f(&self.bytes[self.check_range(offset, len)?])506 }507 fn write(&mut self, offset: u64, bytes: &[u8]) -> Result<()> {508 let range = self.check_range(offset, bytes.len())?;509 self.bytes[range].copy_from_slice(bytes);510 Ok(())511 }512513 fn with_retained_bytes<T>(514 &self,515 offset: u64,516 len: usize,517 f: impl FnOnce(&[u8]) -> Result<T>,518 ) -> Result<T> {519 f(&self.bytes[self.check_range(offset, len)?])520 }521522 fn with_retained_bytes_mut<T>(523 &mut self,524 offset: u64,525 len: usize,526 f: impl FnOnce(&mut [u8]) -> Result<T>,527 ) -> Result<T> {528 let range = self.check_range(offset, len)?;529 f(&mut self.bytes[range])530 }531532 fn with_retained_pair<T>(533 &mut self,534 source: (u64, usize),535 target: (u64, usize),536 f: impl FnOnce(&[u8], &mut [u8]) -> Result<T>,537 ) -> Result<T> {538 let source_range = self.check_range(source.0, source.1)?;539 let target_range = self.check_range(target.0, target.1)?;540 let (start, end) = (source_range.start, source_range.end);541 let (target_start, target_end) = (target_range.start, target_range.end);542 if end > target_start && target_end > start {543 return Err(Error::InvalidInput("overlapping retained windows"));544 }545 // SAFETY: both exact windows passed Store ownership/bounds checks and546 // are disjoint. No intermediate slice spans runtime or provider holes.547 let pointer = self.bytes.as_mut_ptr();548 unsafe {549 f(550 core::slice::from_raw_parts(pointer.add(start), source.1),551 core::slice::from_raw_parts_mut(pointer.add(target_start), target.1),552 )553 }554 }555}556557#[cfg(test)]558mod tests {559 use super::*;560561 #[test]562 fn retained_initialization_rejects_partial_pages_before_mutation() {563 let page = page_pool::PAGE_BYTES;564 for len in [1, page_pool::ROOT_BYTES, page - 1, page + 1] {565 let bytes = vec![0xa5; len];566 let mut memory = VecMemory::from_bytes(bytes.clone());567 assert_eq!(568 memory.initialize_retained_storage(),569 Err(Error::InvalidInput("retained image is not page aligned"))570 );571 assert_eq!(memory.as_bytes(), bytes);572 assert!(!memory.sparse);573 }574 }575576 #[test]577 fn aligned_initialization_preserves_root_and_grows_zero_store_pages() -> Result<()> {578 let page = page_pool::PAGE_BYTES;579 let mut memory = VecMemory::from_bytes(vec![0xa5; page]);580 memory.initialize_retained_storage()?;581 memory.validate_retained_storage()?;582 assert_eq!(583 &memory.as_bytes()[..page_pool::ROOT_BYTES],584 &[0xa5; page_pool::ROOT_BYTES]585 );586 let offset = memory.allocate_retained_extent(page as u64, page as u64)?;587 assert_eq!(offset, page as u64);588 memory.with_retained_bytes(offset, page, |bytes| {589 assert!(bytes.iter().all(|byte| *byte == 0));590 Ok(())591 })?;592 memory.validate_retained_storage()593 }594595 #[test]596 fn native_provider_excludes_runtime_holes_and_reopens_exact_ownership() -> Result<()> {597 let mut memory = VecMemory::new();598 memory.initialize_retained_storage()?;599 let runtime = {600 let mut pool = unsafe {601 page_pool::Pool::attach(VecBacking(&mut memory.bytes), native_pool_config())602 };603 pool.claim(page_pool::Owner::Runtime, 3, 1)604 .map_err(pool_error)?605 };606 memory.bytes[runtime.address()..runtime.address() + runtime.bytes()].fill(0xa5);607 let retained = memory.allocate_retained_extent(608 17 * page_pool::PAGE_BYTES as u64,609 page_pool::PAGE_BYTES as u64,610 )?;611 memory.write(retained + 32, b"pinned")?;612 let expected = Some((retained, 17 * page_pool::PAGE_BYTES as u64));613 assert_eq!(memory.retained_extent_containing(retained + 123)?, expected);614 assert_eq!(615 memory.retained_extent_containing(runtime.address() as u64)?,616 None617 );618 assert_eq!(memory.read(512, &mut [0]), Err(Error::Bounds));619 assert_eq!(620 memory.read(runtime.address() as u64, &mut [0]),621 Err(Error::Bounds)622 );623 memory.with_retained_region(|region| {624 assert!(region.get(0..512).is_some());625 assert!(region.get(512..513).is_none());626 assert!(627 region628 .get(runtime.address()..runtime.address() + 1)629 .is_none()630 );631 assert_eq!(632 ®ion[retained as usize + 32..retained as usize + 38],633 b"pinned"634 );635 Ok(())636 })?;637 memory.with_retained_region_mut(|mut region| {638 assert!(639 region640 .get_mut(runtime.address()..runtime.address() + 1)641 .is_none()642 );643 assert!(region.as_region().get(512..513).is_none());644 region[retained as usize + 31] = 9;645 Ok(())646 })?;647 // The image alone restores authority; no transient extent catalog exists.648 let mut memory = VecMemory::reopen_retained(memory.into_bytes())?;649 memory.validate_retained_storage()?;650 assert_eq!(memory.retained_extent_containing(retained + 123)?, expected);651 assert_eq!(652 memory.retained_allocated_bytes()?,653 512 + 17 * page_pool::PAGE_BYTES as u64654 );655 let mut data = [0; 6];656 memory.read(retained + 32, &mut data)?;657 assert_eq!(&data, b"pinned");658 assert!(memory.release_retained_extent(retained, 17 * page_pool::PAGE_BYTES as u64)?);659 assert_eq!(memory.read(retained, &mut [0]), Err(Error::Bounds));660 assert_eq!(661 memory.release_retained_extent(retained, 17 * page_pool::PAGE_BYTES as u64),662 Err(Error::Bounds)663 );664 // Recycled runtime contents must become initialized zero Store bytes.665 {666 let mut pool = unsafe {667 page_pool::Pool::attach(VecBacking(&mut memory.bytes), native_pool_config())668 };669 unsafe { pool.release(page_pool::Owner::Runtime, runtime) }.map_err(pool_error)?;670 }671 let reused = memory.allocate_retained_extent(672 3 * page_pool::PAGE_BYTES as u64,673 page_pool::PAGE_BYTES as u64,674 )?;675 assert_eq!(reused, runtime.address() as u64);676 memory.with_retained_bytes(reused, runtime.bytes(), |bytes| {677 assert!(bytes.iter().all(|byte| *byte == 0));678 Ok(())679 })680 }681682 #[test]683 fn plain_byte_images_grow_zeroed_without_installing_a_provider() -> Result<()> {684 let mut memory = VecMemory::from_bytes(vec![1, 2, 3]);685 memory.grow_to(9)?;686 assert_eq!(memory.as_bytes(), &[1, 2, 3, 0, 0, 0, 0, 0, 0]);687 memory.write(4, &[7, 8])?;688 let copied = memory.clone();689 memory.write(4, &[9])?;690 assert_eq!(&copied.as_bytes()[4..6], &[7, 8]);691 assert_eq!(memory.read(9, &mut [0]), Err(Error::Bounds));692 assert_eq!(693 memory.validate_retained_storage(),694 Err(Error::UnsupportedFormat)695 );696 assert!(VecMemory::reopen_retained(memory.into_bytes()).is_err());697 Ok(())698 }699}