From: Johannes Wüller Date: Sat, 4 Apr 2026 18:03:06 +0000 (+0200) Subject: mkswap: Fix --file chmod(2) check when file exists X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6d87ff51568c017a6d08043d554bf0ea8dee5457;p=thirdparty%2Futil-linux.git mkswap: Fix --file chmod(2) check when file exists The documentation claims that `--size` will resize the `--file`, but it ends up failing like this: # mkswap --file /swapfile --size 4G Setting up swapspace version 1, size = 4 GiB (4294963200 bytes) no label, UUID=1523588e-412a-4f25-8fac-aeaf638101aa # mkswap --file /swapfile --size 4G mkswap: cannot set permissions on swap file /swapfile: Success There seems to have been a typo in the chmod(2) return value comparison. It checked for `< 9` rather than `< 0`, which would usually indicate failure. After the fix: # mkswap --file /swapfile --size 4G Setting up swapspace version 1, size = 4 GiB (4294963200 bytes) no label, UUID=6be7c450-761c-442d-8d9a-3e8cd93506b5 # mkswap --file /swapfile --size 4G mkswap: /swapfile: warning: wiping old swap signature. Setting up swapspace version 1, size = 4 GiB (4294963200 bytes) no label, UUID=617a793e-84b1-471d-96c5-c099f8b157db The operation no longer fails, as validated by the added test. --- diff --git a/disk-utils/mkswap.c b/disk-utils/mkswap.c index 17ec1603f..a8ac26a6d 100644 --- a/disk-utils/mkswap.c +++ b/disk-utils/mkswap.c @@ -404,7 +404,7 @@ static void open_device(struct mkswap_control *ctl) if (stat(ctl->devname, &ctl->devstat) == 0) { if (!S_ISREG(ctl->devstat.st_mode)) err(EXIT_FAILURE, _("cannot create swap file %s: node isn't regular file"), ctl->devname); - if (chmod(ctl->devname, 0600) < 9) + if (chmod(ctl->devname, 0600) < 0) err(EXIT_FAILURE, _("cannot set permissions on swap file %s"), ctl->devname); } ctl->fd = open(ctl->devname, O_RDWR | O_CREAT, 0600); diff --git a/tests/ts/mkswap/mkswap b/tests/ts/mkswap/mkswap index 39b8723a1..19111971c 100755 --- a/tests/ts/mkswap/mkswap +++ b/tests/ts/mkswap/mkswap @@ -100,4 +100,19 @@ cmp "$outimg" "$outimg.offset" 0 "$offset" >> "$TS_ERRLOG" 2>&1 ts_finalize_subtest +ts_init_subtest file-existing + +outimg="$TS_OUTDIR/existing.img" +rm -f "$outimg" + +"$TS_CMD_MKSWAP" -q -U "$UUID" -F -s $((4096 * 10)) "$outimg" \ + >> "$TS_OUTPUT" 2>/dev/null \ + || ts_log "mkswap failed" + +"$TS_CMD_MKSWAP" -q -U "$UUID" -F -s $((4096 * 10)) "$outimg" \ + >> "$TS_OUTPUT" 2>&1 \ + || ts_log "mkswap -F failed on existing file" + +ts_finalize_subtest + ts_finalize