From 2dd558ee51e82cdc38540db951e189e09b259e41 Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Fri, 9 Oct 2026 11:44:08 -0500 Subject: [PATCH] Apparently having an output file named the same as an input file is not considered pilot error by other "split" versions (despite posix). And instead of unlink() they check and abort with an error, so do that. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This bug was discovered by João Matos and Frederico Ramos as part of a research project conducted at the Instituto Superior Técnico, University of Lisbon https://tecnico.ulisboa.pt/pt/ and Carnegie Mellon University https://www.cmu.edu/. --- tests/split.test | 7 ++++++- toys/posix/split.c | 10 +++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/split.test b/tests/split.test index 57270ffa..e0dc1eb2 100755 --- a/tests/split.test +++ b/tests/split.test @@ -29,7 +29,12 @@ testing "reassembly" \ "yes\n" "" "" rm -f file whang* reassembled -testing "-n" "split -n 3 input; md5sum xaa xab xac" \ +testing "-n" "echo ensure truncation>xab;split -n 3 input;md5sum xaa xab xac" \ "494bb8fb423bfa1a5fd66dd0b98f866d xaa\n449acfdbc692780de30a2df05c5d32aa xab\n15ab4be57aebe9a1e445195d5094036c xac\n" \ "$(seq 1 10000)" "" +rm -f x* + +seq 1 12345 > xab +testing 'collision' 'split -b 100 2>/dev/null || cmp xaa <(head -c 100) && cmp xab <(seq 1 12345) && [ ! -e xac ] && echo yes' 'yes\n' '' '' +rm -f xaa xab diff --git a/toys/posix/split.c b/toys/posix/split.c index 293343bf..730faba0 100644 --- a/toys/posix/split.c +++ b/toys/posix/split.c @@ -4,9 +4,7 @@ * * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/split.html * - * Standard does not cover: - * - should splitting an empty file produce an empty outfile? (Went with "no".) - * - permissions on output file + * Standard does not cover permissions on output file USE_SPLIT(NEWTOY(split, ">2a#<1=2>9b#<1l#<1n#<1[!bl][!bn][!ln]", TOYFLAG_USR|TOYFLAG_BIN)) @@ -38,7 +36,7 @@ static void do_split(int infd, char *in) { unsigned long bytesleft, linesleft, filenum, len, pos; int outfd = -1; - struct stat st; + struct stat st, st2; // posix doesn't cover permissions on output file, so copy input (or 0777) st.st_mode = 0777; @@ -69,7 +67,9 @@ static void do_split(int infd, char *in) bytesleft = TT.b + ((filenum == TT.n) ? st.st_size%TT.n : 0); linesleft = TT.l; xclose(outfd); - outfd = xcreate(TT.outfile, O_RDWR|O_CREAT|O_TRUNC, st.st_mode & 0777); + outfd = xcreate(TT.outfile, O_RDWR|O_CREAT, st.st_mode & 0777); + if (fstat(outfd, &st2) || (st.st_dev==st2.st_dev && st.st_ino==st2.st_ino) + || ftruncate(outfd, 0)) error_exit("'%s'='%s'", TT.outfile, in); } // Write next chunk of output. -- 2.39.5