summaryrefslogtreecommitdiff
path: root/mm
diff options
context:
space:
mode:
authorDavid Howells <dhowells@redhat.com>2017-07-04 19:25:02 +0300
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>2018-02-25 13:01:18 +0300
commite8ee445b600807c8d6ec02a5d6fce2beaf3c9a23 (patch)
treed2249899a28d5e0554948a6ecf11cd256b07139c /mm
parent48e014f330c3fa1b32e134750e89ed5ef21b0e05 (diff)
downloadlinux-e8ee445b600807c8d6ec02a5d6fce2beaf3c9a23.tar.xz
Provide a function to create a NUL-terminated string from unterminated data
commit f35157417215ec138c920320c746fdb3e04ef1d5 upstream. Provide a function, kmemdup_nul(), that will create a NUL-terminated string from an unterminated character array where the length is known in advance. This is better than kstrndup() in situations where we already know the string length as the strnlen() in kstrndup() is superfluous. Signed-off-by: David Howells <dhowells@redhat.com> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Diffstat (limited to 'mm')
-rw-r--r--mm/util.c24
1 files changed, 24 insertions, 0 deletions
diff --git a/mm/util.c b/mm/util.c
index fec39d4509a9..93450b102359 100644
--- a/mm/util.c
+++ b/mm/util.c
@@ -42,6 +42,8 @@ EXPORT_SYMBOL(kstrdup);
* @s: the string to duplicate
* @max: read at most @max chars from @s
* @gfp: the GFP mask used in the kmalloc() call when allocating memory
+ *
+ * Note: Use kmemdup_nul() instead if the size is known exactly.
*/
char *kstrndup(const char *s, size_t max, gfp_t gfp)
{
@@ -80,6 +82,28 @@ void *kmemdup(const void *src, size_t len, gfp_t gfp)
EXPORT_SYMBOL(kmemdup);
/**
+ * kmemdup_nul - Create a NUL-terminated string from unterminated data
+ * @s: The data to stringify
+ * @len: The size of the data
+ * @gfp: the GFP mask used in the kmalloc() call when allocating memory
+ */
+char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
+{
+ char *buf;
+
+ if (!s)
+ return NULL;
+
+ buf = kmalloc_track_caller(len + 1, gfp);
+ if (buf) {
+ memcpy(buf, s, len);
+ buf[len] = '\0';
+ }
+ return buf;
+}
+EXPORT_SYMBOL(kmemdup_nul);
+
+/**
* memdup_user - duplicate memory region from user space
*
* @src: source address in user space