[<prev] [next>] [day] [month] [year] [list]
Message-ID: <20251011065546.54457-1-wangfushuai@baidu.com>
Date: Sat, 11 Oct 2025 14:55:46 +0800
From: Fushuai Wang <wangfushuai@...du.com>
To: <cyphar@...har.com>, <vmalik@...hat.com>, <kees@...nel.org>,
<brauner@...nel.org>
CC: <linux-kernel@...r.kernel.org>, Fushuai Wang <wangfushuai@...du.com>
Subject: [PATCH] uaccess: Add copy_from_user_nul helper
Many places call copy_from_user() to copy a buffer from user space,
but then must 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() help 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 <wangfushuai@...du.com>
---
include/linux/uaccess.h | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h
index 1beb5b395d81..642a6a7e5a06 100644
--- a/include/linux/uaccess.h
+++ b/include/linux/uaccess.h
@@ -213,6 +213,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
Powered by blists - more mailing lists