1 #include <linux/slab.h>
2 #include <linux/string.h>
3 #include <linux/module.h>
5 #include <asm/uaccess.h>
8 * kstrdup - allocate space for and copy an existing string
9 * @s: the string to duplicate
10 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
12 char *kstrdup(const char *s, gfp_t gfp)
21 buf = kmalloc_track_caller(len, gfp);
26 EXPORT_SYMBOL(kstrdup);
29 * kstrndup - allocate space for and copy an existing string
30 * @s: the string to duplicate
31 * @max: read at most @max chars from @s
32 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
34 char *kstrndup(const char *s, size_t max, gfp_t gfp)
42 len = strnlen(s, max);
43 buf = kmalloc_track_caller(len+1, gfp);
50 EXPORT_SYMBOL(kstrndup);
53 * kmemdup - duplicate region of memory
55 * @src: memory region to duplicate
56 * @len: memory region length
57 * @gfp: GFP mask to use
59 void *kmemdup(const void *src, size_t len, gfp_t gfp)
63 p = kmalloc_track_caller(len, gfp);
68 EXPORT_SYMBOL(kmemdup);
71 * __krealloc - like krealloc() but don't free @p.
72 * @p: object to reallocate memory for.
73 * @new_size: how many bytes of memory are required.
74 * @flags: the type of memory to allocate.
76 * This function is like krealloc() except it never frees the originally
77 * allocated buffer. Use this if you don't want to free the buffer immediately
78 * like, for example, with RCU.
80 void *__krealloc(const void *p, size_t new_size, gfp_t flags)
85 if (unlikely(!new_size))
94 ret = kmalloc_track_caller(new_size, flags);
100 EXPORT_SYMBOL(__krealloc);
103 * krealloc - reallocate memory. The contents will remain unchanged.
104 * @p: object to reallocate memory for.
105 * @new_size: how many bytes of memory are required.
106 * @flags: the type of memory to allocate.
108 * The contents of the object pointed to are preserved up to the
109 * lesser of the new and old sizes. If @p is %NULL, krealloc()
110 * behaves exactly like kmalloc(). If @size is 0 and @p is not a
111 * %NULL pointer, the object pointed to is freed.
113 void *krealloc(const void *p, size_t new_size, gfp_t flags)
117 if (unlikely(!new_size)) {
119 return ZERO_SIZE_PTR;
122 ret = __krealloc(p, new_size, flags);
128 EXPORT_SYMBOL(krealloc);
131 * strndup_user - duplicate an existing string from user space
132 * @s: The string to duplicate
133 * @n: Maximum number of bytes to copy, including the trailing NUL.
135 char *strndup_user(const char __user *s, long n)
140 length = strnlen_user(s, n);
143 return ERR_PTR(-EFAULT);
146 return ERR_PTR(-EINVAL);
148 p = kmalloc(length, GFP_KERNEL);
151 return ERR_PTR(-ENOMEM);
153 if (copy_from_user(p, s, length)) {
155 return ERR_PTR(-EFAULT);
158 p[length - 1] = '\0';
162 EXPORT_SYMBOL(strndup_user);