1#include <linux/kernel.h>
2#include <linux/export.h>
3#include <linux/uaccess.h>
4
5#include <asm/word-at-a-time.h>
6
7
8#ifdef __LITTLE_ENDIAN
9# define aligned_byte_mask(n) ((1ul << 8*(n))-1)
10#else
11# define aligned_byte_mask(n) (~0xfful << (BITS_PER_LONG - 8 - 8*(n)))
12#endif
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27static inline long do_strnlen_user(const char __user *src, unsigned long count, unsigned long max)
28{
29 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
30 long align, res = 0;
31 unsigned long c;
32
33
34
35
36
37 if (max > count)
38 max = count;
39
40
41
42
43
44 align = (sizeof(long) - 1) & (unsigned long)src;
45 src -= align;
46 max += align;
47
48 if (unlikely(__get_user(c,(unsigned long __user *)src)))
49 return 0;
50 c |= aligned_byte_mask(align);
51
52 for (;;) {
53 unsigned long data;
54 if (has_zero(c, &data, &constants)) {
55 data = prep_zero_mask(c, data, &constants);
56 data = create_zero_mask(data);
57 return res + find_zero(data) + 1 - align;
58 }
59 res += sizeof(unsigned long);
60 if (unlikely(max < sizeof(unsigned long)))
61 break;
62 max -= sizeof(unsigned long);
63 if (unlikely(__get_user(c,(unsigned long __user *)(src+res))))
64 return 0;
65 }
66 res -= align;
67
68
69
70
71
72 if (res >= count)
73 return count+1;
74
75
76
77
78
79 return 0;
80}
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95long strnlen_user(const char __user *str, long count)
96{
97 unsigned long max_addr, src_addr;
98
99 if (unlikely(count <= 0))
100 return 0;
101
102 max_addr = user_addr_max();
103 src_addr = (unsigned long)str;
104 if (likely(src_addr < max_addr)) {
105 unsigned long max = max_addr - src_addr;
106 return do_strnlen_user(str, count, max);
107 }
108 return 0;
109}
110EXPORT_SYMBOL(strnlen_user);
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126long strlen_user(const char __user *str)
127{
128 unsigned long max_addr, src_addr;
129
130 max_addr = user_addr_max();
131 src_addr = (unsigned long)str;
132 if (likely(src_addr < max_addr)) {
133 unsigned long max = max_addr - src_addr;
134 return do_strnlen_user(str, ~0ul, max);
135 }
136 return 0;
137}
138EXPORT_SYMBOL(strlen_user);
139