From d1d2a2b031d0d3e2161523a1fb475ab8918ddbbe Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sun, 6 Oct 2024 23:41:10 +0800 Subject: [PATCH] Fix a weird behavior of a function The procfile_write prints the content what user writes into. However, when the content size is greater than or equal to PROCFS_MAX_SIZE, procfile_write will print nothing, because the index for appending the tail NULL character will be modulo to 0, which is an off-by-one error. This fixes the problem by changing the upper bound of procfs_buffer_size to (PROCFS_MAX_SIZE - 1), leaving one byte for NULL character. After the change, we can discard the modulo because the range of procfs_buffer_size is already between 0 and (PROCFS_MAX_SIZE - 1). --- examples/procfs2.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/procfs2.c b/examples/procfs2.c index b5539c5..0a711d3 100644 --- a/examples/procfs2.c +++ b/examples/procfs2.c @@ -48,13 +48,13 @@ static ssize_t procfile_write(struct file *file, const char __user *buff, size_t len, loff_t *off) { procfs_buffer_size = len; - if (procfs_buffer_size > PROCFS_MAX_SIZE) - procfs_buffer_size = PROCFS_MAX_SIZE; + if (procfs_buffer_size >= PROCFS_MAX_SIZE) + procfs_buffer_size = PROCFS_MAX_SIZE - 1; if (copy_from_user(procfs_buffer, buff, procfs_buffer_size)) return -EFAULT; - procfs_buffer[procfs_buffer_size & (PROCFS_MAX_SIZE - 1)] = '\0'; + procfs_buffer[procfs_buffer_size] = '\0'; *off += procfs_buffer_size; pr_info("procfile write %s\n", procfs_buffer);