util.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <linux/slab.h>
  2. #include <linux/string.h>
  3. #include <linux/module.h>
  4. #include <linux/err.h>
  5. #include <asm/uaccess.h>
  6. /**
  7. * kstrdup - allocate space for and copy an existing string
  8. *
  9. * @s: the string to duplicate
  10. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  11. */
  12. char *kstrdup(const char *s, gfp_t gfp)
  13. {
  14. size_t len;
  15. char *buf;
  16. if (!s)
  17. return NULL;
  18. len = strlen(s) + 1;
  19. buf = kmalloc_track_caller(len, gfp);
  20. if (buf)
  21. memcpy(buf, s, len);
  22. return buf;
  23. }
  24. EXPORT_SYMBOL(kstrdup);
  25. /**
  26. * kmemdup - duplicate region of memory
  27. *
  28. * @src: memory region to duplicate
  29. * @len: memory region length
  30. * @gfp: GFP mask to use
  31. */
  32. void *kmemdup(const void *src, size_t len, gfp_t gfp)
  33. {
  34. void *p;
  35. p = kmalloc_track_caller(len, gfp);
  36. if (p)
  37. memcpy(p, src, len);
  38. return p;
  39. }
  40. EXPORT_SYMBOL(kmemdup);
  41. /**
  42. * krealloc - reallocate memory. The contents will remain unchanged.
  43. * @p: object to reallocate memory for.
  44. * @new_size: how many bytes of memory are required.
  45. * @flags: the type of memory to allocate.
  46. *
  47. * The contents of the object pointed to are preserved up to the
  48. * lesser of the new and old sizes. If @p is %NULL, krealloc()
  49. * behaves exactly like kmalloc(). If @size is 0 and @p is not a
  50. * %NULL pointer, the object pointed to is freed.
  51. */
  52. void *krealloc(const void *p, size_t new_size, gfp_t flags)
  53. {
  54. void *ret;
  55. size_t ks;
  56. if (unlikely(!new_size)) {
  57. kfree(p);
  58. return ZERO_SIZE_PTR;
  59. }
  60. ks = ksize(p);
  61. if (ks >= new_size)
  62. return (void *)p;
  63. ret = kmalloc_track_caller(new_size, flags);
  64. if (ret) {
  65. memcpy(ret, p, min(new_size, ks));
  66. kfree(p);
  67. }
  68. return ret;
  69. }
  70. EXPORT_SYMBOL(krealloc);
  71. /*
  72. * strndup_user - duplicate an existing string from user space
  73. *
  74. * @s: The string to duplicate
  75. * @n: Maximum number of bytes to copy, including the trailing NUL.
  76. */
  77. char *strndup_user(const char __user *s, long n)
  78. {
  79. char *p;
  80. long length;
  81. length = strnlen_user(s, n);
  82. if (!length)
  83. return ERR_PTR(-EFAULT);
  84. if (length > n)
  85. return ERR_PTR(-EINVAL);
  86. p = kmalloc(length, GFP_KERNEL);
  87. if (!p)
  88. return ERR_PTR(-ENOMEM);
  89. if (copy_from_user(p, s, length)) {
  90. kfree(p);
  91. return ERR_PTR(-EFAULT);
  92. }
  93. p[length - 1] = '\0';
  94. return p;
  95. }
  96. EXPORT_SYMBOL(strndup_user);