[PATCH 01/13] fs: ramfs: zero the rest of a chunk when truncating

Sascha Hauer s.hauer at pengutronix.de
Wed Nov 18 06:51:51 PST 2026


Shrinking a file only frees the chunks entirely beyond the new size. The
chunk the new end falls into keeps its old contents past it, and as
growing the file again doesn't allocate anything as long as the chunks
are big enough, it brings them back:

  write 10000 bytes, ftruncate(3000), ftruncate(6000)
  -> bytes 3000..5999 hold the old data instead of zeroes

Newly allocated chunks are zeroed, so clear the remainder of the chunk
when shrinking to keep everything beyond the end of a file zero.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 fs/ramfs.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/fs/ramfs.c b/fs/ramfs.c
index d86bf6144e..0df4af5294 100644
--- a/fs/ramfs.c
+++ b/fs/ramfs.c
@@ -311,6 +311,14 @@ static void ramfs_truncate_down(struct ramfs_inode *node, unsigned long size)
 			list_del(&data->list);
 			node->alloc_size -= data->size;
 			ramfs_put_chunk(data);
+		} else if (data->ofs + data->size > size) {
+			/*
+			 * Growing the file again reuses the rest of this
+			 * chunk, which must read back as zeroes then, like
+			 * newly allocated chunks do.
+			 */
+			memset(data->data + size - data->ofs, 0,
+			       data->ofs + data->size - size);
 		}
 	}
 

-- 
2.47.3




More information about the barebox mailing list