Opening a file with the O_EXCL flag on and the O_CREAT flag off has
undefined behavior unless the file is a block device. Let's try and
avoid this case on a best-effort basis. The undefined behavior can
still be hit if the block device is replaced with something else
inbetween.

v2: Fix typo: O_CREAT, not O_CREATE.
v3: Change the comment, as the condition is not actually enforced,
    only checked on a best-effort basis.

Signed-off-by: Ari Sundholm <[email protected]>
---
 util-linux/blkdiscard.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/util-linux/blkdiscard.c b/util-linux/blkdiscard.c
index ace88a1..b97f716 100644
--- a/util-linux/blkdiscard.c
+++ b/util-linux/blkdiscard.c
@@ -38,7 +38,7 @@ int blkdiscard_main(int argc UNUSED_PARAM, char **argv)
        uint64_t offset; /* Leaving these two variables out does not  */
        uint64_t length; /* shrink code size and hampers readability. */
        uint64_t range[2];
-//     struct stat st;
+       struct stat st;
        int fd;
 
        enum {
@@ -51,11 +51,17 @@ int blkdiscard_main(int argc UNUSED_PARAM, char **argv)
        opts = getopt32(argv, "o:l:s", &offset_str, &length_str);
        argv += optind;
 
+       /* Opening a file with the O_EXCL flag on and the O_CREAT flag off has
+        * undefined behavior unless the file is a block device. Let's try and
+        * avoid this case on a best-effort basis. The undefined behavior can
+        * still be hit if the block device is replaced with something else
+        * inbetween.
+        */
+       xstat(argv[0], &st);
+       if (!S_ISBLK(st.st_mode))
+               bb_error_msg_and_die("%s: not a block device", argv[0]);
+
        fd = xopen(argv[0], O_RDWR|O_EXCL);
-//Why bother, BLK[SEC]DISCARD will fail on non-blockdevs anyway?
-//     xfstat(fd, &st);
-//     if (!S_ISBLK(st.st_mode))
-//             bb_error_msg_and_die("%s: not a block device", argv[0]);
 
        offset = xatoull_sfx(offset_str, kMG_suffixes);
 
-- 
1.9.1



_______________________________________________
busybox mailing list
[email protected]
http://lists.busybox.net/mailman/listinfo/busybox

Reply via email to