util.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(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(len, gfp);
  33. if (buf)
  34. memcpy(buf, s, len);
  35. return buf;
  36. }
  37. EXPORT_SYMBOL(kstrdup);
  38. /*
  39. * strndup_user - duplicate an existing string from user space
  40. *
  41. * @s: The string to duplicate
  42. * @n: Maximum number of bytes to copy, including the trailing NUL.
  43. */
  44. char *strndup_user(const char __user *s, long n)
  45. {
  46. char *p;
  47. long length;
  48. length = strnlen_user(s, n);
  49. if (!length)
  50. return ERR_PTR(-EFAULT);
  51. if (length > n)
  52. return ERR_PTR(-EINVAL);
  53. p = kmalloc(length, GFP_KERNEL);
  54. if (!p)
  55. return ERR_PTR(-ENOMEM);
  56. if (copy_from_user(p, s, length)) {
  57. kfree(p);
  58. return ERR_PTR(-EFAULT);
  59. }
  60. p[length - 1] = '\0';
  61. return p;
  62. }
  63. EXPORT_SYMBOL(strndup_user);