From: Fushuai Wang <[email protected]>

Many places call copy_from_user() to copy a buffer from user space,
and then manually add a NULL terminator to the destination buffer,
e.g.:

        if (copy_from_user(dest, src, len))
                return -EFAULT;
        dest[len] = '\0';

This is repetitive and error-prone. Add a copy_from_user_nul() helper to
simplify such patterns. It copied n bytes from user space to kernel space,
and NUL-terminates the destination buffer.

Signed-off-by: Fushuai Wang <[email protected]>
---
 include/linux/uaccess.h | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h
index 1f3804245c06..fe9a1db600c7 100644
--- a/include/linux/uaccess.h
+++ b/include/linux/uaccess.h
@@ -224,6 +224,25 @@ copy_from_user(void *to, const void __user *from, unsigned 
long n)
 #endif
 }
 
+/*
+ * copy_from_user_nul - Copy a block of data from user space and NUL-terminate
+ *
+ * @to:   Destination address, in kernel space. This buffer must be at least
+ *        @n+1 bytes long!
+ * @from: Source address, in user space.
+ * @n:    Number of bytes to copy.
+ *
+ * Return: 0 on success, -EFAULT on failure.
+ */
+static __always_inline int __must_check
+copy_from_user_nul(void *to, const void __user *from, unsigned long n)
+{
+       if (copy_from_user(to, from, n))
+               return -EFAULT;
+       ((char *)to)[n] = '\0';
+       return 0;
+}
+
 static __always_inline unsigned long __must_check
 copy_to_user(void __user *to, const void *from, unsigned long n)
 {
-- 
2.36.1


Reply via email to