[PATCH 4/8] staging: comedi: avoid bad truncation of a size_t in comedi_write()

Ian Abbott abbotti at mev.co.uk
Wed Nov 18 17:55:07 UTC 2015


At one point in `comedi_write()`, the variable `n` gets assigned to the
minimum of the parameter `nbytes` and the amount of writeable buffer
space.  The way that is done currently is unsafe in the unlikely case
that `nbytes` exceeds `UINT_MAX`, so fix it.

Signed-off-by: Ian Abbott <abbotti at mev.co.uk>
---
 drivers/staging/comedi/comedi_fops.c | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)

diff --git a/drivers/staging/comedi/comedi_fops.c b/drivers/staging/comedi/comedi_fops.c
index 188a12a..8c784c4 100644
--- a/drivers/staging/comedi/comedi_fops.c
+++ b/drivers/staging/comedi/comedi_fops.c
@@ -2357,16 +2357,13 @@ static ssize_t comedi_write(struct file *file, const char __user *buf,
 			break;
 		}
 
-		n = nbytes;
-
-		m = n;
+		/* Allocate all free buffer space. */
+		comedi_buf_write_alloc(s, async->prealloc_bufsz);
+		m = comedi_buf_write_n_allocated(s);
+		/* Avoid buffer wraparound. */
 		if (async->buf_write_ptr + m > async->prealloc_bufsz)
 			m = async->prealloc_bufsz - async->buf_write_ptr;
-		comedi_buf_write_alloc(s, async->prealloc_bufsz);
-		if (m > comedi_buf_write_n_allocated(s))
-			m = comedi_buf_write_n_allocated(s);
-		if (m < n)
-			n = m;
+		n = min_t(size_t, m, nbytes);
 
 		if (n == 0) {
 			if (file->f_flags & O_NONBLOCK) {
-- 
2.6.2



More information about the devel mailing list