Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

fix(disk): handle QCOW2 zero-cluster, OFLAG_COPIED, and short EOF tail in flatten (#3081)

lfld28732451f10f2b9
diff --git a/docs/contributing/architecture/README.md b/docs/contributing/architecture/README.md
index f7e4c441c..0ce6b6a2a 100644
--- a/docs/contributing/architecture/README.md
+++ b/docs/contributing/architecture/README.md
@@ -218,6 +218,14 @@ with both admissions held.
Final archive writing releases lifecycle admission but retains disk exclusion
while its caller awaits it.
+QCOW2 [`flatten()`](../../../src/boxlite/src/disk/qcow2.rs) treats an L2
+zero-cluster entry as explicit zeros before considering backing-file fallback.
+It sets `QCOW2_OFLAG_COPIED` on allocated output L1 and L2 entries. If an allocated
+input cluster starts before EOF but extends past it, the unread tail is zero-filled.
+It rejects QCOW2 layers with `extended_l2` (subcluster bitmaps) enabled and QCOW2
+backing chains with mismatched `cluster_size` across layers before creating the output
+image.
+
Snapshot, clone, and export execute in the caller's future, so cancellation does not guarantee
completion of disk work or resume/thaw cleanup: a blocking worker may continue
after the caller drops its guards.
diff --git a/src/boxlite/src/disk/qcow2.rs b/src/boxlite/src/disk/qcow2.rs
index b03e76bef..2fa7c3022 100644
--- a/src/boxlite/src/disk/qcow2.rs
+++ b/src/boxlite/src/disk/qcow2.rs
@@ -327,7 +327,7 @@ impl Qcow2Helper {
let l1_idx = (vc / l2_entries) as usize;
let l2_idx = (vc % l2_entries) as usize;
- l2_tables[l1_idx][l2_idx] = offset;
+ l2_tables[l1_idx][l2_idx] = offset | QCOW2_OFLAG_COPIED;
next_data_cluster += 1;
}
}
@@ -356,7 +356,7 @@ impl Qcow2Helper {
for (i, l2) in l2_tables.iter().enumerate() {
let has_data = l2.iter().any(|&e| e != 0);
let entry: u64 = if has_data {
- (l2_start + i as u64) * cluster_size
+ ((l2_start + i as u64) * cluster_size) | QCOW2_OFLAG_COPIED
} else {
0
};
@@ -480,9 +480,27 @@ impl Qcow2Helper {
fn open_flatten_chain(path: &Path) -> BoxliteResult<Vec<FlattenLayer>> {
let mut chain = Vec::new();
let mut current_path = path.to_path_buf();
+ let mut expected_cluster_bits: Option<(PathBuf, u32)> = None;
loop {
let (layer, backing) = FlattenLayer::open(&current_path)?;
+ if let FlattenLayer::Qcow2 { cluster_bits, .. } = &layer {
+ match &expected_cluster_bits {
+ None => {
+ expected_cluster_bits = Some((current_path.clone(), *cluster_bits));
+ }
+ Some((top_path, top_bits)) if *cluster_bits != *top_bits => {
+ return Err(BoxliteError::Storage(format!(
+ "flatten: cluster size mismatch between {} (cluster_bits={}) and {} (cluster_bits={})",
+ top_path.display(),
+ top_bits,
+ current_path.display(),
+ cluster_bits
+ )));
+ }
+ Some(_) => {}
+ }
+ }
chain.push(layer);
match backing {
Some(bp) => current_path = PathBuf::from(bp),
@@ -1165,6 +1183,12 @@ pub fn is_backing_dependency(target: &Path, chain_root: &Path) -> bool {
/// QCOW2 magic number: "QFI\xfb".
const QCOW2_MAGIC: u32 = 0x514649fb;
+/// QCOW2 L1/L2 entry flag indicating refcount == 1 for the referenced table/cluster.
+const QCOW2_OFLAG_COPIED: u64 = 1 << 63;
+
+/// QCOW2 v3 incompatible feature bit for extended L2 entries (subcluster bitmaps).
+const QCOW2_INCOMPAT_EXTL2: u64 = 1 << 4;
+
/// A layer in a QCOW2 backing chain, used during flatten.
enum FlattenLayer {
/// A QCOW2 layer with L1/L2 indirection.
@@ -1218,6 +1242,17 @@ impl FlattenLayer {
))
})?;
+ let version = u32::from_be_bytes(hdr[4..8].try_into().unwrap());
+ if version >= 3 {
+ let incompatible_features = u64::from_be_bytes(hdr[72..80].try_into().unwrap());
+ if (incompatible_features & QCOW2_INCOMPAT_EXTL2) != 0 {
+ return Err(BoxliteError::Storage(format!(
+ "flatten: extended_l2 QCOW2 layers are not supported: {}",
+ path.display()
+ )));
+ }
+ }
+
let backing_offset = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
let backing_size = u32::from_be_bytes(hdr[16..20].try_into().unwrap());
let cluster_bits = u32::from_be_bytes(hdr[20..24].try_into().unwrap());
@@ -1337,6 +1372,11 @@ impl FlattenLayer {
));
}
+ // Bit 0: zero-cluster flag (reads as all zeros; never fall through to backing).
+ if l2_entry & 1 != 0 {
+ return Ok(Some(vec![0u8; cs as usize]));
+ }
+
let data_offset = l2_entry & 0x00FF_FFFF_FFFF_FE00;
if data_offset == 0 {
return Ok(None); // Unallocated — fall through to backing.
@@ -1345,8 +1385,26 @@ impl FlattenLayer {
file.seek(SeekFrom::Start(data_offset))
.map_err(|e| BoxliteError::Storage(format!("flatten: data seek: {}", e)))?;
let mut buf = vec![0u8; cs as usize];
- file.read_exact(&mut buf)
- .map_err(|e| BoxliteError::Storage(format!("flatten: data read: {}", e)))?;
+ let mut total = 0usize;
+ while total < buf.len() {
+ match file.read(&mut buf[total..]) {
+ Ok(0) => break,
+ Ok(n) => total += n,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => {
+ return Err(BoxliteError::Storage(format!(
+ "flatten: data read: {}",
+ e
+ )));
+ }
+ }
+ }
+ if total == 0 {
+ return Err(BoxliteError::Storage(format!(
+ "flatten: data read: unexpected EOF at offset {}",
+ data_offset
+ )));
+ }
Ok(Some(buf))
}
}
@@ -1779,6 +1837,84 @@ mod tests {
assert_eq!(val, 2, "cluster 1 marker should be 2 (cluster_idx + 1)");
}
+ #[test]
+ fn test_flatten_rejects_extended_l2_backing() {
+ use std::io::{Seek, SeekFrom};
+
+ let dir = TempDir::new().unwrap();
+ let virtual_size = 1u64 << CLUSTER_BITS;
+ let raw = dir.path().join("base.raw");
+ write_raw_disk(&raw, virtual_size);
+ let backing = dir.path().join("backing.qcow2");
+ let _backing_disk =
+ Qcow2Helper::create_cow_child_disk(&raw, BackingFormat::Raw, &backing, virtual_size)
+ .unwrap();
+ let top = dir.path().join("top.qcow2");
+ let _top_disk =
+ Qcow2Helper::create_cow_child_disk(&backing, BackingFormat::Qcow2, &top, virtual_size)
+ .unwrap();
+
+ // Set the extended L2 bit in the v3 incompatible features field.
+ let mut file = OpenOptions::new().write(true).open(&backing).unwrap();
+ file.seek(SeekFrom::Start(72)).unwrap();
+ file.write_all(&(1u64 << 4).to_be_bytes()).unwrap();
+
+ let dst = dir.path().join("flat.qcow2");
+ let err = Qcow2Helper::flatten(&top, &dst)
+ .expect_err("flatten must reject a backing layer with extended_l2");
+ assert!(
+ matches!(err, BoxliteError::Storage(ref msg) if msg.contains("extended_l2")),
+ "{err}"
+ );
+ assert!(!dst.exists());
+ }
+
+ #[test]
+ fn test_flatten_rejects_mixed_cluster_sizes() {
+ let dir = TempDir::new().unwrap();
+ let backing_bits = 17; // 128 KiB; the top layer uses 64 KiB.
+ let virtual_size = 1u64 << backing_bits;
+ let backing = dir.path().join("backing.qcow2");
+ let (rc_table, rc_block, _) = Qcow2Header::calculate_meta_params(
+ virtual_size,
+ backing_bits,
+ REFCOUNT_ORDER,
+ BLOCK_SIZE,
+ );
+ let mut buf =
+ vec![0u8; (((1 + rc_table.1 + rc_block.1) as usize) << backing_bits) + BLOCK_SIZE];
+ Qcow2Header::format_qcow2(
+ &mut buf,
+ virtual_size,
+ backing_bits,
+ REFCOUNT_ORDER,
+ BLOCK_SIZE,
+ )
+ .unwrap();
+ std::fs::write(&backing, buf).unwrap();
+ let top = dir.path().join("top.qcow2");
+ let _top_disk =
+ Qcow2Helper::create_cow_child_disk(&backing, BackingFormat::Qcow2, &top, virtual_size)
+ .unwrap();
+
+ let dst = dir.path().join("flat.qcow2");
+ let err = Qcow2Helper::flatten(&top, &dst)
+ .expect_err("flatten must reject QCOW2 layers with different cluster sizes");
+ let BoxliteError::Storage(msg) = err else {
+ panic!("expected storage error, got: {err}");
+ };
+ for detail in [
+ "cluster size mismatch",
+ "top.qcow2",
+ "backing.qcow2",
+ "16",
+ "17",
+ ] {
+ assert!(msg.contains(detail), "missing {detail:?} in: {msg}");
+ }
+ assert!(!dst.exists());
+ }
+
#[test]
fn test_flatten_compressed_cluster_errors() {
// Create a QCOW2 with a manually crafted compressed L2 entry.
@@ -1857,4 +1993,229 @@ mod tests {
err
);
}
+
+ #[test]
+ fn test_flatten_respects_zero_cluster_l2_flag() {
+ use std::io::{Read, Seek, SeekFrom};
+
+ let dir = TempDir::new().unwrap();
+ let cluster_size = 1u64 << CLUSTER_BITS;
+ let virtual_size = cluster_size * 2;
+
+ // Backing image has non-zero markers in cluster 0 and cluster 1.
+ let base = dir.path().join("base.raw");
+ write_raw_disk(&base, virtual_size);
+
+ let child = dir.path().join("child.qcow2");
+ let _child_disk =
+ Qcow2Helper::create_cow_child_disk(&base, BackingFormat::Raw, &child, virtual_size)
+ .unwrap();
+
+ // Populate L1[0] -> L2 table with L2[0] = QCOW_OFLAG_ZERO (bit 0 = 1, offset = 0)
+ // and L2[1] = 0 (unallocated, falls through to backing).
+ {
+ let mut f = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&child)
+ .unwrap();
+ let mut hdr = [0u8; 48];
+ f.read_exact(&mut hdr).unwrap();
+ let l1_offset = u64::from_be_bytes(hdr[40..48].try_into().unwrap());
+
+ let l2_offset = 10u64 * cluster_size;
+ f.seek(SeekFrom::Start(l1_offset)).unwrap();
+ f.write_all(&(l2_offset | (1u64 << 63)).to_be_bytes())
+ .unwrap();
+
+ let mut l2_cluster = vec![0u8; cluster_size as usize];
+ l2_cluster[0..8].copy_from_slice(&1u64.to_be_bytes()); // bit 0 = zero cluster
+ f.seek(SeekFrom::Start(l2_offset)).unwrap();
+ f.write_all(&l2_cluster).unwrap();
+ }
+
+ // Layer itself must return explicit zeros for cluster 0 rather than None.
+ let mut child_chain = Qcow2Helper::open_flatten_chain(&child).unwrap();
+ let c0 = child_chain[0].read_cluster(0, cluster_size).unwrap();
+ assert_eq!(
+ c0.as_deref(),
+ Some(vec![0u8; cluster_size as usize].as_slice()),
+ "zero-flagged L2 entry must return explicit zero cluster, not fall through to backing"
+ );
+
+ let flat = dir.path().join("flat.qcow2");
+ Qcow2Helper::flatten(&child, &flat).unwrap();
+
+ let mut flat_chain = Qcow2Helper::open_flatten_chain(&flat).unwrap();
+ // Flattened standalone image must NOT contain backing's marker in cluster 0.
+ assert!(
+ flat_chain[0]
+ .read_cluster(0, cluster_size)
+ .unwrap()
+ .is_none(),
+ "zeroed cluster 0 must not resurrect backing data after flatten"
+ );
+ // Cluster 1 should still carry backing's marker (2).
+ let c1 = flat_chain[0]
+ .read_cluster(1, cluster_size)
+ .unwrap()
+ .unwrap();
+ assert_eq!(u64::from_be_bytes(c1[0..8].try_into().unwrap()), 2);
+ }
+
+ #[test]
+ fn test_flatten_sets_oflag_copied_and_passes_qemu_img_check() {
+ use std::io::{Read, Seek, SeekFrom};
+
+ let dir = TempDir::new().unwrap();
+ let cluster_size = 1u64 << CLUSTER_BITS;
+ let virtual_size = cluster_size * 2;
+
+ let base = dir.path().join("base.raw");
+ write_raw_disk(&base, virtual_size);
+
+ let child = dir.path().join("child.qcow2");
+ let _child_disk =
+ Qcow2Helper::create_cow_child_disk(&base, BackingFormat::Raw, &child, virtual_size)
+ .unwrap();
+
+ let flat = dir.path().join("flat.qcow2");
+ Qcow2Helper::flatten(&child, &flat).unwrap();
+
+ // Inspect L1[0] and L2[0] directly for QCOW2_OFLAG_COPIED (bit 63).
+ let mut f = std::fs::File::open(&flat).unwrap();
+ let mut hdr = [0u8; 48];
+ f.read_exact(&mut hdr).unwrap();
+ let l1_offset = u64::from_be_bytes(hdr[40..48].try_into().unwrap());
+
+ f.seek(SeekFrom::Start(l1_offset)).unwrap();
+ let mut l1_buf = [0u8; 8];
+ f.read_exact(&mut l1_buf).unwrap();
+ let l1_entry = u64::from_be_bytes(l1_buf);
+ assert_ne!(
+ l1_entry & (1u64 << 63),
+ 0,
+ "L1 entry must set QCOW2_OFLAG_COPIED (bit 63), got 0x{:016x}",
+ l1_entry
+ );
+
+ let l2_offset = l1_entry & 0x00FF_FFFF_FFFF_FE00;
+ f.seek(SeekFrom::Start(l2_offset)).unwrap();
+ let mut l2_buf = [0u8; 8];
+ f.read_exact(&mut l2_buf).unwrap();
+ let l2_entry = u64::from_be_bytes(l2_buf);
+ assert_ne!(
+ l2_entry & (1u64 << 63),
+ 0,
+ "L2 entry must set QCOW2_OFLAG_COPIED (bit 63), got 0x{:016x}",
+ l2_entry
+ );
+
+ if let Ok(output) = Command::new("qemu-img")
+ .args(["check", "-f", "qcow2"])
+ .arg(&flat)
+ .output()
+ {
+ assert!(
+ output.status.success(),
+ "qemu-img check failed (status={:?}): stdout={}, stderr={}",
+ output.status.code(),
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ }
+
+ #[test]
+ fn test_flatten_handles_short_eof_trailing_cluster() {
+ use std::io::{Read, Seek, SeekFrom};
+
+ let dir = TempDir::new().unwrap();
+ let cluster_size = 1u64 << CLUSTER_BITS;
+ let virtual_size = cluster_size * 2;
+
+ // Build a standalone flattened QCOW2 first, then simulate imago 0.2.2's
+ // partial trailing cluster write (12 KiB at end of file without extending
+ // the file to the full 64 KiB cluster boundary).
+ let base = dir.path().join("base.raw");
+ write_raw_disk(&base, virtual_size);
+
+ let child = dir.path().join("child.qcow2");
+ let _child_disk =
+ Qcow2Helper::create_cow_child_disk(&base, BackingFormat::Raw, &child, virtual_size)
+ .unwrap();
+
+ let standalone = dir.path().join("standalone.qcow2");
+ Qcow2Helper::flatten(&child, &standalone).unwrap();
+
+ let file_len = std::fs::metadata(&standalone).unwrap().len();
+ assert_eq!(file_len % cluster_size, 0);
+ let trailing_cluster_offset = file_len;
+ let partial_len = 12 * 1024usize;
+ {
+ let mut f = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&standalone)
+ .unwrap();
+ let mut hdr = [0u8; 48];
+ f.read_exact(&mut hdr).unwrap();
+ let l1_offset = u64::from_be_bytes(hdr[40..48].try_into().unwrap());
+ f.seek(SeekFrom::Start(l1_offset)).unwrap();
+ let mut l1_buf = [0u8; 8];
+ f.read_exact(&mut l1_buf).unwrap();
+ let l2_offset = u64::from_be_bytes(l1_buf) & 0x00FF_FFFF_FFFF_FE00;
+
+ // Point cluster 1 at `trailing_cluster_offset` and write only 12 KiB.
+ f.seek(SeekFrom::Start(l2_offset + 8)).unwrap();
+ f.write_all(&(trailing_cluster_offset | QCOW2_OFLAG_COPIED).to_be_bytes())
+ .unwrap();
+ let mut payload = vec![0u8; partial_len];
+ payload[0..8].copy_from_slice(&0xDEAD_BEEF_CAFE_BABEu64.to_be_bytes());
+ f.seek(SeekFrom::Start(trailing_cluster_offset)).unwrap();
+ f.write_all(&payload).unwrap();
+ }
+
+ let reflattened = dir.path().join("reflattened.qcow2");
+ Qcow2Helper::flatten(&standalone, &reflattened)
+ .expect("flatten must zero-pad a short trailing cluster at EOF");
+
+ let mut chain = Qcow2Helper::open_flatten_chain(&reflattened).unwrap();
+ let c1 = chain[0]
+ .read_cluster(1, cluster_size)
+ .unwrap()
+ .expect("cluster 1 must exist");
+ assert_eq!(
+ u64::from_be_bytes(c1[0..8].try_into().unwrap()),
+ 0xDEAD_BEEF_CAFE_BABEu64
+ );
+ assert!(
+ c1[partial_len..].iter().all(|&b| b == 0),
+ "unwritten tail past EOF must be zero-filled"
+ );
+
+ // Cluster pointing entirely past EOF (0 bytes readable) must still error.
+ let mut chain_mut = Qcow2Helper::open_flatten_chain(&standalone).unwrap();
+ let past_eof_cluster = (file_len + cluster_size * 4) | QCOW2_OFLAG_COPIED;
+ {
+ let mut f = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&standalone)
+ .unwrap();
+ let mut hdr = [0u8; 48];
+ f.read_exact(&mut hdr).unwrap();
+ let l1_offset = u64::from_be_bytes(hdr[40..48].try_into().unwrap());
+ f.seek(SeekFrom::Start(l1_offset)).unwrap();
+ let mut l1_buf = [0u8; 8];
+ f.read_exact(&mut l1_buf).unwrap();
+ let l2_offset = u64::from_be_bytes(l1_buf) & 0x00FF_FFFF_FFFF_FE00;
+ f.seek(SeekFrom::Start(l2_offset + 8)).unwrap();
+ f.write_all(&past_eof_cluster.to_be_bytes()).unwrap();
+ }
+ let err = chain_mut[0]
+ .read_cluster(1, cluster_size)
+ .expect_err("cluster starting past EOF must still fail");
+ assert!(err.to_string().contains("unexpected EOF"), "{err}");
+ }
}