rust-fs-ext4 0.8.0

Pure-Rust ext4 filesystem driver. Exposes a C ABI (fs_ext4_*) suitable for FFI from C/C++/Go/etc.
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
//! Tests for `fs_ext4_pwrite` — the streaming positional-write primitive.
//!
//! This covers the *real* streaming write path (replacing the old
//! "merge then whole-file replace" hack the WinFsp/FSKit adapters used to
//! do). Each test exercises one observable contract:
//!   1. Sequential chunked writes rebuild the same content as a single
//!      whole-file write. This is the "Explorer copy" path.
//!   2. Partial overwrite: writing into an existing file at a non-zero
//!      offset preserves bytes outside the write range.
//!   3. Sparse extension: pwrite past EOF leaves a sparse hole that
//!      reads as zeros, and bumps i_size correctly.
//!   4. Type guards: pwrite on a directory / non-regular-file fails
//!      cleanly with the right errno.
//!   5. Length cap: oversize `len` is rejected before any path resolution.

use fs_ext4::capi::*;
use std::ffi::{CStr, CString};
use std::fs;
use std::io::Write;
use std::os::raw::c_void;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};

const SRC: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/test-disks/ext4-basic.img");

fn scratch() -> PathBuf {
    static COUNTER: AtomicU32 = AtomicU32::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let dst = PathBuf::from(fs_ext4_test_support::temp_path!(
        "fs_ext4_capi_pwrite_{}_{n}.img",
        std::process::id()
    ));
    let mut out = fs::File::create(&dst).unwrap();
    out.write_all(&fs::read(SRC).unwrap()).unwrap();
    dst
}

fn last_err() -> String {
    unsafe {
        let p = fs_ext4_last_error();
        if p.is_null() {
            String::new()
        } else {
            CStr::from_ptr(p).to_string_lossy().into_owned()
        }
    }
}

fn read_full(fs_h: *mut fs_ext4_fs_t, path: &str, size: u64) -> Vec<u8> {
    let cp = CString::new(path).unwrap();
    let mut buf = vec![0u8; size as usize];
    let n =
        unsafe { fs_ext4_read_file(fs_h, cp.as_ptr(), buf.as_mut_ptr() as *mut c_void, 0, size) };
    assert!(
        n >= 0,
        "read_file({path}, 0, {size}) failed: rc={n}, err={}",
        last_err()
    );
    buf.truncate(n as usize);
    buf
}

fn stat_size(fs_h: *mut fs_ext4_fs_t, path: &str) -> u64 {
    let cp = CString::new(path).unwrap();
    let mut attr: fs_ext4_attr_t = unsafe { std::mem::zeroed() };
    let r = unsafe { fs_ext4_stat(fs_h, cp.as_ptr(), &mut attr) };
    assert_eq!(r, 0, "stat({path}) failed: {}", last_err());
    attr.size
}

/// Sequential 64KiB chunks rebuild a 1MiB file identically. Models the
/// Explorer/CopyFileEx cache-manager dispatch pattern that the old
/// merge-and-replace hack handled in O(filesize²); pwrite handles it in
/// O(chunk).
#[test]
fn sequential_chunks_match_whole_file() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null(), "mount: {}", last_err());

    let path = CString::new("/pwrite-streamed").unwrap();
    let ino = unsafe { fs_ext4_create(fs_h, path.as_ptr(), 0o644) };
    assert!(ino > 0, "create: {}", last_err());

    // Synthetic payload: deterministic + non-aligned-friendly. 1 MiB total.
    let total: usize = 1 << 20;
    let payload: Vec<u8> = (0..total)
        .map(|i| (i.wrapping_mul(31) ^ (i >> 8)) as u8)
        .collect();

    let chunk: usize = 64 * 1024;
    let mut written: usize = 0;
    while written < total {
        let len = chunk.min(total - written);
        let rc = unsafe {
            fs_ext4_pwrite(
                fs_h,
                path.as_ptr(),
                payload.as_ptr().add(written) as *const c_void,
                len as u64,
                written as u64,
            )
        };
        assert!(
            rc >= 0,
            "pwrite @{written}+{len} failed: rc={rc} err={}",
            last_err()
        );
        let expected_size = (written + len) as i64;
        assert_eq!(
            rc, expected_size,
            "pwrite returned size {rc}, expected {expected_size}"
        );
        written += len;
    }

    assert_eq!(stat_size(fs_h, "/pwrite-streamed"), total as u64);
    let read_back = read_full(fs_h, "/pwrite-streamed", total as u64);
    assert_eq!(
        read_back, payload,
        "streamed content does not match original"
    );

    unsafe { fs_ext4_umount(fs_h) };

    // Remount RO and re-verify so we know it persists past umount/remount,
    // which exercises the journal-replay + checksum-verification paths
    // that streaming writes most commonly trip up.
    let fs_h = unsafe { fs_ext4_mount(img_c.as_ptr()) };
    assert!(!fs_h.is_null(), "remount: {}", last_err());
    let read_back = read_full(fs_h, "/pwrite-streamed", total as u64);
    assert_eq!(read_back, payload, "remounted content does not match");
    unsafe { fs_ext4_umount(fs_h) };

    let _ = fs::remove_file(&img);
}

