1 #include <linux/module.h>
2 #include <linux/uaccess.h>
3 #include <linux/kernel.h>
4 #include <linux/errno.h>
6 #include <asm/byteorder.h>
8 static inline long find_zero(unsigned long mask
)
23 return (mask
>> 8) ? byte
: byte
+ 1;
26 if (!((unsigned int) mask
)) {
31 if (!(mask
& 0xffff)) {
35 return (mask
& 0xff) ? byte
: byte
+ 1;
39 #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
40 #define IS_UNALIGNED(src, dst) 0
42 #define IS_UNALIGNED(src, dst) \
43 (((long) dst | (long) src) & (sizeof(long) - 1))
47 * Do a strncpy, return length of string without final '\0'.
48 * 'count' is the user-supplied count (return 'count' if we
49 * hit it), 'max' is the address space maximum (and we return
50 * -EFAULT if we hit it).
52 static inline long do_strncpy_from_user(char *dst
, const char __user
*src
, long count
, unsigned long max
)
54 const unsigned long high_bits
= REPEAT_BYTE(0xfe) + 1;
55 const unsigned long low_bits
= REPEAT_BYTE(0x7f);
59 * Truncate 'max' to the user-specified limit, so that
60 * we only have one limit we need to check in the loop
65 if (IS_UNALIGNED(src
, dst
))
68 while (max
>= sizeof(unsigned long)) {
69 unsigned long c
, v
, rhs
;
71 /* Fall back to byte-at-a-time if we get a page fault */
72 if (unlikely(__get_user(c
,(unsigned long __user
*)(src
+res
))))
75 v
= (c
+ high_bits
) & ~rhs
;
76 *(unsigned long *)(dst
+res
) = c
;
78 v
= (c
& low_bits
) + low_bits
;
80 return res
+ find_zero(v
);
82 res
+= sizeof(unsigned long);
83 max
-= sizeof(unsigned long);
90 if (unlikely(__get_user(c
,src
+res
)))
100 * Uhhuh. We hit 'max'. But was that the user-specified maximum
101 * too? If so, that's ok - we got as much as the user asked for.
107 * Nope: we hit the address space limit, and we still had more
108 * characters the caller would have wanted. That's an EFAULT.
114 * strncpy_from_user: - Copy a NUL terminated string from userspace.
115 * @dst: Destination address, in kernel space. This buffer must be at
116 * least @count bytes long.
117 * @src: Source address, in user space.
118 * @count: Maximum number of bytes to copy, including the trailing NUL.
120 * Copies a NUL-terminated string from userspace to kernel space.
122 * On success, returns the length of the string (not including the trailing
125 * If access to userspace fails, returns -EFAULT (some data may have been
128 * If @count is smaller than the length of the string, copies @count bytes
129 * and returns @count.
131 long strncpy_from_user(char *dst
, const char __user
*src
, long count
)
133 unsigned long max_addr
, src_addr
;
135 if (unlikely(count
<= 0))
138 max_addr
= user_addr_max();
139 src_addr
= (unsigned long)src
;
140 if (likely(src_addr
< max_addr
)) {
141 unsigned long max
= max_addr
- src_addr
;
142 return do_strncpy_from_user(dst
, src
, count
, max
);
146 EXPORT_SYMBOL(strncpy_from_user
);