From 5d9341bb52bde33290f2e42869352f2f58ac0edc Mon Sep 17 00:00:00 2001 From: Raul E Rangel Date: Mon, 9 Nov 2026 11:53:45 -0700 Subject: [PATCH] dd: implement conv=sparse Add support for conv=sparse to toybox dd. This allows dd to seek past blocks of zeros in the input rather than writing them to the output, creating sparse output files where possible. When ibs == obs, use SEEK_DATA and SEEK_HOLE to quickly skip input holes without reading zero blocks into user buffers. For regular output files, when writing zeros over existing non-zero blocks (with conv=notrunc), use fallocate FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE to deallocate underlying storage blocks while falling back to writev if unsupported. At EOF, extend truncated files if the final block was sparse-seeked. Centralize fallocate definition in lib/portability.h for portability. Add comprehensive unit tests in tests/dd.test. --- lib/portability.h | 6 +++ tests/dd.test | 102 +++++++++++++++++++++++++++++++++++++++++++++- toys/posix/dd.c | 92 ++++++++++++++++++++++++++++++++++++----- 3 files changed, 189 insertions(+), 11 deletions(-) diff --git a/lib/portability.h b/lib/portability.h index 92d0f751..82284b84 100644 --- a/lib/portability.h +++ b/lib/portability.h @@ -128,6 +128,8 @@ static inline char *basename(char *path) { return __xpg_basename(path); } char *strcasestr(const char *haystack, const char *needle); void *memmem(const void *haystack, size_t haystack_length, const void *needle, size_t needle_length); +int fallocate64(int, int, off_t, off_t); +#define fallocate fallocate64 #endif // defined(glibc) #if !defined(__GLIBC__) @@ -190,8 +192,12 @@ void *memmem(const void *haystack, size_t haystack_length, #endif #ifdef __linux__ +#include #include #else +#define FALLOC_FL_KEEP_SIZE 0 +#define FALLOC_FL_PUNCH_HOLE 0 +static inline int fallocate(int a, int b, off_t c, off_t d) { return -1; } #define PER_LINUX32 0 int personality(int); #endif diff --git a/tests/dd.test b/tests/dd.test index b7bf5d4a..57c363ea 100644 --- a/tests/dd.test +++ b/tests/dd.test @@ -133,4 +133,104 @@ testing 'sync padding ticks down count' \ '02dcf1f497ccbe940f57818dfc34f2d0def8b3f9 -\n' '' '' echo -n "hello " > file -testcmd "oflag=append" "of=file oflag=append conv=notrunc && cat file" "hello world\n" "" "world\n" +testcmd "oflag=append" "of=file oflag=append conv=notrunc && cat file && rm -f file" "hello world\n" "" "world\n" + +# conv=sparse tests +testcmd "conv=sparse dense zero" \ + "if=/dev/zero of=out bs=4096 count=16 conv=sparse status=none && [ \$(stat -c '%s' out) -eq 65536 ] && [ \$(stat -c '%b' out) -le 64 ] && echo OK && rm -f out" \ + "OK\n" "" "" + +truncate -s 65536 in +testcmd "conv=sparse all-hole" \ + "if=in of=out bs=4096 status=noxfer conv=sparse 2>&1 && [ \$(stat -c '%s' out) -eq 65536 ] && [ \$(stat -c '%b' out) -le \$(stat -c '%b' in) ] && echo OK && rm -f in out" \ + "16+0 records in\n16+0 records out\nOK\n" "" "" + +truncate -s 32768 in +head -c 4096 /dev/zero | tr '\000' 'B' | dd of=in bs=4096 seek=2 conv=notrunc status=none +head -c 4096 /dev/zero | tr '\000' 'C' | dd of=in bs=4096 seek=5 conv=notrunc status=none +testcmd "conv=sparse interleaved copy" \ + "if=in of=out bs=4096 status=noxfer conv=sparse 2>&1 && cmp in out && [ \$(stat -c '%b' out) -le \$(stat -c '%b' in) ] && echo OK && rm -f out" \ + "8+0 records in\n8+0 records out\nOK\n" "" "" +testcmd "conv=sparse interleaved skip count" \ + "if=in of=out bs=4096 skip=1 count=5 conv=sparse status=none && dd if=in of=ref bs=4096 skip=1 count=5 status=none && cmp ref out && echo OK && rm -f in out ref" \ + "OK\n" "" "" + +truncate -s 600 in +testcmd "conv=sparse unaligned hole" \ + "if=in of=out bs=512 status=noxfer conv=sparse 2>&1 && [ \$(stat -c '%s' out) -eq 600 ] && [ \$(stat -c '%b' out) -le \$(stat -c '%b' in) ] && echo OK && rm -f in out" \ + "1+1 records in\n1+1 records out\nOK\n" "" "" +truncate -s 600 in +testcmd "conv=sync,sparse unaligned hole" \ + "if=in of=out bs=512 status=noxfer conv=sync,sparse 2>&1 && [ \$(stat -c '%s' out) -eq 1024 ] && [ \$(stat -c '%b' out) -le \$(stat -c '%b' in) ] && echo OK && rm -f in out" \ + "1+1 records in\n2+0 records out\nOK\n" "" "" + +truncate -s 8192 in +testcmd "conv=sparse buffered re-chunking" \ + "if=in of=out ibs=512 obs=4096 status=noxfer conv=sparse 2>&1 && [ \$(stat -c '%s' out) -eq 8192 ] && [ \$(stat -c '%b' out) -le \$(stat -c '%b' in) ] && echo OK && rm -f in out" \ + "16+0 records in\n2+0 records out\nOK\n" "" "" + +head -c 4096 /dev/zero | tr '\000' 'A' > refA +cat refA refA refA > out +testing "conv=notrunc,sparse overwrite zero" \ + "b=\$(stat -c '%b' out) && dd if=/dev/zero of=out bs=4096 count=1 seek=1 conv=notrunc,sparse status=none && [ \$(stat -c '%s' out) -eq 12288 ] && [ \$(stat -c '%b' out) -lt \$b ] && cmp -n 4096 refA out 0 0 && cmp -n 4096 /dev/zero out 0 4096 && cmp -n 4096 refA out 0 8192 && echo OK && rm -f out" \ + "OK\n" "" "" + +cat refA refA refA > out +truncate -s 4096 hole +testing "conv=notrunc,sparse overwrite hole" \ + "b=\$(stat -c '%b' out) && dd if=hole of=out bs=4096 count=1 seek=1 conv=notrunc,sparse status=none && [ \$(stat -c '%s' out) -eq 12288 ] && [ \$(stat -c '%b' out) -lt \$b ] && cmp -n 4096 refA out 0 0 && cmp -n 4096 /dev/zero out 0 4096 && cmp -n 4096 refA out 0 8192 && echo OK && rm -f hole out" \ + "OK\n" "" "" + +no_fallocate() { + python3 -c ' +import ctypes, errno, os, platform, struct, sys +nr = {"x86_64": 285, "aarch64": 47, "riscv64": 47, "i686": 324, "armv7l": 352}.get(platform.machine()) +if nr is not None: + insns = b"".join([ + struct.pack("HBBI", 0x20, 0, 0, 0), + struct.pack("HBBI", 0x15, 0, 1, nr), + struct.pack("HBBI", 0x06, 0, 0, 0x00050000 | errno.EOPNOTSUPP), + struct.pack("HBBI", 0x06, 0, 0, 0x7fff0000), + ]) + buf = ctypes.create_string_buffer(insns) + prog = ctypes.create_string_buffer(struct.pack("HL", 4, ctypes.addressof(buf))) + libc = ctypes.CDLL(None, use_errno=True) + libc.prctl(38, 1, 0, 0, 0) + libc.prctl(22, 2, ctypes.c_ulong(ctypes.addressof(prog)), 0, 0) +os.execvp(sys.argv[1], sys.argv[1:]) +' "$@" +} + +cat refA refA refA > out +skipnot command -v python3 +testing "no_fallocate conv=notrunc,sparse zero" \ + "b=\$(stat -c '%b' out) && no_fallocate dd if=/dev/zero of=out bs=4096 count=1 seek=1 conv=notrunc,sparse status=none && [ \$(stat -c '%s' out) -eq 12288 ] && [ \$(stat -c '%b' out) -eq \$b ] && cmp -n 4096 refA out 0 0 && cmp -n 4096 /dev/zero out 0 4096 && cmp -n 4096 refA out 0 8192 && echo OK && rm -f out" \ + "OK\n" "" "" + +cat refA refA refA > out +truncate -s 4096 hole +skipnot command -v python3 +testing "no_fallocate conv=notrunc,sparse hole" \ + "b=\$(stat -c '%b' out) && no_fallocate dd if=hole of=out bs=4096 count=1 seek=1 conv=notrunc,sparse status=none && [ \$(stat -c '%s' out) -eq 12288 ] && [ \$(stat -c '%b' out) -eq \$b ] && cmp -n 4096 refA out 0 0 && cmp -n 4096 /dev/zero out 0 4096 && cmp -n 4096 refA out 0 8192 && echo OK && rm -f hole out" \ + "OK\n" "" "" + +cp refA out +truncate -s 65536 hole +skipnot command -v python3 +testing "no_fallocate conv=notrunc,sparse partial overlap" \ + "b=\$(stat -c '%b' out) && no_fallocate dd if=hole of=out bs=4096 count=16 conv=notrunc,sparse status=none && [ \$(stat -c '%s' out) -eq 65536 ] && [ \$(stat -c '%b' out) -eq \$b ] && cmp -n 65536 /dev/zero out 0 0 && echo OK && rm -f hole out refA" \ + "OK\n" "" "" + +echo -n "ABCD" > out +testcmd "conv=notrunc,sparse post-EOF extension" \ + "if=/dev/zero of=out bs=1 count=4 seek=8 oflag=seek_bytes conv=notrunc,sparse status=none && stat -c '%s' out && [ \"\$(head -c 4 out)\" = 'ABCD' ] && echo OK && rm -f out" \ + "12\nOK\n" "" "" + +echo -n "ABCD" > out +testcmd "oflag=append conv=notrunc,sparse" \ + "if=/dev/zero of=out bs=1 count=4 oflag=append conv=notrunc,sparse status=none && stat -c '%s' out && [ \"\$(head -c 4 out)\" = 'ABCD' ] && echo OK && rm -f out" \ + "8\nOK\n" "" "" + +testing "conv=sparse stdout pipe" \ + "dd if=/dev/zero bs=512 count=2 conv=sparse 2>/dev/null | wc -c" \ + "1024\n" "" "" diff --git a/toys/posix/dd.c b/toys/posix/dd.c index e8c26fbb..ace2f311 100644 --- a/toys/posix/dd.c +++ b/toys/posix/dd.c @@ -56,7 +56,7 @@ struct dd_flag { }; static const struct dd_flag dd_conv[] = TAGGED_ARRAY(DD_conv, - {"fsync"}, {"noerror"}, {"notrunc"}, {"sync"}, {"nocreat"}, // TODO sparse excl + {"fsync"}, {"noerror"}, {"notrunc"}, {"sync"}, {"nocreat"}, {"sparse"}, // TODO excl ); static const struct dd_flag dd_iflag[] = TAGGED_ARRAY(DD_iflag, @@ -131,6 +131,29 @@ static unsigned long long argxarg(char *arg, int cap) } +static int is_zero_iov(struct iovec *iov, int n) +{ + int i; + + for (i = 0; ist_mode) || cur < st->st_size) + && fallocate(ofd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, cur, len)) + return 0; + return lseek(ofd, len, SEEK_CUR) != -1; +} + // Point 1 or 2 iovec at len bytes at buf, starting at "start" and wrapping // around at buflen. int iovwrap(char *buf, unsigned long long buflen, unsigned long long start, @@ -152,8 +175,11 @@ void dd_main() unsigned long long bs = 0, seek = 0, skip = 0, ibs = 512, obs = 512, count = ULLONG_MAX, buflen; long long len; + struct stat st; struct iovec iov[2]; - int opos, olen, ifd = 0, ofd = 1, trunc = O_TRUNC, iflags, oflags, ii; + int opos, olen, ifd = 0, ofd = 1, trunc = O_TRUNC, iflags, oflags, ii, + sparse_seek = 0; + off_t in_off = -1, in_hole = 0; unsigned conv = 0, iflag = 0, oflag = 0; TT.show_xfer = TT.show_records = 1; @@ -222,13 +248,16 @@ void dd_main() // truncate with O_TRUNC on open, so output to /dev/null etc doesn't error. if (!(oflag & _DD_oflag_seek_bytes)) seek *= obs; if (seek) { - struct stat st; - xlseek(ofd, seek, SEEK_CUR); if (trunc && !fstat(ofd, &st) && S_ISREG(st.st_mode) && ftruncate(ofd,seek)) perror_exit("truncate"); } + if ((conv & _DD_conv_sparse) && ((oflag & _DD_oflag_append) || fstat(ofd, &st) + || (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode)))) + conv &= ~_DD_conv_sparse; + if (conv & _DD_conv_sparse) in_off = lseek(ifd, 0, SEEK_CUR); + if (count!=ULLONG_MAX && !(iflag & _DD_iflag_count_bytes)) count = overmul(count, ibs); @@ -238,11 +267,19 @@ void dd_main() // Write as many output blocks as we can. Using writev() avoids memmove() // to realign data but is still a single atomic write. while (olen>=obs || (olen && (bs || !count))) { - errno = 0; - len = writev(ofd, iov, iovwrap(buf, buflen, opos, minof(obs, olen), iov)); - if (len<1) { - if (errno==EINTR) continue; - perror_exit("%s: write error", oname); + len = minof(obs, olen); + ii = iovwrap(buf, buflen, opos, len, iov); + if ((conv & _DD_conv_sparse) && is_zero_iov(iov, ii) + && sparse_out(ofd, len, &st)) { + sparse_seek = 1; + } else { + errno = 0; + len = writev(ofd, iov, ii); + if (len<1) { + if (errno==EINTR) continue; + perror_exit("%s: write error", oname); + } + sparse_seek = 0; } TT.bytes += len; olen -= len; @@ -252,6 +289,35 @@ void dd_main() } if (!count) break; + if ((conv & _DD_conv_sparse) && !olen && ibs == obs && in_off >= 0 + && in_off >= in_hole) { + off_t next_data = lseek(ifd, in_off, SEEK_DATA); + + if (next_data < 0 && errno == ENXIO + && (next_data = lseek(ifd, 0, SEEK_END)) <= in_off) + next_data = -1; + if (next_data > in_off) { + unsigned long long hole = minof(next_data - in_off, count); + + hole -= hole % ibs; + if (hole && sparse_out(ofd, hole, &st)) { + xlseek(ifd, in_off += hole, SEEK_SET); + sparse_seek = 1; + TT.in_full += hole / ibs; + TT.out_full += hole / obs; + TT.bytes += hole; + count -= hole; + continue; + } + if (!hole) in_hole = next_data; + } else if (next_data != in_off + || (in_hole = lseek(ifd, in_off, SEEK_HOLE)) <= in_off) { + in_hole = LLONG_MAX; + } + if (next_data >= 0 && in_off != lseek(ifd, in_off, SEEK_SET)) + perror_exit("%s: seek", iname); + } + // Read next block of input. (There MUST be enough space, we sized buf.) len = opos+olen; if (len>buflen) len -= buflen; @@ -270,7 +336,7 @@ void dd_main() // Complain and try to seek past it status(); - lseek(ifd, ibs, SEEK_CUR); + in_off = lseek(ifd, ibs, SEEK_CUR); if (conv & _DD_conv_sync) olen += ibs; } @@ -278,10 +344,16 @@ void dd_main() } if (len == ibs) TT.in_full++; else TT.in_part++; + if (in_off >= 0) in_off += len; if (conv & _DD_conv_sync) len = ibs; olen += len; count -= minof(len, count); } + if (sparse_seek && !fstat(ofd, &st) && S_ISREG(st.st_mode) + && (len = lseek(ofd, 0, SEEK_CUR)) != -1 && len > st.st_size + && ftruncate(ofd, len)) + perror_exit("truncate"); + if ((conv & _DD_conv_fsync) && fsync(ofd)) perror_exit("%s: fsync", oname); if (CFG_TOYBOX_FREE) { -- 2.39.5