[PATCH 06/15] string: implement kmemdup_nul

Ahmad Fatoum a.fatoum at barebox.org
Tue May 27 14:22:51 PDT 2025


From: Ahmad Fatoum <a.fatoum at pengutronix.de>

Unlike memdup and strdup, memdup_nul ensures that the output is NUL
terminated, while not expecting the input to be so.

Signed-off-by: Ahmad Fatoum <ahmad at a3f.at>
---
 include/linux/string.h |  6 ++++++
 lib/string.c           | 42 ++++++++++++++++++++++++++----------------
 2 files changed, 32 insertions(+), 16 deletions(-)

diff --git a/include/linux/string.h b/include/linux/string.h
index 0fa84f095e02..953484ebc9f6 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -175,6 +175,12 @@ static inline void *memdup(const void *buf, size_t size)
 }
 #endif
 
+extern char *memdup_nul(const char *s, size_t len);
+static inline char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
+{
+	return memdup_nul(s, len);
+}
+
 #define memdup_array(arr, count) memdup(arr, array_size(count, sizeof(*arr)));
 
 static inline void *kmemdup(const void *src, size_t len, gfp_t gfp)
diff --git a/lib/string.c b/lib/string.c
index f2272be37e76..33d61add8189 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -423,42 +423,52 @@ size_t strnlen(const char * s, size_t count)
 #endif
 EXPORT_SYMBOL(strnlen);
 
-#ifndef __HAVE_ARCH_STRDUP
-char * strdup(const char *s)
+static __always_inline char *__memdup_nul(const char *s, size_t len)
 {
 	char *new;
 
 	if ((s == NULL)	||
-	    ((new = malloc (strlen(s) + 1)) == NULL) ) {
+	    ((new = malloc (len + 1)) == NULL) ) {
 		return NULL;
 	}
 
-	strcpy (new, s);
+	memcpy (new, s, len);
+	/* Ensure the buf is always NUL-terminated, regardless of @s. */
+	new[len] = '\0';
 	return new;
 }
+
+#ifndef __HAVE_ARCH_STRDUP
+char * strdup(const char *s)
+{
+	return s ? __memdup_nul(s, strlen(s)) : NULL;
+}
 #endif
 EXPORT_SYMBOL(strdup);
 
 #ifndef __HAVE_ARCH_STRNDUP
 char *strndup(const char *s, size_t n)
 {
-	char *new;
-	size_t len = strnlen(s, n);
-
-	if ((s == NULL) ||
-	    ((new = malloc(len + 1)) == NULL)) {
-		return NULL;
-	}
-
-	memcpy(new, s, len);
-	new[len] = '\0';
-
-	return new;
+	return s ? __memdup_nul(s, strnlen(s, n)) : NULL;
 }
 
 #endif
 EXPORT_SYMBOL(strndup);
 
+/**
+ * memdup_nul - Create a NUL-terminated string from @s, which might be unterminated.
+ * @s: The data to copy
+ * @len: The size of the data, not including the NUL terminator
+ *
+ * Return: newly allocated copy of @s with NUL-termination or %NULL in
+ * case of error
+ */
+char *memdup_nul(const char *s, size_t n)
+{
+	return s ? __memdup_nul(s, n) : NULL;
+}
+EXPORT_SYMBOL(memdup_nul);
+
 #ifndef __HAVE_ARCH_STRSPN
 /**
  * strspn - Calculate the length of the initial substring of @s which only
-- 
2.39.5




More information about the barebox mailing list