fstool 0.4.14

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! qcow2 — QEMU's copy-on-write disk format, as a [`BlockDevice`].
//!
//! Supports reading v2 and v3 images; writes Phase B (refcount + create)
//! and unsupported features (compression, encryption, snapshots, backing
//! files, external data files, extended L2 entries) error with
//! [`crate::Error::Unsupported`] on open.
//!
//! ## Layout
//!
//! A qcow2 file is a sequence of fixed-size clusters (typically 64 KiB).
//! The first cluster carries the header. From there, three sets of
//! metadata clusters live alongside data clusters:
//!
//! - **Refcount table** (one or more clusters, pointed at by
//!   `refcount_table_offset`): array of u64 entries pointing to refcount
//!   *blocks*.
//! - **Refcount blocks**: array of u16 refcounts, one per data/metadata
//!   cluster. Used to find free clusters when allocating.
//! - **L1 table** (`l1_table_offset`): array of u64 entries pointing to
//!   **L2 tables**, which in turn point to data clusters.
//!
//! `total_size()` returns the virtual size from the header; the backing
//! file is allocate-on-write, so a freshly-created 100 GiB image is only
//! a few clusters on disk until you write to it.
//!
//! ## Concurrency
//!
//! qcow2 is not safe to share between writers. `Qcow2Backend` holds the
//! file open `O_RDWR` without an exclusive lock — the caller is expected
//! to not have another writer pointed at the same file.

pub mod compress;
pub mod header;
pub mod l1l2;
pub mod refcount;

use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;

use header::Header;
use l1l2::{COPIED, L1L2, Mapping};
use refcount::Refcount;

use super::BlockDevice;
use crate::Result;

/// A [`BlockDevice`] backed by a qcow2 image.
pub struct Qcow2Backend {
    file: File,
    header: Header,
    cluster_size: u64,
    l1l2: L1L2,
    refcount: Refcount,
    /// Current backing-file size in bytes; grows when allocate-on-write
    /// extends the file past the previous EOF.
    file_len: u64,
    /// Virtual cursor for the `Read`/`Write`/`Seek` impls.
    cursor: u64,
    /// Single-entry cache of the most recently decompressed cluster, keyed by
    /// its virtual cluster-start offset, so sequential sub-cluster reads of a
    /// compressed cluster don't re-inflate it.
    decomp_cache: Option<(u64, Vec<u8>)>,
    /// True when the backing `File` was opened `O_RDONLY` by
    /// [`Self::open_read_only`]. Writes return `PermissionDenied`
    /// early so callers get a clean refusal rather than a deep
    /// syscall-level error.
    read_only: bool,
}

impl std::fmt::Debug for Qcow2Backend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Qcow2Backend")
            .field("version", &self.header.version)
            .field("cluster_size", &self.cluster_size)
            .field("virtual_size", &self.header.size)
            .field("l1_size", &self.header.l1_size)
            .finish()
    }
}

