Skip to contentSkip to conversation

uaccess: Add copy_from_user_nul helper

PATCH New Fushuai Wang 1 participant 1 message Oct 11, 2025

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 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.

---
 include/linux/uaccess.h | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
include/linux/uaccess.h +19 -0
index 1beb5b395d81..642a6a7e5a06 100644
@@ -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)
 {
Signature · 1 line
2.36.1