/// Partial overwrite of an existing file leaves bytes outside the write
/// range untouched. Models a Save-As that rewrites a header without
/// touching the rest of the file.
#[test]
fn partial_overwrite_preserves_outside_range() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null(), "mount: {}", last_err());

    let path = CString::new("/pwrite-overwrite").unwrap();
    let ino = unsafe { fs_ext4_create(fs_h, path.as_ptr(), 0o644) };
    assert!(ino > 0);

    // Initial content: 16 KiB of byte value 0xAA.
    let initial = vec![0xAAu8; 16 * 1024];
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            path.as_ptr(),
            initial.as_ptr() as *const c_void,
            initial.len() as u64,
            0,
        )
    };
    assert!(rc >= 0, "initial pwrite: {}", last_err());

    // Overwrite [4096, 8192) with 0xBB. The blocks [0, 4096) and
    // [8192, 16384) must remain 0xAA.
    let patch = vec![0xBBu8; 4096];
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            path.as_ptr(),
            patch.as_ptr() as *const c_void,
            patch.len() as u64,
            4096,
        )
    };
    assert!(rc >= 0, "patch pwrite: {}", last_err());
    assert_eq!(rc as u64, 16 * 1024, "size should be unchanged");

    let read_back = read_full(fs_h, "/pwrite-overwrite", 16 * 1024);
    assert_eq!(&read_back[0..4096], &[0xAAu8; 4096][..]);
    assert_eq!(&read_back[4096..8192], &[0xBBu8; 4096][..]);
    assert_eq!(&read_back[8192..16384], &[0xAAu8; 8192][..]);

    unsafe { fs_ext4_umount(fs_h) };
    let _ = fs::remove_file(&img);
}

/// pwrite past current EOF leaves a sparse hole (reads as zeros) and
/// bumps i_size to offset+len. The hole's logical blocks must NOT
/// consume physical blocks.
#[test]
fn pwrite_past_eof_creates_sparse_hole() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null());

    let path = CString::new("/pwrite-sparse").unwrap();
    let ino = unsafe { fs_ext4_create(fs_h, path.as_ptr(), 0o644) };
    assert!(ino > 0);

    // Empty file. pwrite "tail" at offset 32 KiB.
    let tail = b"end-of-sparse-file";
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            path.as_ptr(),
            tail.as_ptr() as *const c_void,
            tail.len() as u64,
            32 * 1024,
        )
    };
    assert!(rc >= 0, "sparse pwrite: {}", last_err());
    let expected_size = 32 * 1024 + tail.len() as u64;
    assert_eq!(rc as u64, expected_size);
    assert_eq!(stat_size(fs_h, "/pwrite-sparse"), expected_size);

    // First 32 KiB must read as zeros; tail must match.
    let mut buf = vec![0xFFu8; expected_size as usize];
    let n = unsafe {
        fs_ext4_read_file(
            fs_h,
            path.as_ptr(),
            buf.as_mut_ptr() as *mut c_void,
            0,
            expected_size,
        )
    };
    assert!(n >= 0, "read sparse: {}", last_err());
    assert_eq!(n as u64, expected_size);
    assert!(buf[..32 * 1024].iter().all(|&b| b == 0), "hole not zero");
    assert_eq!(&buf[32 * 1024..], tail);

    unsafe { fs_ext4_umount(fs_h) };
    let _ = fs::remove_file(&img);
}

#[test]
fn pwrite_on_directory_fails_with_eisdir() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null());

    let dir = CString::new("/subdir").unwrap();
    let payload = b"into the void";
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            dir.as_ptr(),
            payload.as_ptr() as *const c_void,
            payload.len() as u64,
            0,
        )
    };
    assert_eq!(rc, -1);
    assert_eq!(fs_ext4_last_errno(), 22 /* EINVAL */);

    unsafe { fs_ext4_umount(fs_h) };
    let _ = fs::remove_file(&img);
}

#[test]
fn pwrite_rejects_oversize_len() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null());

    let path = CString::new("/anything").unwrap();
    let dummy = [0u8; 1];
    let oversize: u64 = (1u64 << 30) + 1; // 1 byte past the 1 GiB cap
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            path.as_ptr(),
            dummy.as_ptr() as *const c_void,
            oversize,
            0,
        )
    };
    assert_eq!(rc, -1);
    assert_eq!(fs_ext4_last_errno(), 22 /* EINVAL */);
    let msg = last_err();
    assert!(
        msg.contains("len") && msg.contains("exceeds"),
        "expected len-cap message, got: {msg}"
    );

    unsafe { fs_ext4_umount(fs_h) };
    let _ = fs::remove_file(&img);
}

