uaccess.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* uaccess.c: userspace access functions
  2. *
  3. * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
  4. * Written by David Howells (dhowells@redhat.com)
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version
  9. * 2 of the License, or (at your option) any later version.
  10. */
  11. #include <linux/mm.h>
  12. #include <linux/module.h>
  13. #include <asm/uaccess.h>
  14. /*****************************************************************************/
  15. /*
  16. * copy a null terminated string from userspace
  17. */
  18. long strncpy_from_user(char *dst, const char __user *src, long count)
  19. {
  20. unsigned long max;
  21. char *p, ch;
  22. long err = -EFAULT;
  23. BUG_ON(count < 0);
  24. p = dst;
  25. #ifndef CONFIG_MMU
  26. if ((unsigned long) src < memory_start)
  27. goto error;
  28. #endif
  29. if ((unsigned long) src >= get_addr_limit())
  30. goto error;
  31. max = get_addr_limit() - (unsigned long) src;
  32. if ((unsigned long) count > max) {
  33. memset(dst + max, 0, count - max);
  34. count = max;
  35. }
  36. err = 0;
  37. for (; count > 0; count--, p++, src++) {
  38. __get_user_asm(err, ch, src, "ub", "=r");
  39. if (err < 0)
  40. goto error;
  41. if (!ch)
  42. break;
  43. *p = ch;
  44. }
  45. err = p - dst; /* return length excluding NUL */
  46. error:
  47. if (count > 0)
  48. memset(p, 0, count); /* clear remainder of buffer [security] */
  49. return err;
  50. } /* end strncpy_from_user() */
  51. EXPORT_SYMBOL(strncpy_from_user);
  52. /*****************************************************************************/
  53. /*
  54. * Return the size of a string (including the ending 0)
  55. *
  56. * Return 0 on exception, a value greater than N if too long
  57. */
  58. long strnlen_user(const char __user *src, long count)
  59. {
  60. const char __user *p;
  61. long err = 0;
  62. char ch;
  63. BUG_ON(count < 0);
  64. #ifndef CONFIG_MMU
  65. if ((unsigned long) src < memory_start)
  66. return 0;
  67. #endif
  68. if ((unsigned long) src >= get_addr_limit())
  69. return 0;
  70. for (p = src; count > 0; count--, p++) {
  71. __get_user_asm(err, ch, p, "ub", "=r");
  72. if (err < 0)
  73. return 0;
  74. if (!ch)
  75. break;
  76. }
  77. return p - src + 1; /* return length including NUL */
  78. } /* end strnlen_user() */
  79. EXPORT_SYMBOL(strnlen_user);