diff --git a/AGENTS.md b/AGENTS.md index c43cff4..ca15052 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,7 +100,8 @@ streaming import design. its extents. - **Fixed format choices**, modeled on e2fsprogs: 4 KiB blocks, 256-byte inodes, 32-bit block numbers, 32-byte group descriptors, sparse superblocks, - extents, **no journal**. Changing any of these is a design decision, so ask + extents, **a jbd2 journal** (v2 superblock, big-endian, no checksum + features; mke2fs-compatible sizes). Changing any of these is a design decision, so ask before doing it. - **Cross-platform.** Windows is the primary target but the code also compiles on Unix (`#[cfg(unix)]` / `#[cfg(windows)]` in `host/tree.rs`, diff --git a/docs/supported-features.md b/docs/supported-features.md index 4551639..3f197e8 100644 --- a/docs/supported-features.md +++ b/docs/supported-features.md @@ -6,7 +6,8 @@ The formatter currently creates valid ext4 images with a 4 KiB block size and 256-byte inodes. It writes sparse-superblock layout (including backups and group descriptors), block and inode bitmaps, inode tables, the root directory, and `lost+found`. Every image carries a random filesystem UUID (`s_uuid`), -as `mke2fs` writes one, alongside the random directory-hash seed. +as `mke2fs` writes one, alongside the random directory-hash seed, and every +image of at least 8 MiB a jbd2 journal. It supports regular files across fragmented block runs, building multi-level extent trees when needed. Directories have `.` and `..` entries, update parent @@ -92,7 +93,11 @@ those made by `mke2fs`, are rejected. The image size is fixed. See - Image creation runs on Windows; Linux tools are only optional verification. - Layout is modeled on `e2fsprogs` and written directly using ext4 structures. - The implementation uses 32-bit block addresses and 32-byte group descriptors. -- Images are deliberately created without a journal. +- Every image of at least 8 MiB carries a jbd2 journal (v2 superblock, + big-endian, no checksum features; mke2fs-compatible sizes), so the guest + kernel recovers a crashed VM by replaying it on mount. Smaller images get + none, mirroring mke2fs. The snapshot reader never replays a journal; a + non-empty one is refused. - Sparse files, inline/shared xattrs, and SELinux validation are not implemented yet. - Host import preserves the portable subset of metadata supported by the host diff --git a/src/ext4/extent.rs b/src/ext4/extent.rs index 4b72c27..e6381f1 100644 --- a/src/ext4/extent.rs +++ b/src/ext4/extent.rs @@ -20,11 +20,15 @@ pub(crate) struct ExtentTree { pub(crate) tree_blocks: Vec, } -/// Builds initialized leaf extents from physical runs, assigning consecutive logical blocks. +/// Builds initialized leaf extents from physical runs, assigning consecutive +/// logical blocks. Run lengths from `plan_data_blocks` are capped at 32,768 +/// blocks (the initialized-extent limit), which is asserted here: a longer +/// run would truncate `ee_len` silently. pub(super) fn extents_for_runs(runs: &[(u32, u32)]) -> Vec { let mut logical = 0u32; runs.iter() .map(|&(start, len)| { + debug_assert!(len <= u32::from(EXT_INIT_MAX_LEN)); let extent = Ext4Extent { ee_block: logical, ee_len: len as u16, diff --git a/src/ext4/format/mod.rs b/src/ext4/format/mod.rs index 83ade67..997f42d 100644 --- a/src/ext4/format/mod.rs +++ b/src/ext4/format/mod.rs @@ -28,6 +28,11 @@ pub const EXT4_INDEXES_PER_BLOCK: usize = pub const EXT4_BAD_INO: u32 = 1; pub const EXT4_ROOT_INO: u32 = 2; pub const EXT4_FIRST_INO: u32 = 11; +/// The jbd2 journal inode mke2fs places its journal in. +pub const EXT4_JOURNAL_INO: u32 = 8; +/// `s_jnl_backup_type` value: `s_jnl_blocks` holds the journal's first +/// block numbers (e2fsprogs EXT3_JNL_BACKUP_BLOCKS). +pub const EXT3_JNL_BACKUP_BLOCKS: u8 = 1; // File Types pub const EXT4_FT_UNKNOWN: u8 = 0; @@ -94,6 +99,11 @@ pub const EXT2_ERROR_FS: u16 = 0x0002; /// part of [`Ext4SuperBlock`] that is kept as opaque padding. pub const EXT4_SUPERBLOCK_FLAGS_OFFSET: usize = 0x160; pub const EXT2_FLAGS_UNSIGNED_HASH: u32 = 0x0002; +/// What mke2fs writes: dirhash input bytes are sign-extended, matching +/// this crate's `ext4_dirhash_half_md4`. Without it, the kernel records +/// its own (unsigned) choice in `s_flags` on the first mount, and the +/// strict open then rejects the image as using unsigned hashes. +pub const EXT2_FLAGS_SIGNED_HASH: u32 = 0x0001; #[repr(C, packed)] #[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] @@ -147,7 +157,22 @@ pub struct Ext4SuperBlock { pub s_def_hash_version: u8, pub _s_jnl_backup_type: u8, pub _s_desc_size: u16, - pub _padding: [u8; 768], + pub s_default_mount_opts: u32, + pub s_first_meta_bg: u32, + pub s_mkfs_time: u32, + /// Backup of the journal inode's first block numbers, valid when + /// `s_jnl_backup_type` is set (kernel `s_jnl_blocks[17]`, offset 0x10C). + pub s_jnl_blocks: [u32; 17], + /// 64-bit block counts; this writer uses 32-bit numbers, so these stay 0. + pub s_blocks_count_hi: u32, + pub s_r_blocks_count_hi: u32, + pub s_free_blocks_count_hi: u32, + pub s_min_extra_isize: u16, + pub s_want_extra_isize: u16, + /// Miscellaneous flags. SIGNED_HASH records that dirhash input bytes + /// are sign-extended, which both this crate and the kernel honor. + pub s_flags: u32, + pub _padding: [u8; 668], } impl Default for Ext4SuperBlock { @@ -206,7 +231,20 @@ impl Default for Ext4SuperBlock { s_def_hash_version: dirhash::DX_HASH_HALF_MD4, _s_jnl_backup_type: 0, _s_desc_size: 0, - _padding: [0; 768], + s_default_mount_opts: 0, + s_first_meta_bg: 0, + s_mkfs_time: 0, + s_jnl_blocks: [0; 17], + s_blocks_count_hi: 0, + s_r_blocks_count_hi: 0, + s_free_blocks_count_hi: 0, + s_min_extra_isize: 0, + s_want_extra_isize: 0, + // Like mke2fs: dirhash bytes are sign-extended (see + // format::dirhash). Without this the kernel records its own + // unsigned choice on first mount. + s_flags: EXT2_FLAGS_SIGNED_HASH, + _padding: [0; 668], } } } diff --git a/src/ext4/journal.rs b/src/ext4/journal.rs new file mode 100644 index 0000000..12b8488 --- /dev/null +++ b/src/ext4/journal.rs @@ -0,0 +1,329 @@ +//! The jbd2 journal ext4kit writes into every new image, so the guest +//! kernel recovers a crashed VM by replaying it on mount instead of needing +//! e2fsprogs in the guest. +//! +//! The journal is written once, here, and never touched again: the builder +//! does not replay or checkpoint — the kernel is the only writer after +//! create. The on-disk form mirrors `mke2fs` (inode 8, extent-mapped, +//! contiguous blocks, a v2 journal superblock without checksum +//! features), except placement: mke2fs puts the journal mid-filesystem, +//! ext4kit at the first free data block. All jbd2 fields are +//! **big-endian**, unlike every ext4 field. + +use super::Ext4ImageBuilder; +use super::extent::extents_for_runs; +use crate::ext4::format::*; +use anyhow::{Result, bail}; + +/// The jbd2 journal superblock: the header words plus the fields mke2fs +/// writes into the first block of the journal. +pub(crate) struct JournalSuperblockBytes { + /// Length of the journal in blocks, including the superblock block. + maxlen: u32, + /// The filesystem UUID, stored verbatim (not endian-swapped). + uuid: [u8; 16], +} + +impl JournalSuperblockBytes { + /// Serializes the jsb. Offsets per e2fsprogs `kernel-jbd.h` + /// https://github.com/tytso/e2fsprogs/blob/master/lib/ext2fs/kernel-jbd.h#L183 + fn to_bytes(&self) -> [u8; BLOCK_SIZE] { + let mut jsb = [0u8; BLOCK_SIZE]; + let put = |jsb: &mut [u8; BLOCK_SIZE], offset: usize, value: u32| { + jsb[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + }; + put(&mut jsb, 0x00, crate::ext4::reader::JBD2_MAGIC); + // JBD2_SUPERBLOCK_V2: the kernel and e2fsck expect a v2 jsb. + put(&mut jsb, 0x04, crate::ext4::reader::JBD2_SUPERBLOCK_V2); + put(&mut jsb, 0x08, 0); // h_sequence of the superblock itself + put(&mut jsb, 0x0C, BLOCK_SIZE as u32); // s_blocksize + put(&mut jsb, 0x10, self.maxlen); // s_maxlen + put(&mut jsb, 0x14, 1); // s_first: first log block after the jsb + put(&mut jsb, 0x18, 1); // s_sequence: first transaction to use + put(&mut jsb, 0x1C, 0); // s_start: the log is empty + put(&mut jsb, 0x20, 0); // s_errno + put(&mut jsb, 0x24, 0); // s_feature_compat: no checksums + put(&mut jsb, 0x28, 0); // s_feature_incompat + put(&mut jsb, 0x2C, 0); // s_feature_ro_compat + jsb[0x30..0x40].copy_from_slice(&self.uuid); + put(&mut jsb, 0x40, 1); // s_nr_users: this filesystem only + put(&mut jsb, 0x44, 0); // s_dynsuper: external journals only + put(&mut jsb, 0x48, 0); // s_max_transaction: 0 = no limit + put(&mut jsb, 0x4C, 0); // s_max_trans_data: 0 = no limit + put(&mut jsb, 0x50, 0); // s_checksum_type + padding2: JBD2_CHECKSUM_NONE + put(&mut jsb, 0x54, 0); // s_num_fc_blks: no fast commit + put(&mut jsb, 0xFC, 0); // s_checksum: ignored without checksum features + // s_users (0x100..0x200): only scanned when mounting an external + // journal, so an internal one leaves it zeroed like mke2fs does. + jsb + } +} + +/// The journal size `ext2fs_default_journal_size` picks for an image of +/// `blocks` blocks: `None` below 8 MiB (mke2fs writes no journal there), +/// otherwise 4 MiB under 128 MiB and a growing ladder above. An honest +/// journal never exceeds its filesystem. +pub(crate) fn default_journal_size(blocks: u64) -> Option { + if blocks < 2048 { + return None; + } + let journal: u64 = if blocks < 32768 { + 1024 + } else if blocks < 256 * 1024 { + 4096 + } else if blocks < 512 * 1024 { + 8192 + } else if blocks < 4096 * 1024 { + 16384 + } else if blocks < 8192 * 1024 { + 32768 + } else if blocks < 16384 * 1024 { + 65536 + } else if blocks < 32768 * 1024 { + 131072 + } else { + 262144 + }; + (journal < blocks).then_some(journal as u32) +} + +impl Ext4ImageBuilder { + /// Creates the journal: a contiguous run of `journal_blocks` data + /// blocks owned by extent-mapped inode 8, a fresh v2 journal + /// superblock in the first block, and the superblock feature bits and + /// backup fields mke2fs writes. Only called by the constructors; the + /// blocks are taken from the fresh data area, so the allocation cannot + /// fragment the journal. + pub(crate) fn create_journal(&mut self) -> Result<()> { + let fs_blocks = u64::from(self.superblock.s_blocks_count_lo); + let Some(journal_blocks) = default_journal_size(fs_blocks) else { + return Ok(()); + }; + let free_blocks = self.superblock.s_free_blocks_count_lo; + if u64::from(free_blocks) < u64::from(journal_blocks) { + bail!("no room for a {journal_blocks}-block journal: {free_blocks} free blocks"); + } + + // Plan the run before touching any bitmap (the preflight rule), then + // commit it; on a fresh image this is one contiguous extent. + let runs = self.plan_data_blocks(0, journal_blocks)?; + if runs.is_empty() { + bail!("the journal needs {journal_blocks} blocks"); + } + self.commit_data_blocks(&runs); + + let first_block = runs[0].0; + + // Inode 8: mode 0600, root-owned, extent-mapped, its block list in + // the superblock backup. The extent tree is written with the same + // machinery as file payloads, so a journal too large for one extent + // (over 32768 blocks) still lays out correctly. + // + // This breaks "preflight, then commit" on purpose: a journal with + // more than 4 runs needs an external tree block, and + // write_extent_tree allocates it after the data blocks are + // committed. That is acceptable only because the constructors are + // the sole callers and turn any failure into a panic, so no + // half-built builder ever escapes. + let size = u64::from(journal_blocks) * BLOCK_SIZE as u64; + let mut inode = Ext4Inode { + i_mode: S_IFREG | 0o600, + i_links_count: 1, + i_flags: EXT4_EXTENTS_FL, + i_size_lo: size as u32, + i_size_high: (size >> 32) as u32, + ..Ext4Inode::default() + }; + let tree_blocks = self.write_extent_tree(0, &mut inode, &extents_for_runs(&runs))?; + let data_blocks: u32 = runs.iter().map(|&(_, len)| len).sum(); + inode.i_blocks_lo = (data_blocks + tree_blocks) * (BLOCK_SIZE as u32 / 512); + let local_index = (EXT4_JOURNAL_INO - 1) as usize; + self.groups[0].inode_table[local_index] = inode; + self.mark_inode_used(EXT4_JOURNAL_INO); + + // A fresh jsb in the journal's first block; the rest of the journal + // stays zeroed like the surrounding image. + let jsb = JournalSuperblockBytes { + maxlen: journal_blocks, + uuid: self.superblock.s_uuid, + } + .to_bytes(); + let offset = first_block as usize * BLOCK_SIZE; + self.disk_data[offset..offset + BLOCK_SIZE].copy_from_slice(&jsb); + + // Superblock feature bit, journal location and backup, as mke2fs + // writes them. + self.superblock.s_feature_compat |= EXT4_FEATURE_COMPAT_HAS_JOURNAL; + self.superblock._s_journal_inum = EXT4_JOURNAL_INO; + self.superblock._s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS; + // The backup (mkjournal.c): the journal inode's extent root as 15 + // u32s, then i_size_high, then i_size. e2fsck rebuilds inode 8 + // from this backup when the inode is damaged, and a writable + // e2fsck rewrites it when it doesn't match, so the format must + // be exact. + let mut backup = [0u32; 17]; + let (words, _) = inode.i_block.as_chunks::<4>(); + for (word, chunk) in backup.iter_mut().zip(words) { + *word = u32::from_le_bytes(*chunk); + } + backup[15] = inode.i_size_high; + backup[16] = inode.i_size_lo; + self.superblock.s_jnl_blocks = backup; + Ok(()) + } + + /// The journal size the constructors would pick for this image's block + /// count, in blocks. Used by the sizing estimate so a recommended image + /// has room for tree plus journal. + pub fn journal_blocks_for_size(size_mib: usize) -> Option { + default_journal_size((size_mib as u64) * 1024 * 1024 / BLOCK_SIZE as u64) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ext4::PosixMetadata; + use crate::ext4::extent::extent_len; + use crate::ext4::test_support::fresh_builder; + + #[test] + fn the_journal_ladder_matches_mke2fs() { + // 8 MiB is mke2fs's minimum for a journal; below it, none. + assert_eq!(default_journal_size(2047), None); + // Under 128 MiB: 4 MiB, the size the WSL experiments showed. + assert_eq!(default_journal_size(2048), Some(1024)); + assert_eq!(default_journal_size(4096), Some(1024)); + assert_eq!(default_journal_size(32767), Some(1024)); + // The growing ladder above. Every tier was measured against + // mke2fs 1.47.2 in WSL (the size depends only on the block count): 256 MiB + // → 16 MiB, 512 MiB → 16 MiB, 1 GiB → 32 MiB, 2–8 GiB → 64 MiB, + // 20 GiB → 128 MiB, 32 GiB → 256 MiB, 64 GiB → 512 MiB. + assert_eq!(default_journal_size(32768), Some(4096)); + assert_eq!(default_journal_size(65536), Some(4096)); + assert_eq!(default_journal_size(256 * 1024), Some(8192)); + // Each tier starts exactly at its bound (the ladder compares with + // `<`), so check both sides of every boundary. + assert_eq!(default_journal_size(512 * 1024 - 1), Some(8192)); + assert_eq!(default_journal_size(512 * 1024), Some(16384)); + assert_eq!(default_journal_size(4096 * 1024 - 1), Some(16384)); + assert_eq!(default_journal_size(4096 * 1024), Some(32768)); + assert_eq!(default_journal_size(8192 * 1024 - 1), Some(32768)); + assert_eq!(default_journal_size(8192 * 1024), Some(65536)); + assert_eq!(default_journal_size(16384 * 1024 - 1), Some(65536)); + assert_eq!(default_journal_size(16384 * 1024), Some(131072)); + assert_eq!(default_journal_size(32768 * 1024 - 1), Some(131072)); + // The 1 GiB cap: mke2fs never goes larger. + assert_eq!(default_journal_size(32768 * 1024), Some(262144)); + assert_eq!(default_journal_size(u64::from(u32::MAX)), Some(262144)); + } + + #[test] + fn a_new_image_carries_an_empty_extent_mapped_journal() -> Result<()> { + let builder = fresh_builder()?; + let compat = builder.superblock.s_feature_compat; + let journal_inum = builder.superblock._s_journal_inum; + assert_ne!(compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL, 0); + assert_eq!(journal_inum, EXT4_JOURNAL_INO); + + // The reader (which validates the jsb big-endian) must see an + // empty journal; serialize first, like write_to_file does. + let mut builder = builder; + builder.commit_metadata(); + let (_, state) = crate::ext4::reader::ImageReader::from_memory(builder.disk_data.to_vec())?; + assert!(state.has_journal); + assert!(state.journal_empty); + assert!(!state.mounted); + + let inode = builder.inode(EXT4_JOURNAL_INO); + let (mode, flags, size_lo, blocks_lo) = ( + inode.i_mode, + inode.i_flags, + inode.i_size_lo, + inode.i_blocks_lo, + ); + assert_eq!(mode & S_IFMT, S_IFREG); + assert_eq!(mode & 0o777, 0o600); + assert_eq!(flags & EXT4_EXTENTS_FL, EXT4_EXTENTS_FL); + let journal_blocks = default_journal_size(4096).unwrap(); + assert_eq!( + size_lo, + journal_blocks * BLOCK_SIZE as u32, + "a 16 MiB image carries the 4 MiB journal" + ); + let extents = builder.get_inode_extents(inode)?; + let mapped: u32 = extents.iter().map(extent_len).sum(); + assert_eq!(mapped, journal_blocks); + assert_eq!(blocks_lo, journal_blocks * (BLOCK_SIZE as u32 / 512)); + + // The backup: the journal inode's extent root as 15 u32s, then + // i_size_high, then i_size (mkjournal.c format, verified against + // a real mke2fs image's superblock). + let backup = builder.superblock.s_jnl_blocks; + let mut i_block_words = [0u32; 15]; + let (words, _) = inode.i_block.as_chunks::<4>(); + for (word, chunk) in i_block_words.iter_mut().zip(words) { + *word = u32::from_le_bytes(*chunk); + } + assert_eq!(&backup[..15], &i_block_words); + assert_eq!(backup[15], { inode.i_size_high }); + assert_eq!(backup[16], { inode.i_size_lo }); + + // Free counts must reflect the journal: reopen recomputes them. + let reloaded = Ext4ImageBuilder::from_image(builder.disk_data.to_vec())?; + let (free, expected) = ( + reloaded.superblock.s_free_blocks_count_lo, + builder.superblock.s_free_blocks_count_lo, + ); + assert_eq!(free, expected); + Ok(()) + } + + #[test] + fn a_journal_opt_out_image_has_no_journal() -> Result<()> { + let mut builder = Ext4ImageBuilder::new_without_journal(16); + builder.create_root_dir()?; + builder.create_lost_and_found()?; + builder.reserve_inodes(); + let compat = builder.superblock.s_feature_compat; + assert_eq!(compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL, 0); + // Inode 8 is still reserved by reserve_inodes, but holds no journal. + let journal_inode = builder.inode(EXT4_JOURNAL_INO); + let (flags, size_lo) = (journal_inode.i_flags, journal_inode.i_size_lo); + assert_eq!(flags & EXT4_EXTENTS_FL, 0); + assert_eq!(size_lo, 0); + builder.commit_metadata(); + let reloaded = Ext4ImageBuilder::from_image(builder.disk_data.to_vec())?; + let reloaded_compat = reloaded.superblock.s_feature_compat; + assert_eq!(reloaded_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL, 0); + Ok(()) + } + + #[test] + fn images_below_the_mke2fs_threshold_get_no_journal() -> Result<()> { + // 4 MiB = 1024 blocks, below mke2fs's 2048-block journal minimum. + let mut builder = Ext4ImageBuilder::new(4); + builder.create_root_dir()?; + builder.create_lost_and_found()?; + builder.reserve_inodes(); + let compat = builder.superblock.s_feature_compat; + assert_eq!(compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL, 0); + Ok(()) + } + + #[test] + fn the_journal_survives_edits_and_a_reopen() -> Result<()> { + let mut builder = fresh_builder()?; + let meta = PosixMetadata::default(); + builder.add_file(EXT4_ROOT_INO, "f.txt", b"hi", &meta)?; + builder.commit_metadata(); + let reloaded = Ext4ImageBuilder::from_image(builder.disk_data.to_vec())?; + let reloaded_compat = reloaded.superblock.s_feature_compat; + assert_ne!(reloaded_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL, 0); + // The journal blocks stay allocated; the reader still sees it empty. + let (_, state) = + crate::ext4::reader::ImageReader::from_memory(reloaded.disk_data.to_vec())?; + assert!(state.journal_empty); + Ok(()) + } +} diff --git a/src/ext4/layout.rs b/src/ext4/layout.rs index 0e6d0ec..c4607bc 100644 --- a/src/ext4/layout.rs +++ b/src/ext4/layout.rs @@ -380,13 +380,17 @@ impl Ext4ImageBuilder { Ok(()) } - /// Reserves ext4's fixed low-numbered inodes; returns no value. + /// Reserves ext4's fixed low-numbered inodes; returns no value. Inodes + /// already allocated — the journal's inode 8 on images that carry one — + /// are skipped, so the free-inode accounting never double-counts. pub fn reserve_inodes(&mut self) { self.mark_inode_used(EXT4_BAD_INO); // Skip Root (#2) and lost+found (#11), mark remaining 3..=10 for inode_num in (EXT4_ROOT_INO + 1)..EXT4_FIRST_INO { - self.mark_inode_used(inode_num); + if !self.is_inode_allocated(inode_num) { + self.mark_inode_used(inode_num); + } } } diff --git a/src/ext4/mod.rs b/src/ext4/mod.rs index 4efe971..de363de 100644 --- a/src/ext4/mod.rs +++ b/src/ext4/mod.rs @@ -20,6 +20,7 @@ mod file; pub mod format; mod htree; mod inode; +mod journal; mod layout; use layout::PlannedGeometry; mod open; @@ -84,6 +85,8 @@ impl Ext4ImageBuilder { /// blocks is dropped, so the /// filesystem can be slightly smaller than the requested image; a size /// too small for a single block group panics with a clear message. + /// Every image of at least 8 MiB carries a jbd2 journal, as `mke2fs` + /// writes one; smaller images get none, mirroring `mke2fs`. pub fn new(size_mb: usize) -> Self { let image_size_bytes = size_mb * 1024 * 1024; let geometry = Self::plan_geometry(image_size_bytes / BLOCK_SIZE).unwrap_or_else(|err| { @@ -92,10 +95,39 @@ impl Ext4ImageBuilder { Self::new_with_storage(geometry, DiskData::Memory(vec![0; image_size_bytes])) } + /// Creates an in-memory builder without a journal, for tests and for + /// callers that manage their own recovery; see + /// [`Ext4ImageBuilder::new`]. + pub fn new_without_journal(size_mb: usize) -> Self { + let image_size_bytes = size_mb * 1024 * 1024; + let geometry = Self::plan_geometry(image_size_bytes / BLOCK_SIZE).unwrap_or_else(|err| { + panic!("cannot lay out an image of {image_size_bytes} bytes: {err}") + }); + Self::new_with_storage_impl(geometry, DiskData::Memory(vec![0; image_size_bytes]), false) + } + /// Creates an image directly in `output_path`. The mapping is file-backed, /// so imported payload pages can be flushed instead of retaining a second - /// complete image-sized heap allocation. + /// complete image-sized heap allocation. Every image of at least 8 MiB + /// carries a jbd2 journal. pub fn new_file(size_mb: usize, output_path: impl AsRef) -> std::io::Result { + Self::new_file_with_journal(size_mb, output_path, true) + } + + /// Creates a file-backed image without a journal; see + /// [`Ext4ImageBuilder::new_file`]. + pub fn new_file_without_journal( + size_mb: usize, + output_path: impl AsRef, + ) -> std::io::Result { + Self::new_file_with_journal(size_mb, output_path, false) + } + + fn new_file_with_journal( + size_mb: usize, + output_path: impl AsRef, + journal: bool, + ) -> std::io::Result { let image_size_bytes = size_mb .checked_mul(1024 * 1024) .ok_or_else(|| std::io::Error::other("image size overflow"))?; @@ -113,13 +145,22 @@ impl Ext4ImageBuilder { // the file remains at its fixed length for the lifetime of the // mapping, and all access is mediated through the uniquely owned MmapMut. let mapping = unsafe { MmapOptions::new().map_mut(&file)? }; - Ok(Self::new_with_storage( + Ok(Self::new_with_storage_impl( geometry, DiskData::File { mapping, path }, + journal, )) } fn new_with_storage(geometry: PlannedGeometry, disk_data: DiskData) -> Self { + Self::new_with_storage_impl(geometry, disk_data, true) + } + + fn new_with_storage_impl( + geometry: PlannedGeometry, + disk_data: DiskData, + journal: bool, + ) -> Self { if BYTES_PER_INODE_RATIO < BLOCK_SIZE { panic!("BYTES_PER_INODE_RATIO must be greater than or equal to BLOCK_SIZE"); } @@ -214,6 +255,11 @@ impl Ext4ImageBuilder { }; builder.init_layout(); + if journal { + builder + .create_journal() + .expect("a fresh image always has room for its journal"); + } builder } } diff --git a/src/ext4/open.rs b/src/ext4/open.rs index 0ac11e1..e525c6c 100644 --- a/src/ext4/open.rs +++ b/src/ext4/open.rs @@ -435,57 +435,36 @@ mod tests { (|sb: &mut Ext4SuperBlock| sb.s_feature_incompat |= FLEX_BG) as fn(&mut _), |sb| sb.s_feature_ro_compat |= METADATA_CSUM, |sb| sb.s_feature_compat &= !EXT4_FEATURE_COMPAT_DIR_INDEX, - // needs_recovery without a journal is meaningless; only the - // kernel writes it, and only together with has_journal. - |sb| sb.s_feature_incompat |= EXT4_FEATURE_INCOMPAT_RECOVER, ] { let (_, mut bytes) = written_image(); with_superblock(&mut bytes, change); assert!(load_error(bytes).contains("unsupported ext4 features")); } - } - - /// Turns inode 8 into an extent-mapped inode whose first block holds a - /// valid empty jbd2 superblock, so a superblock with `has_journal` set - /// and `_s_journal_inum` 8 points at a parsable, empty journal. - fn add_empty_journal(builder: &Ext4ImageBuilder, bytes: &mut [u8]) { - let table = builder.group_descriptors[0].bg_inode_table_lo as usize; - let inode_offset = table * BLOCK_SIZE + 7 * INODE_SIZE; - let mut inode = - Ext4Inode::read_from_bytes(&bytes[inode_offset..inode_offset + INODE_SIZE]).unwrap(); - inode.i_flags |= EXT4_EXTENTS_FL; - inode.i_blocks_lo = 8; // 4 KiB data block = 8 sectors - let jsb_block = builder.superblock.s_blocks_count_lo - 1; - let header = Ext4ExtentHeader { - eh_magic: EXT4_EH_MAGIC, - eh_entries: 1, - eh_max: EXT4_EXTENTS_IN_INODE as u16, - eh_depth: 0, - eh_generation: 0, - }; - inode.i_block[..12].copy_from_slice(header.as_bytes()); - let extent = Ext4Extent { - ee_block: 0, - ee_len: 1, - ee_start_hi: 0, - ee_start_lo: jsb_block, - }; - inode.i_block[12..24].copy_from_slice(extent.as_bytes()); - bytes[inode_offset..inode_offset + INODE_SIZE].copy_from_slice(inode.as_bytes()); - // The jsb: big-endian magic and v2 blocktype, s_start 0 at 0x1C. - let jsb_offset = jsb_block as usize * BLOCK_SIZE; - let jsb = &mut bytes[jsb_offset..jsb_offset + BLOCK_SIZE]; - jsb.fill(0); - jsb[..4].copy_from_slice(&crate::ext4::reader::JBD2_MAGIC.to_be_bytes()); - jsb[4..8].copy_from_slice(&crate::ext4::reader::JBD2_SUPERBLOCK_V2.to_be_bytes()); - jsb[0x0C..0x10].copy_from_slice(&(BLOCK_SIZE as u32).to_be_bytes()); + // needs_recovery on a journal-less image is meaningless; only the + // kernel writes it, and only together with has_journal. + let mut builder = Ext4ImageBuilder::new_without_journal(16); + builder.create_root_dir().unwrap(); + builder.create_lost_and_found().unwrap(); + builder.reserve_inodes(); + builder.commit_metadata(); + let mut bytes = builder.disk_data.to_vec(); + with_superblock(&mut bytes, |superblock| { + superblock.s_feature_incompat |= EXT4_FEATURE_INCOMPAT_RECOVER; + }); + let error = load_error(bytes); + assert!( + error.contains("unsupported ext4 features"), + "unexpected error: {error}" + ); } #[test] fn rejects_a_journal_feature_without_a_journal_inode() { + // The fixture carries a real journal, so the meaningful corruption + // is clearing the journal inode number while keeping has_journal. let (_, mut bytes) = written_image(); with_superblock(&mut bytes, |superblock| { - superblock.s_feature_compat |= EXT4_FEATURE_COMPAT_HAS_JOURNAL; + superblock._s_journal_inum = 0; }); let error = load_error(bytes); assert!( @@ -496,11 +475,10 @@ mod tests { #[test] fn rejects_a_mounted_journaled_image_with_the_mounted_message() { - let (builder, mut bytes) = written_image(); - add_empty_journal(&builder, &mut bytes); + // The fixture's journal is real and empty; needs_recovery on top of + // it is the mounted marker. + let (_, mut bytes) = written_image(); with_superblock(&mut bytes, |superblock| { - superblock.s_feature_compat |= EXT4_FEATURE_COMPAT_HAS_JOURNAL; - superblock._s_journal_inum = 8; superblock.s_feature_incompat |= EXT4_FEATURE_INCOMPAT_RECOVER; }); let error = load_error(bytes); @@ -512,15 +490,16 @@ mod tests { #[test] fn rejects_a_non_empty_journal() { + // Corrupt the fixture's real journal superblock: s_start at jsb + // byte 0x1C, big-endian, one unprocessed transaction. let (builder, mut bytes) = written_image(); - add_empty_journal(&builder, &mut bytes); + let journal_inode = builder.inode(8); + let extents = builder.get_inode_extents(journal_inode).unwrap(); + let jsb_block = extents[0].ee_start_lo; with_superblock(&mut bytes, |superblock| { - superblock.s_feature_compat |= EXT4_FEATURE_COMPAT_HAS_JOURNAL; superblock._s_journal_inum = 8; }); - // s_start at jsb byte 0x1C, big-endian: an unprocessed transaction. - let jsb_block = builder.superblock.s_blocks_count_lo as usize - 1; - bytes[jsb_block * BLOCK_SIZE + 0x1C..jsb_block * BLOCK_SIZE + 0x20] + bytes[jsb_block as usize * BLOCK_SIZE + 0x1C..jsb_block as usize * BLOCK_SIZE + 0x20] .copy_from_slice(&1u32.to_be_bytes()); let error = load_error(bytes); assert!( diff --git a/src/host/mod.rs b/src/host/mod.rs index 08607d4..6c0a35e 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -118,9 +118,13 @@ impl Ext4ImageBuilder { // One block bitmap and one inode bitmap per group, plus primary // and sparse-super backup metadata. This is conservative. let ext4_metadata_blocks = inode_table_blocks + groups * 4; + // Every image of at least 8 MiB carries a journal (4 MiB under + // 128 MiB, a growing ladder above), which is not free space. + let journal_blocks = u64::from(Self::journal_blocks_for_size(size_mib).unwrap_or(0)); let allocated_blocks = usage .data_blocks .checked_add(ext4_metadata_blocks as u64) + .and_then(|blocks| blocks.checked_add(journal_blocks)) .ok_or_else(|| anyhow::anyhow!("allocation estimate overflow"))?; let required_with_free_space = allocated_blocks .checked_mul(110) diff --git a/tests/cli.rs b/tests/cli.rs index ae30832..15022f5 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -166,6 +166,54 @@ fn created_images_carry_a_random_filesystem_uuid() { Some(&b'4'), "a version-4 UUID like mke2fs writes: {uuid}" ); + // The journal: inode 8, the mke2fs size for the image, an empty log. + // debugfs pads the columns, so match whole trimmed lines. + let stats_field = |name: &str| -> String { + stats + .lines() + .find_map(|line| line.trim_start().strip_prefix(name)) + .map(|rest| rest.trim().to_owned()) + .unwrap_or_else(|| panic!("debugfs stats must report {name}: {stats}")) + }; + assert_eq!(stats_field("Journal inode:"), "8"); + let journal = image.debugfs("stat <8>"); + assert!( + journal.contains("Size: 4194304"), + "a 16 MiB image carries the 4 MiB journal: {journal}" + ); + // An empty log: debugfs stats does not report Journal start for a + // journal it never loaded, but dumpe2fs -h does. + if let Some(tools) = e2fsprogs_tools() { + let output = common::run_tool(tools, "dumpe2fs", &["-h", &tools.target(&out)]); + let dump = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!( + dump.lines() + .any(|line| line.split_whitespace().collect::>().join(" ") + == "Journal start: 0"), + "a freshly created journal must be empty: {dump}" + ); + + // A writable e2fsck has nothing to change. `-n` skips the + // s_jnl_blocks backup check entirely, so only a `-y` run on a copy + // catches a backup that doesn't match inode 8's extent root. + let copy = out.with_extension("fsck.img"); + std::fs::copy(&out, ©).unwrap(); + let output = common::run_tool(tools, "e2fsck", &["-fy", &tools.target(©)]); + let report = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!( + output.status.success() && !report.contains("MODIFIED"), + "a writable e2fsck must leave a fresh image untouched ({}):\n{report}", + output.status + ); + } } /// The jsb decoder must agree with `dumpe2fs` on an image `mke2fs` made: a @@ -329,6 +377,64 @@ fn reader_matches_the_journal_state_machine_of_a_mounted_filesystem() { expect(&base.join("unmounted.img"), false, true); } +/// The kernel must accept an ext4kit-written journal: mount the image the +/// binary just created, write a file, sync, and cleanly unmount. After the +/// unmount the image reopens (a clean unmount leaves an empty journal and +/// VALID_FS set), the written file is visible, and e2fsck stays clean. +/// +/// Needs root for the loop mount: WSL `wsl -u root` or native passwordless +/// `sudo -n`; other environments skip with a note. +#[test] +fn the_kernel_mounts_a_created_image_and_replays_its_journal() { + use ext4kit::ext4::reader::ImageReader; + + let tmp = TempDir::new().unwrap(); + let dir = tmp.path().join("src"); + fs::create_dir(&dir).unwrap(); + fs::write(dir.join("a.txt"), "hi\n").unwrap(); + let out = tmp.path().join("out.img"); + create(&["--add", &format!("{}:/opt", arg(&dir))], &out); + + let Some(tools) = e2fsprogs_tools() else { + return; + }; + let target = tools.target(&out); + let script = format!( + "set -e\n\ + umount /mnt/ext4kit-mount 2>/dev/null || true\n\ + mkdir -p /mnt/ext4kit-mount\n\ + mount -o loop \"{target}\" /mnt/ext4kit-mount\n\ + echo kernel-accepted > /mnt/ext4kit-mount/proof.txt\n\ + sync\n\ + umount /mnt/ext4kit-mount" + ); + let Some(output) = common::root_shell(tools, &script) else { + return; + }; + assert!( + output.status.success(), + "the kernel did not mount the image (its journal was rejected?): {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + + // A clean unmount: the image reopens, the journal is empty, the + // kernel-written file is there, and e2fsck has nothing to say. + let (reader, state) = ImageReader::open(&out).unwrap(); + assert!(state.has_journal); + assert!(state.journal_empty, "clean unmount empties the journal"); + assert!(!state.mounted); + let _ = reader; + let Some(image) = Image::check(&out) else { + return; + }; + assert_eq!( + image.cat("/proof.txt"), + "kernel-accepted\n", + "the file written by the kernel must be readable back" + ); +} + #[test] fn large_directory_gets_an_htree_index() { let tmp = TempDir::new().unwrap(); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index d15c5a3..d054709 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -176,9 +176,22 @@ impl E2fsprogs { /// Runs `command`, retrying WSL transport failures. Under parallel test load /// the WSL service intermittently fails a client outright with exit code -1 /// (`Wsl/Service/E_UNEXPECTED`, `0x8007274c` timeouts); the e2fsprogs tools -/// never exit -1, so the signature is unambiguous. Native runs pass `false` -/// and never retry. +/// never exit -1, so the signature is unambiguous. WSL invocations also +/// hold a global lock, because the service degrades badly when several +/// test threads hammer it at once — retries alone cannot save an +/// every-attempt-fails storm. Native runs pass `false`, never retry and +/// never lock. fn output_with_retry(command: &mut Command, retry_wsl_failures: bool) -> std::process::Output { + // The lock is per test binary (each integration-test crate gets its own + // copy), which is enough: within one binary the parallel test threads + // are what overwhelm the service. + static WSL_LOCK: OnceLock> = OnceLock::new(); + let _guard = retry_wsl_failures.then(|| { + WSL_LOCK + .get_or_init(Default::default) + .lock() + .expect("another thread panicked while holding the WSL lock") + }); try_output_with_retry(command, retry_wsl_failures).expect("failed to run e2fsprogs") }