impl Qcow2Backend {
    /// Open an existing qcow2 file read+write. Errors with `Unsupported`
    /// if the image uses features fstool doesn't implement.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::open_inner(path.as_ref(), false)
    }

    /// Open an existing qcow2 file read-only. The backing `File` is
    /// opened `O_RDONLY` — any write that slips past the BlockDevice
    /// API would fail at the syscall. The qcow2 read paths
    /// (L1/L2/refcount load, cluster reads) work unchanged.
    pub fn open_read_only<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::open_inner(path.as_ref(), true)
    }

    fn open_inner(path: &Path, read_only: bool) -> Result<Self> {
        let mut opts = OpenOptions::new();
        opts.read(true);
        if !read_only {
            opts.write(true);
        }
        let mut file = opts.open(path)?;
        // Read the first sector so the header decoder can reach the
        // `compression_type` byte at offset 104 (a valid qcow2 is always at
        // least one cluster, so 512 bytes are guaranteed present).
        let mut buf = [0u8; 512];
        file.read_exact(&mut buf)?;
        let header = Header::decode(&buf)?;
        let cluster_size = header.cluster_size();
        let l1l2 = L1L2::load(&mut file, &header)?;
        let refcount = Refcount::load(&mut file, &header)?;
        let file_len = file.metadata()?.len();
        Ok(Self {
            file,
            header,
            cluster_size,
            l1l2,
            refcount,
            file_len,
            cursor: 0,
            decomp_cache: None,
            read_only,
        })
    }

    /// Format a fresh qcow2 v3 image at `path`. The file is created
    /// (truncating any existing one) and seeded with the header, an
    /// empty refcount table + refcount block, and an L1 table. All
    /// data clusters are allocate-on-write.
    pub fn create<P: AsRef<Path>>(path: P, virtual_size: u64, cluster_size: u32) -> Result<Self> {
        if !cluster_size.is_power_of_two() || cluster_size < 512 {
            return Err(crate::Error::InvalidArgument(format!(
                "qcow2: cluster_size {cluster_size} must be a power of two ≥ 512"
            )));
        }
        let cs = cluster_size as u64;
        let cluster_bits = cs.trailing_zeros();

        // Compute L1 size: one L2 cluster covers (cs/8) clusters, which
        // covers (cs/8) * cs virtual bytes. l1 entries needed:
        let l2_coverage = (cs / 8) * cs;
        let l1_size = virtual_size.div_ceil(l2_coverage) as u32;
        // L1 size must be a power of two? No — but it does need to fit
        // in some number of clusters. Round up `l1_size` to a multiple
        // of (cs / 8) so the L1 table is a whole number of clusters.
        let l1_per_cluster = (cs / 8) as u32;
        let l1_clusters = l1_size.div_ceil(l1_per_cluster);
        let l1_size = l1_clusters * l1_per_cluster;

        // Layout (in clusters):
        //   0:                header
        //   1:                refcount table (1 cluster)
        //   2:                refcount block 0
        //   3..3+l1_clusters: L1 table
        let refcount_table_cluster = 1u64;
        let refcount_block_cluster = 2u64;
        let l1_first_cluster = 3u64;
        let next_free_cluster = l1_first_cluster + l1_clusters as u64;
        let file_len = next_free_cluster * cs;

        // The clusters we just laid out must all have refcount=1.
        let initial: Vec<u64> = {
            let mut v = Vec::new();
            v.push(0); // header
            v.push(refcount_table_cluster);
            v.push(refcount_block_cluster);
            for i in 0..l1_clusters as u64 {
                v.push(l1_first_cluster + i);
            }
            v
        };

        // Build the header.
        let header = Header {
            version: header::VERSION_V3,
            backing_file_offset: 0,
            backing_file_size: 0,
            cluster_bits,
            size: virtual_size,
            crypt_method: 0,
            l1_size,
            l1_table_offset: l1_first_cluster * cs,
            refcount_table_offset: refcount_table_cluster * cs,
            refcount_table_clusters: 1,
            nb_snapshots: 0,
            snapshots_offset: 0,
            incompatible_features: 0,
            compatible_features: 0,
            autoclear_features: 0,
            refcount_order: 4,
            header_length: header::V3_HEADER_LEN as u32,
            compression_type: 0,
        };

        // Create the backing file at exactly `file_len` bytes,
        // zero-filled by `set_len` (sparse).
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path.as_ref())?;
        file.set_len(file_len)?;

        // Write the header at byte 0, padded to the cluster.
        file.seek(SeekFrom::Start(0))?;
        let mut cluster0 = vec![0u8; cs as usize];
        cluster0[..header::V3_HEADER_LEN].copy_from_slice(&header.encode_v3());
        file.write_all(&cluster0)?;

        // L1 table starts all-zero — set_len already zero-filled it.
        let mut l1l2 = L1L2 {
            cluster_size: cs,
            cluster_bits,
            l2_entries: (cs / 8) as usize,
            l1: vec![0u64; l1_size as usize],
            l1_table_offset: l1_first_cluster * cs,
            l2_cache: std::collections::HashMap::new(),
            l2_cache_cap: 32,
        };

        // Refcount table + initial refcount block live in memory; flush
        // them so the on-disk view matches.
        let mut refcount = Refcount::new_fresh(
            cs,
            refcount_table_cluster * cs,
            refcount_block_cluster * cs,
            &initial,
        );
        refcount.flush(&mut file)?;
        l1l2.flush(&mut file)?;
        file.sync_data()?;

        Ok(Self {
            file,
            header,
            cluster_size: cs,
            l1l2,
            refcount,
            file_len,
            cursor: 0,
            decomp_cache: None,
            read_only: false,
        })
    }

    /// Read-only convenience: open and confirm this is a qcow2 image.
    pub fn probe<P: AsRef<Path>>(path: P) -> Result<bool> {
        let mut file = File::open(path.as_ref())?;
        let mut magic = [0u8; 4];
        if file.read_exact(&mut magic).is_err() {
            return Ok(false);
        }
        Ok(magic == header::MAGIC)
    }

    /// The decoded header — exposed for diagnostics.
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Write `buf` to virtual offset `offset`, allocating physical
    /// clusters and L2 tables on demand.
    fn write_virtual(&mut self, mut offset: u64, mut buf: &[u8]) -> Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        if self.read_only {
            return Err(crate::Error::Io(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "Qcow2Backend opened read-only — write refused",
            )));
        }
        let end = offset
            .checked_add(buf.len() as u64)
            .ok_or(crate::Error::OutOfBounds {
                offset,
                len: buf.len() as u64,
                size: self.header.size,
            })?;
        if end > self.header.size {
            return Err(crate::Error::OutOfBounds {
                offset,
                len: buf.len() as u64,
                size: self.header.size,
            });
        }
        let cs = self.cluster_size;
        while !buf.is_empty() {
            let in_cluster = offset & (cs - 1);
            let take = ((cs - in_cluster) as usize).min(buf.len());
            let (chunk, rest) = buf.split_at(take);
            let cluster_start = offset - in_cluster;
            let mapping = self.l1l2.map(&mut self.file, cluster_start)?;
            // Sparse fast path: writing zeros to a cluster that has no
            // physical mapping is a no-op — an unallocated qcow2 cluster
            // already reads back as zero, so allocating one just to fill
            // it with zeros bloats the file on disk for no semantic gain.
            // This is what made an 8 GiB ext2 repacked into qcow2 take
            // 8 GiB on disk: `Ext::format_with` calls `dev.zero_range`
            // across the whole image before formatting.
            if chunk.iter().all(|&b| b == 0) && matches!(mapping, Mapping::Unallocated) {
                offset += take as u64;
                buf = rest;
                continue;
            }
            let phys = match mapping {
                // Writing to a compressed cluster: copy it out to a fresh
                // plain cluster first (qemu's behaviour), then write into that.
                Mapping::Compressed {
                    host_offset,
                    byte_len,
                } => self.cow_compressed_cluster(cluster_start, host_offset, byte_len)?,
                _ => self.ensure_mapping(cluster_start)?,
            };
            self.file.seek(SeekFrom::Start(phys + in_cluster))?;
            self.file.write_all(chunk)?;
            offset += take as u64;
            buf = rest;
        }
        Ok(())
    }

    /// Copy a compressed cluster out to a freshly allocated *plain* cluster:
    /// decompress it, write the bytes verbatim, repoint the L2 entry, and
    /// release the old compressed cluster's host-range refcounts. Returns the
    /// new plain cluster's physical byte offset, ready for the caller to write
    /// the actual (partial) update into.
    fn cow_compressed_cluster(
        &mut self,
        cluster_start: u64,
        host_offset: u64,
        byte_len: u64,
    ) -> Result<u64> {
        self.fill_decomp_cache(cluster_start, host_offset, byte_len)?;
        let content = self.decomp_cache.as_ref().unwrap().1.clone();

        let data_cluster = self
            .refcount
            .alloc_cluster(&mut self.file, &mut self.file_len)?;
        let new_off = data_cluster * self.cluster_size;
        let new_end = new_off + self.cluster_size;
        if new_end > self.file_len {
            self.file_len = new_end;
        }
        self.file.set_len(self.file_len)?;
        self.file.seek(SeekFrom::Start(new_off))?;
        self.file.write_all(&content)?;

        // Repoint the L2 entry at the new plain cluster.
        let (l1_idx, l2_idx, _) = self.l1l2.split_addr(cluster_start);
        let l2_off = self.l1l2.l1[l1_idx] & l1l2::OFFSET_MASK;
        self.l1l2.set_l2_entry(l2_off, l2_idx, new_off | COPIED)?;

        // Drop the old compressed cluster's references (it may have shared
        // host clusters with neighbours, which keep a positive refcount).
        self.refcount
            .release_range(&mut self.file, host_offset, byte_len)?;
        // The cluster is now plain; invalidate the decompressed-bytes cache so
        // the subsequent in-place write isn't shadowed by stale data.
        self.decomp_cache = None;
        Ok(new_off)
    }

    /// Make sure the cluster covering virtual offset `vaddr_cluster_aligned`
    /// has a physical mapping, allocating one if not. Returns the
    /// physical byte offset of the cluster.
    fn ensure_mapping(&mut self, vaddr: u64) -> Result<u64> {
        let (l1_idx, l2_idx, _) = self.l1l2.split_addr(vaddr);
        let l1_entry = self.l1l2.l1[l1_idx];
        let l2_off = l1_entry & l1l2::OFFSET_MASK;
        let (l2_off, _) = if l2_off == 0 {
            // Allocate an L2 cluster.
            let cluster_idx = self
                .refcount
                .alloc_cluster(&mut self.file, &mut self.file_len)?;
            // Make sure the file is long enough to hold the new L2 cluster.
            let new_end = (cluster_idx + 1) * self.cluster_size;
            if new_end > self.file_len {
                self.file_len = new_end;
            }
            self.file.set_len(self.file_len)?;
            let new_l2_off = cluster_idx * self.cluster_size;
            self.l1l2.insert_empty_l2(new_l2_off);
            self.l1l2.set_l1(l1_idx, new_l2_off | COPIED);
            (new_l2_off, l2_idx)
        } else {
            // Cache-load the L2 if it isn't already in cache.
            let _ = self.l1l2.lookup(&mut self.file, vaddr)?;
            (l2_off, l2_idx)
        };

        let l2_entry = self
            .l1l2
            .l2_cache
            .get(&l2_off)
            .expect("L2 just loaded/created")
            .entries[l2_idx];
        let data_off = l2_entry & l1l2::OFFSET_MASK;
        if data_off != 0 {
            return Ok(data_off);
        }
        // Allocate a data cluster.
        let data_cluster = self
            .refcount
            .alloc_cluster(&mut self.file, &mut self.file_len)?;
        let new_data_off = data_cluster * self.cluster_size;
        let new_end = new_data_off + self.cluster_size;
        if new_end > self.file_len {
            self.file_len = new_end;
        }
        self.file.set_len(self.file_len)?;
        self.l1l2
            .set_l2_entry(l2_off, l2_idx, new_data_off | COPIED)?;
        Ok(new_data_off)
    }

    /// Ensure `decomp_cache` holds the decompressed bytes of the compressed
    /// cluster at virtual `cluster_start`. Reads `byte_len` compressed bytes
    /// from `host_offset`, decodes them with the image's codec, and pads the
    /// result out to a full cluster.
    fn fill_decomp_cache(
        &mut self,
        cluster_start: u64,
        host_offset: u64,
        byte_len: u64,
    ) -> Result<()> {
        if self.decomp_cache.as_ref().map(|(k, _)| *k) == Some(cluster_start) {
            return Ok(());
        }
        let mut comp = vec![0u8; byte_len as usize];
        self.file.seek(SeekFrom::Start(host_offset))?;
        self.file.read_exact(&mut comp)?;
        let cs = self.cluster_size as usize;
        let mut plain = compress::decompress_cluster(self.header.compression_type, &comp, cs)?;
        plain.resize(cs, 0); // qcow2 compresses full clusters; pad short output
        self.decomp_cache = Some((cluster_start, plain));
        Ok(())
    }

    /// Read `buf.len()` bytes starting at virtual offset `offset`. Walks
    /// the L1/L2 mapping cluster-by-cluster; unallocated clusters return
    /// zeroes.
    fn read_virtual(&mut self, mut offset: u64, mut buf: &mut [u8]) -> Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        let end = offset
            .checked_add(buf.len() as u64)
            .ok_or(crate::Error::OutOfBounds {
                offset,
                len: buf.len() as u64,
                size: self.header.size,
            })?;
        if end > self.header.size {
            return Err(crate::Error::OutOfBounds {
                offset,
                len: buf.len() as u64,
                size: self.header.size,
            });
        }
        let cs = self.cluster_size;
        while !buf.is_empty() {
            let in_cluster = offset & (cs - 1);
            let take = ((cs - in_cluster) as usize).min(buf.len());
            let (chunk, rest) = buf.split_at_mut(take);
            let cluster_start = offset - in_cluster;
            match self.l1l2.map(&mut self.file, cluster_start)? {
                Mapping::Normal(phys) => {
                    self.file.seek(SeekFrom::Start(phys + in_cluster))?;
                    self.file.read_exact(chunk)?;
                }
                Mapping::Unallocated => {
                    chunk.fill(0);
                }
                Mapping::Compressed {
                    host_offset,
                    byte_len,
                } => {
                    self.fill_decomp_cache(cluster_start, host_offset, byte_len)?;
                    let cluster = &self.decomp_cache.as_ref().unwrap().1;
                    let from = in_cluster as usize;
                    chunk.copy_from_slice(&cluster[from..from + take]);
                }
            }
            offset += take as u64;
            buf = rest;
        }
        Ok(())
    }
}

