diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 596a3880c0e..6d6978cd2c0 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -1405,12 +1405,13 @@ fn finalize( // not yet written. let wstat_update = output.flush()?; - // Sync the output, if configured to do so. - output.sync()?; - // With `conv=sparse`, trailing zero blocks were skipped, not written. + // Set the final length first so that `fsync`/`fdatasync` covers it. output.extend_sparse()?; + // Sync the output, if configured to do so. + output.sync()?; + // Print the final read/write statistics. let wstat = wstat + wstat_update; let prog_update = ProgUpdate::new(rstat, wstat, start.elapsed(), ProgUpdateType::Final); diff --git a/tests/by-util/test_dd.rs b/tests/by-util/test_dd.rs index 553b3c14fba..f2a260d9930 100644 --- a/tests/by-util/test_dd.rs +++ b/tests/by-util/test_dd.rs @@ -1574,6 +1574,41 @@ fn test_sparse_notrunc_extends_file() { assert_eq!(at.metadata("outfile").len(), 1024); } +/// With `conv=sparse,fsync` (or `fdatasync`), the trailing zero block extends +/// the file before the sync, so the sync covers the final length. +#[rstest] +#[case::fsync("fsync")] +#[case::fdatasync("fdatasync")] +#[cfg(target_os = "linux")] +#[cfg(not(wasi_runner))] +fn test_sparse_extends_before_sync(#[case] sync: &str) { + let (at, _ucmd) = at_and_ucmd!(); + at.write_bytes("infile", &[0; 4096]); + let trace = at.plus("trace"); + let Ok(out) = Command::new("strace") + .arg("-o") + .arg(&trace) + .args(["-e", "trace=fsync,fdatasync,ftruncate"]) + .arg(get_tests_binary()) + .arg("dd") + .args(["if=infile", "of=outfile", "bs=4096", "status=none"]) + .arg(format!("conv=sparse,{sync}")) + .current_dir(at.as_string()) + .output() + else { + return; // missing strace + }; + if String::from_utf8_lossy(&out.stderr).contains("ptrace") { + return; // tracing not permitted here + } + assert!(out.status.success()); + assert_eq!(at.metadata("outfile").len(), 4096); + let trace = at.read("trace"); + let extend = trace.find(", 4096)").expect("final ftruncate"); + let synced = trace.find(&format!("{sync}(")).expect("sync call"); + assert!(extend < synced, "{trace}"); +} + /// `conv=notrunc,sparse` must not shrink an output file longer than the copy. #[test] fn test_sparse_notrunc_does_not_shrink() {