Skip to content

Commit 8b16a3d

Browse files
yunusarda-sudoRenjiSann
authored andcommitted
dd: extend a sparse output before syncing it
1 parent 7913995 commit 8b16a3d

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

‎src/uu/dd/src/dd.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1405,12 +1405,13 @@ fn finalize<T>(
14051405
// not yet written.
14061406
let wstat_update = output.flush()?;
14071407

1408-
// Sync the output, if configured to do so.
1409-
output.sync()?;
1410-
14111408
// With `conv=sparse`, trailing zero blocks were skipped, not written.
1409+
// Set the final length first so that `fsync`/`fdatasync` covers it.
14121410
output.extend_sparse()?;
14131411

1412+
// Sync the output, if configured to do so.
1413+
output.sync()?;
1414+
14141415
// Print the final read/write statistics.
14151416
let wstat = wstat + wstat_update;
14161417
let prog_update = ProgUpdate::new(rstat, wstat, start.elapsed(), ProgUpdateType::Final);

‎tests/by-util/test_dd.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1574,6 +1574,41 @@ fn test_sparse_notrunc_extends_file() {
15741574
assert_eq!(at.metadata("outfile").len(), 1024);
15751575
}
15761576

1577+
/// With `conv=sparse,fsync` (or `fdatasync`), the trailing zero block extends
1578+
/// the file before the sync, so the sync covers the final length.
1579+
#[cfg(target_os = "linux")]
1580+
#[uutests::wasi_ignore(NoSubprocessSpawning)]
1581+
#[rstest]
1582+
#[case::fsync("fsync")]
1583+
#[case::fdatasync("fdatasync")]
1584+
fn test_sparse_extends_before_sync(#[case] sync: &str) {
1585+
let (at, _ucmd) = at_and_ucmd!();
1586+
at.write_bytes("infile", &[0; 4096]);
1587+
let trace = at.plus("trace");
1588+
let Ok(out) = Command::new("strace")
1589+
.arg("-o")
1590+
.arg(&trace)
1591+
.args(["-e", "trace=fsync,fdatasync,ftruncate"])
1592+
.arg(get_tests_binary())
1593+
.arg("dd")
1594+
.args(["if=infile", "of=outfile", "bs=4096", "status=none"])
1595+
.arg(format!("conv=sparse,{sync}"))
1596+
.current_dir(at.as_string())
1597+
.output()
1598+
else {
1599+
return; // missing strace
1600+
};
1601+
if String::from_utf8_lossy(&out.stderr).contains("ptrace") {
1602+
return; // tracing not permitted here
1603+
}
1604+
assert!(out.status.success());
1605+
assert_eq!(at.metadata("outfile").len(), 4096);
1606+
let trace = at.read("trace");
1607+
let extend = trace.find(", 4096)").expect("final ftruncate");
1608+
let synced = trace.find(&format!("{sync}(")).expect("sync call");
1609+
assert!(extend < synced, "{trace}");
1610+
}
1611+
15771612
/// `conv=notrunc,sparse` must not shrink an output file longer than the copy.
15781613
#[test]
15791614
fn test_sparse_notrunc_does_not_shrink() {

0 commit comments

Comments
 (0)