/// Force the extent tree past the inline-root capacity (4 entries). Writes
/// 5 single-block chunks at sparse-hole-separated offsets so each
/// `plan_insert_extent` call produces a NEW extent (no auto-merge with
/// neighbours). The 5th write trips `LEAF_FULL_NEEDS_PROMOTION` — without
/// the deep-insert fallback this would fail outright; with it, the tree
/// promotes to depth 1 and all reads round-trip.
#[test]
fn many_disjoint_writes_promote_extent_tree_depth() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null(), "mount: {}", last_err());

    let path = CString::new("/pwrite-deep-tree").unwrap();
    let ino = unsafe { fs_ext4_create(fs_h, path.as_ptr(), 0o644) };
    assert!(ino > 0, "create: {}", last_err());

    // Sparse-separated, single-block writes. The 4096-byte gap between
    // them ensures each lands in a brand new logical block range that
    // doesn't auto-merge with the prior extent (different logical_block
    // and the gap has no extent to be contiguous with).
    let block_bytes = 4096usize;
    let chunk = vec![0xCDu8; block_bytes];
    let offsets: [u64; 6] = [
        0,
        2 * block_bytes as u64,
        4 * block_bytes as u64,
        6 * block_bytes as u64,
        8 * block_bytes as u64,
        10 * block_bytes as u64,
    ];
    for &off in &offsets {
        let rc = unsafe {
            fs_ext4_pwrite(
                fs_h,
                path.as_ptr(),
                chunk.as_ptr() as *const c_void,
                chunk.len() as u64,
                off,
            )
        };
        assert!(
            rc >= 0,
            "pwrite @{off} failed (deep-insert path): rc={rc} err={}",
            last_err()
        );
    }

    // Each written block must read back as 0xCD; each gap as 0x00 (sparse).
    let total_size = *offsets.last().unwrap() + chunk.len() as u64;
    let mut buf = vec![0xFFu8; total_size as usize];
    let n = unsafe {
        fs_ext4_read_file(
            fs_h,
            path.as_ptr(),
            buf.as_mut_ptr() as *mut c_void,
            0,
            total_size,
        )
    };
    assert!(n >= 0, "read after deep promotion: {}", last_err());
    for &off in &offsets {
        let written_slice = &buf[off as usize..off as usize + block_bytes];
        assert!(
            written_slice.iter().all(|&b| b == 0xCD),
            "written block at {off} not preserved after deep promotion"
        );
    }
    // Verify a couple of gaps stayed sparse (zeroed).
    for &off in &offsets[..offsets.len() - 1] {
        let gap_start = off as usize + block_bytes;
        let gap_end = gap_start + block_bytes;
        assert!(
            buf[gap_start..gap_end].iter().all(|&b| b == 0),
            "sparse gap at byte {gap_start}..{gap_end} not zero"
        );
    }

    unsafe { fs_ext4_umount(fs_h) };

    // Remount and re-verify — exercises the deep-tree read path against
    // freshly-checksummed metadata.
    let fs_h = unsafe { fs_ext4_mount(img_c.as_ptr()) };
    assert!(!fs_h.is_null(), "remount: {}", last_err());
    let mut buf2 = vec![0xFFu8; total_size as usize];
    let n = unsafe {
        fs_ext4_read_file(
            fs_h,
            path.as_ptr(),
            buf2.as_mut_ptr() as *mut c_void,
            0,
            total_size,
        )
    };
    assert!(n >= 0, "read after remount: {}", last_err());
    assert_eq!(buf2, buf, "content drift across remount");
    unsafe { fs_ext4_umount(fs_h) };

    let _ = fs::remove_file(&img);
}

#[test]
fn pwrite_zero_len_is_noop() {
    let img = scratch();
    let img_c = CString::new(img.to_str().unwrap()).unwrap();
    let fs_h = unsafe { fs_ext4_mount_rw(img_c.as_ptr()) };
    assert!(!fs_h.is_null());

    let path = CString::new("/pwrite-zerolen").unwrap();
    let ino = unsafe { fs_ext4_create(fs_h, path.as_ptr(), 0o644) };
    assert!(ino > 0);
    // Seed some content so we can verify the no-op didn't truncate.
    let seed = b"keepme";
    let rc = unsafe {
        fs_ext4_pwrite(
            fs_h,
            path.as_ptr(),
            seed.as_ptr() as *const c_void,
            seed.len() as u64,
            0,
        )
    };
    assert!(rc >= 0);

    let rc = unsafe { fs_ext4_pwrite(fs_h, path.as_ptr(), std::ptr::null(), 0, 999) };
    assert!(rc >= 0, "zero-len pwrite at any offset must succeed");
    assert_eq!(rc as u64, seed.len() as u64, "size unchanged");

    let read_back = read_full(fs_h, "/pwrite-zerolen", seed.len() as u64);
    assert_eq!(read_back, seed);

    unsafe { fs_ext4_umount(fs_h) };
    let _ = fs::remove_file(&img);
}