Fix Bug to corrupt the img file

Reproduce steps:
  > dd if=/dev/zero of=btrfs-small.img bs=1M count=1
  > ls -lh btrfs-small.img
  -rw-rw-r--. 1 rock rock 1.0M Oct 24 09:51 btrfs-small.img
  > mkfs.btrfs btrfs-small.img
  -rw-rw-r--. 1 rock rock 2.0M Oct 24 09:53 btrfs-small.img

Here you can see the original img file's size goes larger to 2Mbytes.

Signed-off-by: Rock Lee <zim...@code-trick.com>
---
 utils.c |    8 ++++++--
 1 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/utils.c b/utils.c
index 205e667..3c88d2e 100644
--- a/utils.c
+++ b/utils.c
@@ -441,7 +441,7 @@ static int zero_blocks(int fd, off_t start, size_t len)
        return ret;
 }

-static int zero_dev_start(int fd)
+static int zero_dev_start(int fd, u64 dev_size)
 {
        off_t start = 0;
        size_t len = 2 * 1024 * 1024;
@@ -451,6 +451,10 @@ static int zero_dev_start(int fd)
        start = 1024;
        len -= 1024;
 #endif
+
+       if (dev_size < len)
+               return -EIO;
+
        return zero_blocks(fd, start, len);
 }

@@ -572,7 +576,7 @@ int btrfs_prepare_device(int fd, char *file, int
zero_end, u64 *block_count_ret,
                discard_blocks(fd, 0, block_count);
        }

-       ret = zero_dev_start(fd);
+       ret = zero_dev_start(fd, block_count);
        if (ret) {
                fprintf(stderr, "failed to zero device start %d\n", ret);
                exit(1);
-- 
1.7.7.6
--
To unsubscribe from this list: send the line "unsubscribe linux-btrfs" in
the body of a message to majord...@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Reply via email to