usercopy.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/compiler.h>
  3. #include <linux/errno.h>
  4. #include <linux/export.h>
  5. #include <linux/fault-inject-usercopy.h>
  6. #include <linux/instrumented.h>
  7. #include <linux/kernel.h>
  8. #include <linux/nospec.h>
  9. #include <linux/string.h>
  10. #include <linux/uaccess.h>
  11. #include <linux/wordpart.h>
  12. /* out-of-line parts */
  13. #if !defined(INLINE_COPY_FROM_USER)
  14. unsigned long _copy_from_user(void *to, const void __user *from, unsigned long n)
  15. {
  16. return _inline_copy_from_user(to, from, n);
  17. }
  18. EXPORT_SYMBOL(_copy_from_user);
  19. #endif
  20. #if !defined(INLINE_COPY_TO_USER)
  21. unsigned long _copy_to_user(void __user *to, const void *from, unsigned long n)
  22. {
  23. return _inline_copy_to_user(to, from, n);
  24. }
  25. EXPORT_SYMBOL(_copy_to_user);
  26. #endif
  27. /**
  28. * check_zeroed_user: check if a userspace buffer only contains zero bytes
  29. * @from: Source address, in userspace.
  30. * @size: Size of buffer.
  31. *
  32. * This is effectively shorthand for "memchr_inv(from, 0, size) == NULL" for
  33. * userspace addresses (and is more efficient because we don't care where the
  34. * first non-zero byte is).
  35. *
  36. * Returns:
  37. * * 0: There were non-zero bytes present in the buffer.
  38. * * 1: The buffer was full of zero bytes.
  39. * * -EFAULT: access to userspace failed.
  40. */
  41. int check_zeroed_user(const void __user *from, size_t size)
  42. {
  43. unsigned long val;
  44. uintptr_t align = (uintptr_t) from % sizeof(unsigned long);
  45. if (unlikely(size == 0))
  46. return 1;
  47. from -= align;
  48. size += align;
  49. if (!user_read_access_begin(from, size))
  50. return -EFAULT;
  51. unsafe_get_user(val, (unsigned long __user *) from, err_fault);
  52. if (align)
  53. val &= ~aligned_byte_mask(align);
  54. while (size > sizeof(unsigned long)) {
  55. if (unlikely(val))
  56. goto done;
  57. from += sizeof(unsigned long);
  58. size -= sizeof(unsigned long);
  59. unsafe_get_user(val, (unsigned long __user *) from, err_fault);
  60. }
  61. if (size < sizeof(unsigned long))
  62. val &= aligned_byte_mask(size);
  63. done:
  64. user_read_access_end();
  65. return (val == 0);
  66. err_fault:
  67. user_read_access_end();
  68. return -EFAULT;
  69. }
  70. EXPORT_SYMBOL(check_zeroed_user);