[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20260112073039.1185-2-fushuai.wang@linux.dev>
Date: Mon, 12 Jan 2026 15:30:34 +0800
From: Fushuai Wang <fushuai.wang@...ux.dev>
To: tglx@...nel.org,
peterz@...radead.org,
mathieu.desnoyers@...icios.com,
akpm@...ux-foundation.org,
aliceryhl@...gle.com,
yury.norov@...il.com,
vmalik@...hat.com,
kees@...nel.org,
dave.hansen@...ux.intel.com,
luto@...nel.org,
mingo@...hat.com,
bp@...en8.de,
hpa@...or.com,
rostedt@...dmis.org,
mhiramat@...nel.org,
brauner@...nel.org,
jack@...e.cz,
cyphar@...har.com
Cc: linux-kernel@...r.kernel.org,
x86@...nel.org,
linux-trace-kernel@...r.kernel.org,
wangfushuai@...du.com
Subject: [PATCH v2 1/6] uaccess: Add copy_from_user_nul helper
From: Fushuai Wang <wangfushuai@...du.com>
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 <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 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
Powered by blists - more mailing lists