[PATCH] fs/kernel_read_file: set the correct 'buf_size' after allocating 'buf'
From: gouhao
Date: Mon Mar 27 2023 - 02:48:19 EST
From: Gou Hao <gouhao@xxxxxxxxxxxxx>
According to the comments of the kernel_read_file():
'if @buf is NULL, a buffer will be allocated, and
@buf_size will be ignored'.
But if i pass 'buf=NULL, buf_size=0' to kernel_read_file(),
0 is returned, it means that has not read the content.
The root cause is that 'buf_size' is not set correctly after
allocating memory, which does not match 'copied < buf_size',
so 0 is returned.
So we should set 'buf_size' to 'i_size' after allocating memory.
Signed-off-by: Gou Hao <gouhao@xxxxxxxxxxxxx>
---
fs/kernel_read_file.c | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/fs/kernel_read_file.c b/fs/kernel_read_file.c
index 5d826274570c..77d400f5951d 100644
--- a/fs/kernel_read_file.c
+++ b/fs/kernel_read_file.c
@@ -63,12 +63,14 @@ ssize_t kernel_read_file(struct file *file, loff_t offset, void **buf,
goto out;
}
/* The entire file cannot be read in one buffer. */
- if (!file_size && offset == 0 && i_size > buf_size) {
+ if (!file_size && offset == 0 &&
+ (buf_size && i_size > buf_size)) {
ret = -EFBIG;
goto out;
}
- whole_file = (offset == 0 && i_size <= buf_size);
+ whole_file = (offset == 0 &&
+ (!buf_size || i_size <= buf_size));
ret = security_kernel_read_file(file, id, whole_file);
if (ret)
goto out;
@@ -76,8 +78,11 @@ ssize_t kernel_read_file(struct file *file, loff_t offset, void **buf,
if (file_size)
*file_size = i_size;
- if (!*buf)
+ if (!*buf) {
*buf = allocated = vmalloc(i_size);
+ buf_size = i_size;
+ }
+
if (!*buf) {
ret = -ENOMEM;
goto out;
--
2.20.1