impl Read for Qcow2Backend {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let remaining = self.header.size.saturating_sub(self.cursor);
        let n = (buf.len() as u64).min(remaining) as usize;
        if n == 0 {
            return Ok(0);
        }
        self.read_virtual(self.cursor, &mut buf[..n])
            .map_err(io::Error::other)?;
        self.cursor += n as u64;
        Ok(n)
    }
}

impl Write for Qcow2Backend {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let remaining = self.header.size.saturating_sub(self.cursor);
        let n = (buf.len() as u64).min(remaining) as usize;
        if n == 0 {
            return Ok(0);
        }
        self.write_virtual(self.cursor, &buf[..n])
            .map_err(io::Error::other)?;
        self.cursor += n as u64;
        Ok(n)
    }

    fn flush(&mut self) -> io::Result<()> {
        // The qcow2 layer flushes its metadata on `sync`; the std
        // `Write::flush` contract just says "drain buffered data", and
        // we have no internal buffer.
        Ok(())
    }
}

impl Seek for Qcow2Backend {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let size = self.header.size;
        let new = match pos {
            SeekFrom::Start(n) => n,
            SeekFrom::End(n) => size
                .checked_add_signed(n)
                .ok_or_else(|| io::Error::other("qcow2: seek past i64 bounds"))?,
            SeekFrom::Current(n) => self
                .cursor
                .checked_add_signed(n)
                .ok_or_else(|| io::Error::other("qcow2: seek past i64 bounds"))?,
        };
        self.cursor = new;
        Ok(self.cursor)
    }
}

