[PATCH 02/13] fs: fat: zero-fill files grown by truncate
Sascha Hauer
s.hauer at pengutronix.de
Wed Nov 18 06:51:52 PST 2026
fat_truncate() grows a file by seeking beyond its end, which makes FatFs
extend the cluster chain without clearing anything. Whatever the newly
allocated clusters held before, e.g. the contents of deleted files, and
whatever followed the old end in its last cluster, e.g. data cut off by
an earlier truncate, becomes part of the file:
write 10000 bytes, ftruncate(3000), ftruncate(6000)
-> bytes 3000..5999 hold the old data instead of zeroes
Grow files by writing zeroes from the old end instead. The VFS extends a
file by truncating it before writing beyond its end, so this also fills
the hole such a write leaves with zeroes.
Fixes: 17e91068b1 ("fs: add fat filesystem support")
Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
fs/fat/fat.c | 46 ++++++++++++++++++++++++++++++++++++++++------
1 file changed, 40 insertions(+), 6 deletions(-)
diff --git a/fs/fat/fat.c b/fs/fat/fat.c
index b6f9fd8fe5..1c5aa257b4 100644
--- a/fs/fat/fat.c
+++ b/fs/fat/fat.c
@@ -159,6 +159,34 @@ static int fat_write(struct file *f, const void *buf, size_t insize)
return outsize;
}
+/*
+ * Grow @f_file to @size bytes. Seeking past the end would extend the file as
+ * well, but leave whatever the newly allocated clusters and the rest of the
+ * last one held before, so write zeroes instead.
+ */
+static int fat_extend(FIL *f_file, loff_t size)
+{
+ static const u8 zeroes[SZ_4K];
+ UINT now, written;
+ int ret;
+
+ ret = f_lseek(f_file, f_file->fsize);
+ if (ret)
+ return ret;
+
+ while (f_file->fsize < size) {
+ now = min_t(loff_t, size - f_file->fsize, sizeof(zeroes));
+
+ ret = f_write(f_file, zeroes, now, &written);
+ if (ret)
+ return ret;
+ if (written != now)
+ return -ENOSPC;
+ }
+
+ return 0;
+}
+
static int fat_truncate(struct file *f, loff_t size)
{
FIL *f_file = f->private_data;
@@ -171,13 +199,19 @@ static int fat_truncate(struct file *f, loff_t size)
lastofs = f_file->fptr;
- ret = f_lseek(f_file, size);
- if (ret)
- return ret;
+ if (size > f_file->fsize) {
+ ret = fat_extend(f_file, size);
+ if (ret)
+ return ret;
+ } else {
+ ret = f_lseek(f_file, size);
+ if (ret)
+ return ret;
- ret = f_truncate(f_file);
- if (ret)
- return ret;
+ ret = f_truncate(f_file);
+ if (ret)
+ return ret;
+ }
/* don't extend the file again in case it was shrunk */
ret = f_lseek(f_file, min_t(loff_t, lastofs, size));
--
2.47.3
More information about the barebox
mailing list