util.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * __kzalloc - allocate memory. The memory is set to zero.
  8. * @size: how many bytes of memory are required.
  9. * @flags: the type of memory to allocate.
  10. */
  11. void *__kzalloc(size_t size, gfp_t flags)
  12. {
  13. void *ret = kmalloc_track_caller(size, flags);
  14. if (ret)
  15. memset(ret, 0, size);
  16. return ret;
  17. }
  18. EXPORT_SYMBOL(__kzalloc);
  19. /*
  20. * kstrdup - allocate space for and copy an existing string
  21. *
  22. * @s: the string to duplicate
  23. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  24. */
  25. char *kstrdup(const char *s, gfp_t gfp)
  26. {
  27. size_t len;
  28. char *buf;
  29. if (!s)
  30. return NULL;
  31. len = strlen(s) + 1;
  32. buf = kmalloc_track_caller(len, gfp);
  33. if (buf)
  34. memcpy(buf, s, len);
  35. return buf;
  36. }
  37. EXPORT_SYMBOL(kstrdup);
  38. /**
  39. * kmemdup - duplicate region of memory
  40. *
  41. * @src: memory region to duplicate
  42. * @len: memory region length
  43. * @gfp: GFP mask to use
  44. */
  45. void *kmemdup(const void *src, size_t len, gfp_t gfp)
  46. {
  47. void *p;
  48. p = kmalloc_track_caller(len, gfp);
  49. if (p)
  50. memcpy(p, src, len);
  51. return p;
  52. }
  53. EXPORT_SYMBOL(kmemdup);
  54. /*
  55. * strndup_user - duplicate an existing string from user space
  56. *
  57. * @s: The string to duplicate
  58. * @n: Maximum number of bytes to copy, including the trailing NUL.
  59. */
  60. char *strndup_user(const char __user *s, long n)
  61. {
  62. char *p;
  63. long length;
  64. length = strnlen_user(s, n);
  65. if (!length)
  66. return ERR_PTR(-EFAULT);
  67. if (length > n)
  68. return ERR_PTR(-EINVAL);
  69. p = kmalloc(length, GFP_KERNEL);
  70. if (!p)
  71. return ERR_PTR(-ENOMEM);
  72. if (copy_from_user(p, s, length)) {
  73. kfree(p);
  74. return ERR_PTR(-EFAULT);
  75. }
  76. p[length - 1] = '\0';
  77. return p;
  78. }
  79. EXPORT_SYMBOL(strndup_user);