impl BlockDevice for Qcow2Backend {
    fn block_size(&self) -> u32 {
        512
    }

    fn total_size(&self) -> u64 {
        self.header.size
    }

    fn sync(&mut self) -> Result<()> {
        if self.read_only {
            // No writes happened; nothing to flush. Calling
            // l1l2.flush / refcount.flush on a RO-opened file would
            // try to write back potentially clean caches and fail at
            // the syscall — skip them entirely.
            return Ok(());
        }
        self.l1l2.flush(&mut self.file)?;
        self.refcount.flush(&mut self.file)?;
        self.file.sync_data()?;
        Ok(())
    }

    fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<()> {
        self.read_virtual(offset, buf)
    }

    fn write_at(&mut self, offset: u64, buf: &[u8]) -> Result<()> {
        self.write_virtual(offset, buf)
    }

    fn zero_range(&mut self, offset: u64, len: u64) -> Result<()> {
        if len == 0 {
            return Ok(());
        }
        let size = self.header.size;
        let end = offset
            .checked_add(len)
            .ok_or(crate::Error::OutOfBounds { offset, len, size })?;
        if end > size {
            return Err(crate::Error::OutOfBounds { offset, len, size });
        }
        // Sparse-aware: an unallocated qcow2 cluster already reads as
        // zero, so a zero_range over unallocated clusters is a no-op.
        // Only clusters that already carry a physical mapping need to
        // be overwritten with zeros (we don't punch/discard yet — that
        // would require touching the refcount table). This is what
        // keeps an 8 GiB virtual image at a few megabytes on disk when
        // the FS formatter prefaces format with a full-device zero.
        let cs = self.cluster_size;
        let zero = [0u8; 4096];
        let mut cur = offset;
        while cur < end {
            let in_cluster = cur & (cs - 1);
            let take = (cs - in_cluster).min(end - cur);
            let cluster_start = cur - in_cluster;
            let phys = match self.l1l2.map(&mut self.file, cluster_start)? {
                Mapping::Unallocated => None,
                Mapping::Normal(phys) => Some(phys),
                // A compressed cluster carries real data; copy it out to a
                // plain cluster so we can zero the requested sub-range in place.
                Mapping::Compressed {
                    host_offset,
                    byte_len,
                } => Some(self.cow_compressed_cluster(cluster_start, host_offset, byte_len)?),
            };
            if let Some(phys) = phys {
                self.file.seek(SeekFrom::Start(phys + in_cluster))?;
                let mut remaining = take;
                while remaining > 0 {
                    let n = remaining.min(zero.len() as u64) as usize;
                    self.file.write_all(&zero[..n])?;
                    remaining -= n as u64;
                }
            }
            cur += take;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Smoke test using a hand-rolled minimal qcow2 image: header, an
    /// empty L1 entry, and a small refcount table. The reader should
    /// return zeros for every offset (everything unallocated).
    #[test]
    fn read_returns_zeros_on_fresh_image() {
        // Generate a minimal v3 image in a tempfile and read it back.
        // Cluster size 64 KiB, virtual size 64 MiB, one L1 entry pointing
        // at nothing (everything unallocated).
        use std::io::Write;
        use tempfile::NamedTempFile;

        let tmp = NamedTempFile::new().unwrap();
        let cluster_size = 65536u64;
        let virtual_size = 64u64 * 1024 * 1024;
        let h = Header {
            version: header::VERSION_V3,
            backing_file_offset: 0,
            backing_file_size: 0,
            cluster_bits: 16,
            size: virtual_size,
            crypt_method: 0,
            // virtual_size / cluster_size = 1024 clusters; one L2 cluster
            // (8192 entries) covers 8192 clusters, so l1_size = 1.
            l1_size: 1,
            l1_table_offset: 3 * cluster_size,
            refcount_table_offset: cluster_size,
            refcount_table_clusters: 1,
            nb_snapshots: 0,
            snapshots_offset: 0,
            incompatible_features: 0,
            compatible_features: 0,
            autoclear_features: 0,
            refcount_order: 4,
            header_length: header::V3_HEADER_LEN as u32,
            compression_type: 0,
        };
        let mut f = std::fs::File::create(tmp.path()).unwrap();
        // Cluster 0: header padded to a cluster.
        let mut c0 = vec![0u8; cluster_size as usize];
        c0[..header::V3_HEADER_LEN].copy_from_slice(&h.encode_v3());
        f.write_all(&c0).unwrap();
        // Cluster 1: refcount table, all-zero (we don't read it on the
        // pure read path).
        f.write_all(&vec![0u8; cluster_size as usize]).unwrap();
        // Cluster 2: refcount block, all-zero.
        f.write_all(&vec![0u8; cluster_size as usize]).unwrap();
        // Cluster 3: L1 table, one entry == 0 (unallocated).
        f.write_all(&vec![0u8; cluster_size as usize]).unwrap();
        f.sync_all().unwrap();
        drop(f);

        let mut back = Qcow2Backend::open(tmp.path()).unwrap();
        assert_eq!(back.total_size(), virtual_size);
        assert_eq!(back.header.cluster_size(), cluster_size);

        // Reading from anywhere returns zeros.
        let mut buf = [0xffu8; 4096];
        back.read_at(0, &mut buf).unwrap();
        assert!(buf.iter().all(|&b| b == 0));

        let mut buf2 = [0xffu8; 8192];
        back.read_at(virtual_size - 8192, &mut buf2).unwrap();
        assert!(buf2.iter().all(|&b| b == 0));

        // OOB rejection.
        let mut tail = [0u8; 16];
        let err = back.read_at(virtual_size, &mut tail).unwrap_err();
        assert!(matches!(err, crate::Error::OutOfBounds { .. }));

        // Read trait works via cursor.
        back.seek(SeekFrom::Start(0)).unwrap();
        let mut chunk = [0u8; 1024];
        let n = back.read(&mut chunk).unwrap();
        assert_eq!(n, 1024);
        assert!(chunk.iter().all(|&b| b == 0));
    }
}