[PATCH 2/9] Simplify bound checks in nvram for copy_from_user

Arjan van de Ven
2009-09-26T18:54:44Z

Subject: [PATCH 2/9] Simplify bound checks in nvram for copy_from_user

The nvram driver's write() function has an interesting bound check.
Not only does it use the always-hard-to-read ? C operator, it also
has a magic "i" in there, which comes from the file position of
the file.

On first sight the check looks sane, however the value of "i" is not
checked at all and I as human don't know if the C type rules guarantee
that the result is always within bounds.. and neither does gcc seem to
know.

This patch simplifies the checks and guarantees that the copy will not
overflow the destination buffer.

Signed-off-by: Arjan van de Ven <arjan@linux.intel.com>

diff --git a/drivers/char/nvram.c b/drivers/char/nvram.c
index 88cee40..b2a7eaf 100644
--- a/drivers/char/nvram.c
+++ b/drivers/char/nvram.c
@@ -267,7 +267,15 @@ static ssize_t nvram_write(struct file *file, const char __user *buf,
unsigned char *tmp;
int len;

- len = (NVRAM_BYTES - i) < count ? (NVRAM_BYTES - i) : count;
+ len = count;
+ if (count > NVRAM_BYTES - i)
+ len = NVRAM_BYTES - i;
+
+ if (len > NVRAM_BYTES)
+ len = NVRAM_BYTES;
+ if (len < 0)
+ return -EINVAL;
+
if (copy_from_user(contents, buf, len))