From 3f6d63f9c34affd72c122bcf88be0308181efa15 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Tue, 24 Nov 2026 14:02:27 +0000 Subject: [PATCH 1/2] feat: add explicit snapshot compaction Pack live snapshot pages into one memory layer, optionally retaining identical immutable base layers. Preserve execution state, page-table topology, metadata, transport state, and cached hashes without changing the OCI snapshot format. Signed-off-by: Jorge Prendes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/snapshot-oci-format.md | 15 + src/hyperlight_host/src/mem/layout.rs | 2 +- src/hyperlight_host/src/mem/virtq/mod.rs | 2 +- .../src/sandbox/snapshot/compact.rs | 348 ++++++++++++++++++ .../src/sandbox/snapshot/file_tests.rs | 78 ++++ .../src/sandbox/snapshot/mod.rs | 52 +-- 6 files changed, 472 insertions(+), 25 deletions(-) create mode 100644 src/hyperlight_host/src/sandbox/snapshot/compact.rs diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 9d7319516..7e1806d4f 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -8,6 +8,21 @@ Only a snapshot taken after the guest has run can be persisted. Such a snapshot carries the captured vCPU registers needed to resume a call. `Snapshot::save` rejects a pre-init snapshot. +`Snapshot::compact(None)` packs live memory pages into a single layer. +`Snapshot::compact(Some(&base))` retains referenced immutable layers identical +to the base and packs other live pages into at most one new layer. Base matching +uses the layer's address, geometry, and complete blob contents, so a separately +loaded base works too. The base must have the same memory layout. + +Compaction leaves its inputs unchanged and preserves execution state, metadata, +transport state, page-table topology, and cached hashes of retained layers. +Repacked memory gets a fresh hash on its first ordinary save. +It does not change the file format: +save and restore the result normally. Saving includes every required blob, +including preserved base blobs; omitting or sharing those blobs during transport +is the caller's responsibility. Compaction copies live non-base pages and is +explicit rather than automatically performed on every snapshot. + [OCI Image Layout]: https://github.com/opencontainers/image-spec/blob/main/image-layout.md ## Directory layout diff --git a/src/hyperlight_host/src/mem/layout.rs b/src/hyperlight_host/src/mem/layout.rs index 0543e5abc..b78515943 100644 --- a/src/hyperlight_host/src/mem/layout.rs +++ b/src/hyperlight_host/src/mem/layout.rs @@ -55,7 +55,7 @@ use crate::error::HyperlightError::{MemoryRequestTooBig, MemoryRequestTooSmall}; use crate::sandbox::SandboxConfiguration; use crate::{Result, new_error}; -#[derive(Copy, Clone)] +#[derive(Copy, Clone, PartialEq, Eq)] pub(crate) struct SandboxMemoryLayout { /// The size of the guest code section. code_size: usize, diff --git a/src/hyperlight_host/src/mem/virtq/mod.rs b/src/hyperlight_host/src/mem/virtq/mod.rs index fd2c623a8..c596269f0 100644 --- a/src/hyperlight_host/src/mem/virtq/mod.rs +++ b/src/hyperlight_host/src/mem/virtq/mod.rs @@ -63,7 +63,7 @@ pub(crate) fn create_consumers( } /// Validated ring images excluded from ordinary snapshot pages. -#[derive(Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct VirtqSnapshot { /// Guest-to-host ring bytes. g2h_ring: Vec, diff --git a/src/hyperlight_host/src/sandbox/snapshot/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs new file mode 100644 index 000000000..4a0d18e1b --- /dev/null +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +use super::memory::host_page_size; +use super::*; + +impl Snapshot { + /// Compacts live memory into a new snapshot without changing this snapshot. + /// + /// With no `base`, live pages are packed into a single memory layer. With a + /// base, referenced layers identical to the base's layers are retained, + /// including their serialized blob contents; other live pages are packed + /// into at most one new memory layer. Intermediate snapshots are not needed + /// to save or restore the result. + /// + /// Base layers are matched by GPA, geometry, and complete blob contents, + /// not pointer identity, so a separately loaded base can be used. Unused + /// layers and unreferenced pages in merged layers are discarded. Retained + /// base layers are kept whole. + /// + /// Registers, metadata, transport state, generation, and page-table roots + /// are preserved. The result uses the existing snapshot file format. + /// + /// # Errors + /// + /// Returns an error if the base has a different memory layout, allocation + /// fails, or the compacted memory cannot fit within the address-space or + /// layer limits. + #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")] + pub fn compact(&self, base: Option<&Snapshot>) -> Result> { + if let Some(base) = base + && self.state.layout != base.state.layout + { + return Err(crate::new_error!( + "compaction base has an incompatible memory layout" + )); + } + + let memory = &self.state.memory; + let preserve: Vec = memory + .layers() + .iter() + .map(|layer| { + base.is_some_and(|base| { + base.state.memory.layers().iter().any(|candidate| { + Arc::ptr_eq(layer, candidate) + || (layer.gpa_start() == candidate.gpa_start() + && layer.data_len() == candidate.data_len() + && layer.page_table_len() == candidate.page_table_len() + && layer.memory().as_slice() == candidate.memory().as_slice()) + }) + }) + }) + .collect(); + let mut reused = vec![false; preserve.len()]; + let mut pages = Vec::new(); + let mut page_tables = memory.page_table_bytes().to_vec(); + + // Snapshot tables use guest-page leaves. Intermediate-table pointers, + // scratch, and IO mappings lie outside the data layers. Visiting every + // entry preserves all roots and shared tables at their original GPAs. + for bytes in page_tables.as_chunks::().0 { + let entry = vmem::PageTableEntry::from_le_bytes(*bytes); + if entry & vmem::PAGE_PRESENT == 0 { + continue; + } + let gpa = entry & vmem::PTE_ADDR_MASK; + if let Some((index, offset)) = memory.resolve(gpa, PAGE_SIZE) { + if preserve[index] { + reused[index] = true; + } else { + pages.push(NewPage { + source_gpa: gpa, + backing: GuestBacking { + source: BackingSource::Snapshot(index), + offset, + }, + }); + } + } + } + pages.sort_unstable_by_key(|page| page.source_gpa); + pages.dedup_by_key(|page| page.source_gpa); + let mut layers: Vec<_> = memory + .layers() + .iter() + .zip(reused) + .filter(|(_, reused)| *reused) + .map(|(layer, _)| layer.clone()) + .collect(); + let alignment = host_page_size(); + let data_len = packed_data_len(pages.len(), alignment)?; + let scratch_base = scratch_base_gpa(self.state.layout.get_scratch_size()); + let new_gpa = if data_len == 0 { + None + } else { + Some( + first_fit_blob_gpa(data_len, &layers, scratch_base) + .ok_or_else(|| crate::new_error!("no address space for compacted memory"))?, + ) + }; + let runs = match new_gpa { + Some(gpa) => new_page_runs(&pages, gpa)?, + None => Vec::new(), + }; + for bytes in page_tables.as_chunks_mut::().0 { + let entry = vmem::PageTableEntry::from_le_bytes(*bytes); + if entry & vmem::PAGE_PRESENT != 0 + && let Some(destination) = page_destination(&runs, entry & vmem::PTE_ADDR_MASK) + { + *bytes = ((entry & !vmem::PTE_ADDR_MASK) | destination).to_le_bytes(); + } + } + let blob_len = data_len + .checked_add(page_tables.len()) + .and_then(|len| len.checked_next_multiple_of(alignment)) + .ok_or_else(|| crate::new_error!("compacted snapshot size overflows"))?; + let mut allocation = ExclusiveSharedMemory::new(blob_len)?; + for copy in new_page_copies(&pages)? { + let BackingSource::Snapshot(index) = copy.backing.source else { + return Err(crate::new_error!( + "compaction source is not snapshot memory" + )); + }; + memory.layers()[index].memory().copy_to_slice( + &mut allocation.as_mut_slice()[copy.destination], + copy.backing.offset, + )?; + } + allocation.copy_from_slice(&page_tables, data_len)?; + let blob = Arc::new(SnapshotBlob::new( + allocation.freeze(data_len)?, + new_gpa.unwrap_or_default(), + page_tables.len(), + scratch_base, + )?); + if data_len > 0 { + layers.push(blob.clone()); + } + Ok(Arc::new(Self { + state: Arc::new(SnapshotState { + memory: Arc::new(SnapshotMemory::new(layers.into_boxed_slice(), blob)?), + ..(*self.state).clone() + }), + metadata: self.metadata.clone(), + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mem::shared_mem::ReadonlySharedMemory; + + fn layered_snapshot() -> Snapshot { + let layout = SandboxMemoryLayout::new(SandboxConfiguration::default(), PAGE_SIZE).unwrap(); + let start = SandboxMemoryLayout::BASE_ADDRESS as u64; + let alignment = host_page_size(); + let pt = GuestPageTableBuffer::new(layout.get_pt_base_gpa() as usize); + let kinds = [ + MappingKind::Basic(BasicMapping { + readable: true, + writable: false, + executable: true, + }), + MappingKind::Cow(CowMapping { + readable: true, + executable: false, + }), + MappingKind::Cow(CowMapping { + readable: true, + executable: false, + }), + MappingKind::ZeroInit(BasicMapping { + readable: true, + writable: true, + executable: false, + }), + ]; + for (index, kind) in kinds.into_iter().enumerate() { + // SAFETY: The local buffer has no concurrent access and mappings + // are aligned guest pages. + unsafe { + vmem::map( + &pt, + Mapping { + phys_base: start + if index == 0 { 0 } else { 4 * alignment as u64 }, + virt_base: start + (index * PAGE_SIZE) as u64, + len: PAGE_SIZE as u64, + kind, + }, + ); + } + } + map_specials(&pt, layout.get_scratch_size()); + let layers = [0x11, 0x22, 0x33] + .into_iter() + .enumerate() + .map(|(index, value)| { + let bytes = vec![value; 2 * alignment]; + Arc::new( + SnapshotBlob::new( + ReadonlySharedMemory::from_bytes(&bytes, bytes.len()).unwrap(), + start + (index * 4 * alignment) as u64, + 0, + scratch_base_gpa(layout.get_scratch_size()), + ) + .unwrap(), + ) + }) + .collect::>(); + Snapshot { + state: Arc::new(SnapshotState { + memory: Arc::new( + SnapshotMemory::new( + layers.into_boxed_slice(), + super::super::memory::tests::page_tables_from_bytes(&pt.into_bytes()), + ) + .unwrap(), + ), + layout, + load_info: LoadInfo::dummy(), + stack_top_gva: start, + sregs: None, + #[cfg(target_arch = "x86_64")] + msrs: None, + next_action: NextAction::None, + original_entrypoint: start, + snapshot_generation: 7, + host_functions: HostFunctionDetails::default(), + virtq: None, + }), + metadata: BTreeMap::new(), + } + } + + #[test] + fn compact_packs_live_pages_and_preserves_aliases_and_permissions() { + let original = layered_snapshot(); + let start = SandboxMemoryLayout::BASE_ADDRESS as u64; + for preserve in [false, true] { + let compacted = original.compact(preserve.then_some(&original)).unwrap(); + let memory = &compacted.state.memory; + assert_eq!(memory.layers().len(), if preserve { 2 } else { 1 }); + assert_eq!( + memory + .layers() + .iter() + .map(|layer| layer.data_len()) + .sum::(), + if preserve { + 4 * host_page_size() + } else { + packed_data_len(2, host_page_size()).unwrap() + } + ); + // SAFETY: Both immutable snapshots own their page tables. + let before = unsafe { vmem::virt_to_phys(&original, start, 4 * PAGE_SIZE as u64) } + .collect::>(); + let after = + unsafe { vmem::virt_to_phys(compacted.as_ref(), start, 4 * PAGE_SIZE as u64) } + .collect::>(); + assert_eq!(before.len(), after.len()); + for (index, (before, after)) in before.iter().zip(&after).enumerate() { + assert_eq!(before.virt_base, after.virt_base); + assert_eq!(before.kind, after.kind); + if index < 3 { + let (layer, offset) = memory.resolve(after.phys_base, PAGE_SIZE).unwrap(); + assert_eq!( + &memory.layers()[layer].memory().as_slice()[offset..offset + PAGE_SIZE], + vec![if index == 0 { 0x11 } else { 0x22 }; PAGE_SIZE] + ); + } + } + assert_eq!(after[1].phys_base, after[2].phys_base); + if preserve { + for (actual, expected) in memory.layers().iter().zip(original.state.memory.layers()) + { + assert!(Arc::ptr_eq(actual, expected)); + } + assert_eq!(memory.page_table_blob().data_len(), 0); + } + assert_eq!(compacted.snapshot_generation(), 7); + } + assert_eq!(original.state.memory.layers().len(), 3); + } + + #[test] + fn compact_rejects_incompatible_base_layout() { + let current = layered_snapshot(); + let mut state = (*current.state).clone(); + state.layout = state + .layout + .with_scratch_size(2 * state.layout.get_scratch_size()) + .unwrap(); + let base = Snapshot { + state: Arc::new(state), + metadata: BTreeMap::new(), + }; + let error = current.compact(Some(&base)).err().unwrap(); + assert!(error.to_string().contains("incompatible memory layout")); + } + + #[test] + fn compact_preserves_only_identical_base_blobs() { + let base = layered_snapshot(); + let mut current = layered_snapshot(); + let mut layers = current.state.memory.layers().to_vec(); + let replaced = &layers[1]; + layers[1] = Arc::new( + SnapshotBlob::new( + ReadonlySharedMemory::from_bytes( + &vec![0x44; replaced.data_len()], + replaced.data_len(), + ) + .unwrap(), + replaced.gpa_start(), + 0, + scratch_base_gpa(current.state.layout.get_scratch_size()), + ) + .unwrap(), + ); + current.state = Arc::new(SnapshotState { + memory: Arc::new( + SnapshotMemory::new( + layers.into_boxed_slice(), + current.state.memory.page_table_blob().clone(), + ) + .unwrap(), + ), + ..(*current.state).clone() + }); + let compacted = current.compact(Some(&base)).unwrap(); + let layers = compacted.state.memory.layers(); + assert_eq!(layers.len(), 2); + assert!(Arc::ptr_eq(&layers[0], ¤t.state.memory.layers()[0])); + assert!(!Arc::ptr_eq(&layers[0], &base.state.memory.layers()[0])); + assert_eq!( + layers[0].memory().as_slice(), + base.state.memory.layers()[0].memory().as_slice() + ); + assert_eq!(layers[1].data_len(), host_page_size()); + assert_eq!( + &layers[1].memory().as_slice()[..PAGE_SIZE], + vec![0x44; PAGE_SIZE] + ); + } +} diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 970bbf3b5..d77040c38 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -98,6 +98,84 @@ fn create_snapshot() -> Arc { sbox.snapshot().unwrap() } +#[test] +fn compact_round_trip_preserves_base_blobs_and_execution_state() { + let mut sandbox = create_test_sandbox(); + let base = sandbox.snapshot().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let tag = OciTag::new("base").unwrap(); + base.save(directory.path(), &tag).unwrap(); + let loaded_base = Snapshot::checked_load(directory.path(), tag).unwrap(); + + for preserve in [false, true] { + sandbox.restore(base.clone()).unwrap(); + let mut last = base.clone(); + for value in 1..=35 { + assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), value); + let captured = sandbox + .snapshot() + .unwrap() + .with_metadata("compact-test", &value) + .unwrap(); + let compacted = captured.compact(preserve.then_some(&loaded_base)).unwrap(); + let limit = if preserve { + base.snapshot_memory().layers().len() + 1 + } else { + 1 + }; + assert!(compacted.snapshot_memory().layers().len() <= limit); + assert_eq!( + compacted.snapshot_generation(), + captured.snapshot_generation() + ); + assert_eq!(compacted.virtq(), captured.virtq()); + assert_eq!( + serde_json::to_value(compacted.sregs()).unwrap(), + serde_json::to_value(captured.sregs()).unwrap() + ); + assert_eq!( + compacted.metadata::("compact-test").unwrap(), + Some(value) + ); + if preserve && value == 1 { + let blobs: Vec<_> = compacted.snapshot_memory().blobs().collect(); + assert!(blobs.iter().any(|blob| blob.sha256.get().is_some())); + let uncached_bytes: usize = blobs + .iter() + .filter(|blob| blob.sha256.get().is_none()) + .map(|blob| blob.memory().as_slice().len()) + .sum(); + let before = super::file::test_hashed_bytes(); + compacted + .save(directory.path(), &OciTag::new("compacted-cache").unwrap()) + .unwrap(); + let hashed_bytes = super::file::test_hashed_bytes() - before; + assert!(hashed_bytes >= uncached_bytes); + assert!(hashed_bytes < uncached_bytes + 64 * 1024); + } + sandbox.restore(compacted.clone()).unwrap(); + last = compacted; + } + if preserve { + assert!(last.snapshot_memory().layers().iter().any(|layer| { + loaded_base.snapshot_memory().layers().iter().any(|base| { + Arc::ptr_eq(layer, base) + || (layer.gpa_start() == base.gpa_start() + && layer.memory().as_slice() == base.memory().as_slice()) + }) + })); + } + let output = tempfile::tempdir().unwrap(); + let tag = OciTag::new("compacted").unwrap(); + last.save(output.path(), &tag).unwrap(); + let loaded = Arc::new(Snapshot::checked_load(output.path(), tag).unwrap()); + assert_eq!(loaded.snapshot_generation(), last.snapshot_generation()); + let mut restored = SandboxBuilder::from_snapshot(loaded).build().unwrap(); + assert_eq!(restored.call::("GetStatic", ()).unwrap(), 35); + assert_eq!(restored.call::("AddToStatic", 1i32).unwrap(), 36); + } +} + #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct TestMetadata { format_version: u32, diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index bb24e0800..ad0c51be5 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. +mod compact; mod file; mod file_tests; pub(crate) mod memory; @@ -107,6 +108,7 @@ pub struct Snapshot { } /// Immutable sandbox state held by a snapshot. +#[derive(Clone)] struct SnapshotState { /// Layout object for the sandbox. TODO: get rid of this and /// replace with something saner and set up from the guest (early @@ -1424,6 +1426,7 @@ mod tests { let layout = SandboxMemoryLayout::new(cfg, 4096).unwrap(); let pt_base = layout.get_pt_base_gpa(); let base = SandboxMemoryLayout::BASE_ADDRESS as u64; + let data_base = base + (8 * page_size::get()) as u64; let pt_buf = GuestPageTableBuffer::new(pt_base as usize); let first_root = pt_buf.initial_root(); // SAFETY: The local buffer owns its page tables and has no concurrent access. @@ -1438,7 +1441,7 @@ mod tests { vmem::map( &pt_buf, Mapping { - phys_base: base, + phys_base: data_base, virt_base: base, len: PAGE_SIZE as u64, kind, @@ -1448,7 +1451,7 @@ mod tests { vmem::map( &pt_buf, Mapping { - phys_base: base + PAGE_SIZE as u64, + phys_base: data_base + PAGE_SIZE as u64, virt_base: base + PAGE_SIZE as u64, len: PAGE_SIZE as u64, kind, @@ -1466,7 +1469,7 @@ mod tests { let memory = super::memory::tests::flat_memory( &bytes, &page_tables, - base, + data_base, hyperlight_common::layout::scratch_base_gpa(layout.get_scratch_size()), ); let manager = SandboxMemoryManager::new( @@ -1513,26 +1516,29 @@ mod tests { if mapping.virt_base == base + PAGE_SIZE as u64 ))); - manager.restore_snapshot(&snapshot).unwrap(); - manager - .with_guest_memory(&[], |memory| { - for (root, gva, expected) in [ - (rebuilt_first_root, base, 0x11), - (rebuilt_second_root, base + PAGE_SIZE as u64, 0x22), - ] { - let reader = super::PageTableReader::new(memory, root); - // SAFETY: The reader borrows the stopped manager's mapped memory. - let mapping = unsafe { vmem::virt_to_phys(&reader, gva, 1) } - .next() - .unwrap(); - let gpa = mapping.phys_base + gva - mapping.virt_base; - let mut byte = [0u8; 1]; - memory.read(gpa, &mut byte).unwrap(); - assert_eq!(byte, [expected]); - } - Ok(()) - }) - .unwrap(); + let compacted = snapshot.compact(None).unwrap(); + for snapshot in [&snapshot, compacted.as_ref()] { + manager.restore_snapshot(snapshot).unwrap(); + manager + .with_guest_memory(&[], |memory| { + for (root, gva, expected) in [ + (rebuilt_first_root, base, 0x11), + (rebuilt_second_root, base + PAGE_SIZE as u64, 0x22), + ] { + let reader = super::PageTableReader::new(memory, root); + // SAFETY: The reader borrows the stopped manager's mapped memory. + let mapping = unsafe { vmem::virt_to_phys(&reader, gva, 1) } + .next() + .unwrap(); + let gpa = mapping.phys_base + gva - mapping.virt_base; + let mut byte = [0u8; 1]; + memory.read(gpa, &mut byte).unwrap(); + assert_eq!(byte, [expected]); + } + Ok(()) + }) + .unwrap(); + } } #[cfg(target_arch = "x86_64")] From 70771a2210063d508723d7fbd3fe03ac8f03208a Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Tue, 24 Nov 2026 14:19:52 +0000 Subject: [PATCH 2/2] fix: preserve compacted snapshot GPA span and support gdb Keep the loader code-span invariant through packed-layer placement and minimal padding when all live pages reside in preserved base layers. Copy from the backing-independent slice accessor and cover sparse persistence plus debug gdb compaction. Signed-off-by: Jorge Prendes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/snapshot-oci-format.md | 4 + .../src/sandbox/snapshot/compact.rs | 75 +++++++++++++++++-- .../src/sandbox/snapshot/file_tests.rs | 57 ++++++++++++++ .../src/sandbox/snapshot/mod.rs | 19 +++-- 4 files changed, 142 insertions(+), 13 deletions(-) diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 7e1806d4f..ad14b90a5 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -17,6 +17,10 @@ loaded base works too. The base must have the same memory layout. Compaction leaves its inputs unchanged and preserves execution state, metadata, transport state, page-table topology, and cached hashes of retained layers. Repacked memory gets a fresh hash on its first ordinary save. +Packed layers are placed to preserve the loader's guest-code GPA-span bound +without keeping unused code bytes. If retained base layers alone fall short +and all live pages are already retained, one zero-filled host page supplies +the required span. It does not change the file format: save and restore the result normally. Saving includes every required blob, including preserved base blobs; omitting or sharing those blobs during transport diff --git a/src/hyperlight_host/src/sandbox/snapshot/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs index 4a0d18e1b..51d74fd1b 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/compact.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -15,8 +15,9 @@ impl Snapshot { /// /// Base layers are matched by GPA, geometry, and complete blob contents, /// not pointer identity, so a separately loaded base can be used. Unused - /// layers and unreferenced pages in merged layers are discarded. Retained - /// base layers are kept whole. + /// layers and unreferenced pages in merged layers are discarded, except + /// for minimal padding required by the snapshot format. Retained base + /// layers are kept whole. /// /// Registers, metadata, transport state, generation, and page-table roots /// are preserved. The result uses the existing snapshot file format. @@ -90,12 +91,29 @@ impl Snapshot { .collect(); let alignment = host_page_size(); let data_len = packed_data_len(pages.len(), alignment)?; + let base_gpa = SandboxMemoryLayout::BASE_ADDRESS as u64; + let required_memory_size = self.state.layout.get_memory_size()?; + let preserves_span = layers + .last() + .is_some_and(|layer| layer.gpa_range().end - base_gpa >= required_memory_size as u64); + // The loader requires the GPA span to cover the original code region. + // Place packed data high enough without retaining unused code bytes. + let data_len = if !preserves_span && data_len == 0 { + alignment + } else { + data_len + }; + let minimum_gpa = if preserves_span { + base_gpa + } else { + base_gpa + required_memory_size.saturating_sub(data_len) as u64 + }; let scratch_base = scratch_base_gpa(self.state.layout.get_scratch_size()); let new_gpa = if data_len == 0 { None } else { Some( - first_fit_blob_gpa(data_len, &layers, scratch_base) + first_fit_blob_gpa(data_len, &layers, minimum_gpa, scratch_base) .ok_or_else(|| crate::new_error!("no address space for compacted memory"))?, ) }; @@ -122,10 +140,13 @@ impl Snapshot { "compaction source is not snapshot memory" )); }; - memory.layers()[index].memory().copy_to_slice( - &mut allocation.as_mut_slice()[copy.destination], - copy.backing.offset, - )?; + let source = memory.layers()[index] + .memory() + .as_slice() + .get(copy.backing.offset..) + .and_then(|source| source.get(..copy.destination.len())) + .ok_or_else(|| crate::new_error!("compaction source range is out of bounds"))?; + allocation.copy_from_slice(source, copy.destination.start)?; } allocation.copy_from_slice(&page_tables, data_len)?; let blob = Arc::new(SnapshotBlob::new( @@ -285,6 +306,46 @@ mod tests { assert_eq!(original.state.memory.layers().len(), 3); } + #[test] + fn compact_preserves_sparse_code_span_with_and_without_base_layers() { + let mut original = layered_snapshot(); + let alignment = host_page_size(); + original.state = Arc::new(SnapshotState { + layout: SandboxMemoryLayout::new(SandboxConfiguration::default(), 10 * alignment) + .unwrap(), + ..(*original.state).clone() + }); + for preserve in [false, true] { + let compacted = original.compact(preserve.then_some(&original)).unwrap(); + let memory = &compacted.state.memory; + assert_eq!(memory.layers().len(), if preserve { 3 } else { 1 }); + assert!(memory.gpa_span_len() >= 10 * alignment); + assert!( + memory + .layers() + .iter() + .map(|layer| layer.data_len()) + .sum::() + < 10 * alignment + ); + if preserve { + for (actual, expected) in memory.layers()[..2] + .iter() + .zip(original.state.memory.layers()) + { + assert!(Arc::ptr_eq(actual, expected)); + } + let padding = memory.layers().last().unwrap(); + assert_eq!(padding.data_len(), alignment); + assert!( + padding.memory().as_slice()[..alignment] + .iter() + .all(|byte| *byte == 0) + ); + } + } + } + #[test] fn compact_rejects_incompatible_base_layout() { let current = layered_snapshot(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index d77040c38..eaa9510db 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -98,6 +98,60 @@ fn create_snapshot() -> Arc { sbox.snapshot().unwrap() } +#[test] +fn compact_sparse_memory_round_trips_with_both_loaders() { + let original = create_snapshot(); + let memory = original.snapshot_memory(); + let mut page_tables = memory.page_table_bytes().to_vec(); + let mut live_gpa = None; + for bytes in page_tables.as_chunks_mut::<{ super::PTE_SIZE }>().0 { + let entry = super::vmem::PageTableEntry::from_le_bytes(*bytes); + let gpa = entry & super::vmem::PTE_ADDR_MASK; + if entry & super::vmem::PAGE_PRESENT != 0 + && memory.resolve(gpa, super::PAGE_SIZE).is_some() + && *live_gpa.get_or_insert(gpa) != gpa + { + *bytes = (entry & !super::vmem::PAGE_PRESENT).to_le_bytes(); + } + } + let live_gpa = live_gpa.unwrap(); + let (layer, offset) = memory.resolve(live_gpa, super::PAGE_SIZE).unwrap(); + let expected = &memory.layers()[layer].memory().as_slice()[offset..offset + super::PAGE_SIZE]; + let sparse = Snapshot { + state: Arc::new(super::SnapshotState { + memory: Arc::new( + SnapshotMemory::new( + memory.layers().to_vec().into_boxed_slice(), + super::memory::tests::page_tables_from_bytes(&page_tables), + ) + .unwrap(), + ), + ..(*original.state).clone() + }), + metadata: original.metadata.clone(), + }; + let compacted = sparse.compact(None).unwrap(); + let layer = &compacted.snapshot_memory().layers()[0]; + assert_eq!(layer.data_len(), super::memory::host_page_size()); + assert!(layer.data_len() < sparse.state.layout.get_memory_size().unwrap()); + let directory = tempfile::tempdir().unwrap(); + let tag = OciTag::new("sparse").unwrap(); + compacted.save(directory.path(), &tag).unwrap(); + for checked in [false, true] { + let loaded = if checked { + Snapshot::checked_load(directory.path(), tag.clone()) + } else { + Snapshot::load(directory.path(), tag.clone()) + } + .unwrap(); + assert_eq!(loaded.snapshot_memory().layers().len(), 1); + assert_eq!( + &loaded.snapshot_memory().layers()[0].memory().as_slice()[..super::PAGE_SIZE], + expected + ); + } +} + #[test] fn compact_round_trip_preserves_base_blobs_and_execution_state() { let mut sandbox = create_test_sandbox(); @@ -137,6 +191,8 @@ fn compact_round_trip_preserves_base_blobs_and_execution_state() { compacted.metadata::("compact-test").unwrap(), Some(value) ); + // Debug gdb builds copy all pages, so an identical base blob need not survive. + #[cfg(not(unshared_snapshot_mem))] if preserve && value == 1 { let blobs: Vec<_> = compacted.snapshot_memory().blobs().collect(); assert!(blobs.iter().any(|blob| blob.sha256.get().is_some())); @@ -156,6 +212,7 @@ fn compact_round_trip_preserves_base_blobs_and_execution_state() { sandbox.restore(compacted.clone()).unwrap(); last = compacted; } + #[cfg(not(unshared_snapshot_mem))] if preserve { assert!(last.snapshot_memory().layers().iter().any(|layer| { loaded_base.snapshot_memory().layers().iter().any(|base| { diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index ad0c51be5..0c15d2947 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -479,13 +479,14 @@ fn packed_data_len(page_count: usize, host_page_size: usize) -> Result { fn first_fit_blob_gpa( data_len: usize, layers: &[Arc], + minimum_gpa: u64, scratch_base: u64, ) -> Option { if data_len == 0 { return None; } let data_len = u64::try_from(data_len).ok()?; - let mut candidate = SandboxMemoryLayout::BASE_ADDRESS as u64; + let mut candidate = minimum_gpa; for range in layers.iter().map(|layer| layer.gpa_range()) { let end = candidate.checked_add(data_len)?; if end <= range.start { @@ -844,7 +845,13 @@ impl Snapshot { None } else { Some( - first_fit_blob_gpa(data_len, &layers, target_scratch_gpa).ok_or_else(|| { + first_fit_blob_gpa( + data_len, + &layers, + SandboxMemoryLayout::BASE_ADDRESS as u64, + target_scratch_gpa, + ) + .ok_or_else(|| { crate::new_error!("snapshot has no address space for a new layer") })?, ) @@ -1291,20 +1298,20 @@ mod tests { let scratch_base = base + 2 * PAGE_SIZE as u64; // An empty delta needs no address. - assert_eq!(super::first_fit_blob_gpa(0, &[], scratch_base), None); + assert_eq!(super::first_fit_blob_gpa(0, &[], base, scratch_base), None); // With nothing to reuse the delta lands at the base. assert_eq!( - super::first_fit_blob_gpa(PAGE_SIZE, &[], scratch_base), + super::first_fit_blob_gpa(PAGE_SIZE, &[], base, scratch_base), Some(base) ); // Exactly filling the space below scratch is allowed. assert_eq!( - super::first_fit_blob_gpa(2 * PAGE_SIZE, &[], scratch_base), + super::first_fit_blob_gpa(2 * PAGE_SIZE, &[], base, scratch_base), Some(base) ); // One page more is not. assert_eq!( - super::first_fit_blob_gpa(3 * PAGE_SIZE, &[], scratch_base), + super::first_fit_blob_gpa(3 * PAGE_SIZE, &[], base, scratch_base), None ); }