xref: /linux/lib/kstrtox.c (revision bba2c3615bd6cfee7456d1130f2e6b01b3f4e9ba)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Convert integer string representation to an integer.
4  * If an integer doesn't fit into specified type, -E is returned.
5  *
6  * Integer starts with optional sign.
7  * kstrtou*() functions do not accept sign "-".
8  *
9  * Radix 0 means autodetection: leading "0x" implies radix 16,
10  * leading "0" implies radix 8, otherwise radix is 10.
11  * Autodetection hints work after optional sign, but not before.
12  *
13  * If -E is returned, result is not touched.
14  */
15 #include <linux/ctype.h>
16 #include <linux/errno.h>
17 #include <linux/export.h>
18 #include <linux/kstrtox.h>
19 #include <linux/math64.h>
20 #include <linux/types.h>
21 #include <linux/uaccess.h>
22 
23 #include "kstrtox.h"
24 
25 noinline
26 const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
27 {
28 	if (*base == 0) {
29 		if (s[0] == '0') {
30 			if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
31 				*base = 16;
32 			else
33 				*base = 8;
34 		} else
35 			*base = 10;
36 	}
37 	if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
38 		s += 2;
39 	return s;
40 }
41 
42 /**
43  * _parse_integer_limit - Convert integer string representation to an integer
44  * @s: Integer string representation
45  * @base: Radix
46  * @p: Where to store result
47  * @max_chars: Maximum amount of characters to convert
48  *
49  * Convert non-negative integer string representation in explicitly given
50  * radix to an integer. If overflow occurs, value at @p is set to ULLONG_MAX.
51  *
52  * This function is the workhorse of other string conversion functions and it
53  * is discouraged to use it explicitly. Consider kstrto*() family instead.
54  *
55  * Return: Number of characters consumed, maybe ORed with overflow bit
56  */
57 noinline
58 unsigned int _parse_integer_limit(const char *s, unsigned int base, unsigned long long *p,
59 				  size_t max_chars)
60 {
61 	unsigned int rv, overflow = 0;
62 	unsigned long long res;
63 
64 	res = 0;
65 	for (rv = 0; rv < max_chars; rv++, s++) {
66 		unsigned int c = *s;
67 		unsigned int lc = _tolower(c);
68 		unsigned int val;
69 
70 		if ('0' <= c && c <= '9')
71 			val = c - '0';
72 		else if ('a' <= lc && lc <= 'f')
73 			val = lc - 'a' + 10;
74 		else
75 			break;
76 
77 		if (val >= base)
78 			break;
79 		/*
80 		 * Check for overflow only if we are within range of
81 		 * it in the max base we support (16)
82 		 */
83 		if (unlikely(res & (~0ull << 60))) {
84 			if (check_mul_overflow(res, base, &res) ||
85 			    check_add_overflow(res, val, &res)) {
86 				res = ULLONG_MAX;
87 				overflow = KSTRTOX_OVERFLOW;
88 			}
89 		} else {
90 			res = res * base + val;
91 		}
92 	}
93 	*p = res;
94 	return rv | overflow;
95 }
96 
97 noinline
98 unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p)
99 {
100 	return _parse_integer_limit(s, base, p, INT_MAX);
101 }
102 
103 static int _kstrtoull(const char *s, unsigned int base, unsigned long long *res)
104 {
105 	unsigned long long _res;
106 	unsigned int rv;
107 
108 	s = _parse_integer_fixup_radix(s, &base);
109 	rv = _parse_integer(s, base, &_res);
110 	if (rv & KSTRTOX_OVERFLOW)
111 		return -ERANGE;
112 	if (rv == 0)
113 		return -EINVAL;
114 	s += rv;
115 	if (*s == '\n')
116 		s++;
117 	if (*s)
118 		return -EINVAL;
119 	*res = _res;
120 	return 0;
121 }
122 
123 /**
124  * kstrtoull - convert a string to an unsigned long long
125  * @s: The start of the string. The string must be null-terminated, and may also
126  *  include a single newline before its terminating null. The first character
127  *  may also be a plus sign, but not a minus sign.
128  * @base: The number base to use. The maximum supported base is 16. If base is
129  *  given as 0, then the base of the string is automatically detected with the
130  *  conventional semantics - If it begins with 0x the number will be parsed as a
131  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
132  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
133  * @res: Where to write the result of the conversion on success.
134  *
135  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
136  * Preferred over simple_strtoull(). Return code must be checked.
137  */
138 noinline
139 int kstrtoull(const char *s, unsigned int base, unsigned long long *res)
140 {
141 	if (s[0] == '+')
142 		s++;
143 	return _kstrtoull(s, base, res);
144 }
145 EXPORT_SYMBOL(kstrtoull);
146 
147 /**
148  * kstrtoll - convert a string to a long long
149  * @s: The start of the string. The string must be null-terminated, and may also
150  *  include a single newline before its terminating null. The first character
151  *  may also be a plus sign or a minus sign.
152  * @base: The number base to use. The maximum supported base is 16. If base is
153  *  given as 0, then the base of the string is automatically detected with the
154  *  conventional semantics - If it begins with 0x the number will be parsed as a
155  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
156  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
157  * @res: Where to write the result of the conversion on success.
158  *
159  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
160  * Preferred over simple_strtoll(). Return code must be checked.
161  */
162 noinline
163 int kstrtoll(const char *s, unsigned int base, long long *res)
164 {
165 	unsigned long long tmp;
166 	int rv;
167 
168 	if (s[0] == '-') {
169 		rv = _kstrtoull(s + 1, base, &tmp);
170 		if (rv < 0)
171 			return rv;
172 		if ((long long)-tmp > 0)
173 			return -ERANGE;
174 		*res = -tmp;
175 	} else {
176 		rv = kstrtoull(s, base, &tmp);
177 		if (rv < 0)
178 			return rv;
179 		if ((long long)tmp < 0)
180 			return -ERANGE;
181 		*res = tmp;
182 	}
183 	return 0;
184 }
185 EXPORT_SYMBOL(kstrtoll);
186 
187 /* Internal, do not use. */
188 int _kstrtoul(const char *s, unsigned int base, unsigned long *res)
189 {
190 	unsigned long long tmp;
191 	int rv;
192 
193 	rv = kstrtoull(s, base, &tmp);
194 	if (rv < 0)
195 		return rv;
196 	if (tmp != (unsigned long)tmp)
197 		return -ERANGE;
198 	*res = tmp;
199 	return 0;
200 }
201 EXPORT_SYMBOL(_kstrtoul);
202 
203 /* Internal, do not use. */
204 int _kstrtol(const char *s, unsigned int base, long *res)
205 {
206 	long long tmp;
207 	int rv;
208 
209 	rv = kstrtoll(s, base, &tmp);
210 	if (rv < 0)
211 		return rv;
212 	if (tmp != (long)tmp)
213 		return -ERANGE;
214 	*res = tmp;
215 	return 0;
216 }
217 EXPORT_SYMBOL(_kstrtol);
218 
219 /**
220  * kstrtouint - convert a string to an unsigned int
221  * @s: The start of the string. The string must be null-terminated, and may also
222  *  include a single newline before its terminating null. The first character
223  *  may also be a plus sign, but not a minus sign.
224  * @base: The number base to use. The maximum supported base is 16. If base is
225  *  given as 0, then the base of the string is automatically detected with the
226  *  conventional semantics - If it begins with 0x the number will be parsed as a
227  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
228  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
229  * @res: Where to write the result of the conversion on success.
230  *
231  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
232  * Preferred over simple_strtoul(). Return code must be checked.
233  */
234 noinline
235 int kstrtouint(const char *s, unsigned int base, unsigned int *res)
236 {
237 	unsigned long long tmp;
238 	int rv;
239 
240 	rv = kstrtoull(s, base, &tmp);
241 	if (rv < 0)
242 		return rv;
243 	if (tmp != (unsigned int)tmp)
244 		return -ERANGE;
245 	*res = tmp;
246 	return 0;
247 }
248 EXPORT_SYMBOL(kstrtouint);
249 
250 /**
251  * kstrtoint - convert a string to an int
252  * @s: The start of the string. The string must be null-terminated, and may also
253  *  include a single newline before its terminating null. The first character
254  *  may also be a plus sign or a minus sign.
255  * @base: The number base to use. The maximum supported base is 16. If base is
256  *  given as 0, then the base of the string is automatically detected with the
257  *  conventional semantics - If it begins with 0x the number will be parsed as a
258  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
259  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
260  * @res: Where to write the result of the conversion on success.
261  *
262  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
263  * Preferred over simple_strtol(). Return code must be checked.
264  */
265 noinline
266 int kstrtoint(const char *s, unsigned int base, int *res)
267 {
268 	long long tmp;
269 	int rv;
270 
271 	rv = kstrtoll(s, base, &tmp);
272 	if (rv < 0)
273 		return rv;
274 	if (tmp != (int)tmp)
275 		return -ERANGE;
276 	*res = tmp;
277 	return 0;
278 }
279 EXPORT_SYMBOL(kstrtoint);
280 
281 noinline
282 int kstrtou16(const char *s, unsigned int base, u16 *res)
283 {
284 	unsigned long long tmp;
285 	int rv;
286 
287 	rv = kstrtoull(s, base, &tmp);
288 	if (rv < 0)
289 		return rv;
290 	if (tmp != (u16)tmp)
291 		return -ERANGE;
292 	*res = tmp;
293 	return 0;
294 }
295 EXPORT_SYMBOL(kstrtou16);
296 
297 noinline
298 int kstrtos16(const char *s, unsigned int base, s16 *res)
299 {
300 	long long tmp;
301 	int rv;
302 
303 	rv = kstrtoll(s, base, &tmp);
304 	if (rv < 0)
305 		return rv;
306 	if (tmp != (s16)tmp)
307 		return -ERANGE;
308 	*res = tmp;
309 	return 0;
310 }
311 EXPORT_SYMBOL(kstrtos16);
312 
313 noinline
314 int kstrtou8(const char *s, unsigned int base, u8 *res)
315 {
316 	unsigned long long tmp;
317 	int rv;
318 
319 	rv = kstrtoull(s, base, &tmp);
320 	if (rv < 0)
321 		return rv;
322 	if (tmp != (u8)tmp)
323 		return -ERANGE;
324 	*res = tmp;
325 	return 0;
326 }
327 EXPORT_SYMBOL(kstrtou8);
328 
329 noinline
330 int kstrtos8(const char *s, unsigned int base, s8 *res)
331 {
332 	long long tmp;
333 	int rv;
334 
335 	rv = kstrtoll(s, base, &tmp);
336 	if (rv < 0)
337 		return rv;
338 	if (tmp != (s8)tmp)
339 		return -ERANGE;
340 	*res = tmp;
341 	return 0;
342 }
343 EXPORT_SYMBOL(kstrtos8);
344 
345 /**
346  * kstrtobool - convert common user inputs into boolean values
347  * @s: input string
348  * @res: result
349  *
350  * This routine returns 0 iff the first character is one of 'EeYyTt1DdNnFf0',
351  * or [oO][NnFf] for "on" and "off". Otherwise it will return -EINVAL.  Value
352  * pointed to by res is updated upon finding a match.
353  */
354 noinline
355 int kstrtobool(const char *s, bool *res)
356 {
357 	if (!s)
358 		return -EINVAL;
359 
360 	switch (s[0]) {
361 	case 'e':
362 	case 'E':
363 	case 'y':
364 	case 'Y':
365 	case 't':
366 	case 'T':
367 	case '1':
368 		*res = true;
369 		return 0;
370 	case 'd':
371 	case 'D':
372 	case 'n':
373 	case 'N':
374 	case 'f':
375 	case 'F':
376 	case '0':
377 		*res = false;
378 		return 0;
379 	case 'o':
380 	case 'O':
381 		switch (s[1]) {
382 		case 'n':
383 		case 'N':
384 			*res = true;
385 			return 0;
386 		case 'f':
387 		case 'F':
388 			*res = false;
389 			return 0;
390 		default:
391 			break;
392 		}
393 		break;
394 	default:
395 		break;
396 	}
397 
398 	return -EINVAL;
399 }
400 EXPORT_SYMBOL(kstrtobool);
401 
402 /*
403  * Since "base" would be a nonsense argument, this open-codes the
404  * _from_user helper instead of using the helper macro below.
405  */
406 int kstrtobool_from_user(const char __user *s, size_t count, bool *res)
407 {
408 	/* Longest string needed to differentiate, newline, terminator */
409 	char buf[4];
410 
411 	count = min(count, sizeof(buf) - 1);
412 	if (copy_from_user(buf, s, count))
413 		return -EFAULT;
414 	buf[count] = '\0';
415 	return kstrtobool(buf, res);
416 }
417 EXPORT_SYMBOL(kstrtobool_from_user);
418 
419 #define kstrto_from_user(f, g, type)					\
420 int f(const char __user *s, size_t count, unsigned int base, type *res)	\
421 {									\
422 	/* sign, base 2 representation, newline, terminator */		\
423 	char buf[1 + sizeof(type) * 8 + 1 + 1];				\
424 									\
425 	count = min(count, sizeof(buf) - 1);				\
426 	if (copy_from_user(buf, s, count))				\
427 		return -EFAULT;						\
428 	buf[count] = '\0';						\
429 	return g(buf, base, res);					\
430 }									\
431 EXPORT_SYMBOL(f)
432 
433 kstrto_from_user(kstrtoull_from_user,	kstrtoull,	unsigned long long);
434 kstrto_from_user(kstrtoll_from_user,	kstrtoll,	long long);
435 kstrto_from_user(kstrtoul_from_user,	kstrtoul,	unsigned long);
436 kstrto_from_user(kstrtol_from_user,	kstrtol,	long);
437 kstrto_from_user(kstrtouint_from_user,	kstrtouint,	unsigned int);
438 kstrto_from_user(kstrtoint_from_user,	kstrtoint,	int);
439 kstrto_from_user(kstrtou16_from_user,	kstrtou16,	u16);
440 kstrto_from_user(kstrtos16_from_user,	kstrtos16,	s16);
441 kstrto_from_user(kstrtou8_from_user,	kstrtou8,	u8);
442 kstrto_from_user(kstrtos8_from_user,	kstrtos8,	s8);
443