xref: /linux/arch/x86/boot/string.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* -*- linux-c -*- ------------------------------------------------------- *
3  *
4  *   Copyright (C) 1991, 1992 Linus Torvalds
5  *   Copyright 2007 rPath, Inc. - All Rights Reserved
6  *
7  * ----------------------------------------------------------------------- */
8 
9 /*
10  * Very basic string functions
11  */
12 
13 #include <linux/types.h>
14 #include <linux/compiler.h>
15 #include <linux/errno.h>
16 #include <linux/limits.h>
17 #include <asm/asm.h>
18 #include "ctype.h"
19 #include "string.h"
20 
21 #define KSTRTOX_OVERFLOW       (1U << 31)
22 
23 /*
24  * Undef these macros so that the functions that we provide
25  * here will have the correct names regardless of how string.h
26  * may have chosen to #define them.
27  */
28 #undef memcpy
29 #undef memset
30 #undef memcmp
31 
32 int memcmp(const void *s1, const void *s2, size_t len)
33 {
34 	bool diff;
35 	asm("repe; cmpsb" CC_SET(nz)
36 	    : CC_OUT(nz) (diff), "+D" (s1), "+S" (s2), "+c" (len));
37 	return diff;
38 }
39 
40 /*
41  * Clang may lower `memcmp == 0` to `bcmp == 0`.
42  */
43 int bcmp(const void *s1, const void *s2, size_t len)
44 {
45 	return memcmp(s1, s2, len);
46 }
47 
48 int strcmp(const char *str1, const char *str2)
49 {
50 	const unsigned char *s1 = (const unsigned char *)str1;
51 	const unsigned char *s2 = (const unsigned char *)str2;
52 	int delta;
53 
54 	while (*s1 || *s2) {
55 		delta = *s1 - *s2;
56 		if (delta)
57 			return delta;
58 		s1++;
59 		s2++;
60 	}
61 	return 0;
62 }
63 
64 int strncmp(const char *cs, const char *ct, size_t count)
65 {
66 	unsigned char c1, c2;
67 
68 	while (count) {
69 		c1 = *cs++;
70 		c2 = *ct++;
71 		if (c1 != c2)
72 			return c1 < c2 ? -1 : 1;
73 		if (!c1)
74 			break;
75 		count--;
76 	}
77 	return 0;
78 }
79 
80 size_t strnlen(const char *s, size_t maxlen)
81 {
82 	const char *es = s;
83 	while (*es && maxlen) {
84 		es++;
85 		maxlen--;
86 	}
87 
88 	return (es - s);
89 }
90 
91 /* Works only for digits and letters, but small and fast */
92 #define TOLOWER(x) ((x) | 0x20)
93 
94 static unsigned int simple_guess_base(const char *cp)
95 {
96 	if (cp[0] == '0') {
97 		if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2]))
98 			return 16;
99 		else
100 			return 8;
101 	} else {
102 		return 10;
103 	}
104 }
105 
106 /**
107  * simple_strtoull - convert a string to an unsigned long long
108  * @cp: The start of the string
109  * @endp: A pointer to the end of the parsed string will be placed here
110  * @base: The number base to use
111  */
112 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
113 {
114 	unsigned long long result = 0;
115 
116 	if (!base)
117 		base = simple_guess_base(cp);
118 
119 	if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x')
120 		cp += 2;
121 
122 	while (isxdigit(*cp)) {
123 		unsigned int value;
124 
125 		value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10;
126 		if (value >= base)
127 			break;
128 		result = result * base + value;
129 		cp++;
130 	}
131 	if (endp)
132 		*endp = (char *)cp;
133 
134 	return result;
135 }
136 
137 long simple_strtol(const char *cp, char **endp, unsigned int base)
138 {
139 	if (*cp == '-')
140 		return -simple_strtoull(cp + 1, endp, base);
141 
142 	return simple_strtoull(cp, endp, base);
143 }
144 
145 /**
146  * strlen - Find the length of a string
147  * @s: The string to be sized
148  */
149 size_t strlen(const char *s)
150 {
151 	const char *sc;
152 
153 	for (sc = s; *sc != '\0'; ++sc)
154 		/* nothing */;
155 	return sc - s;
156 }
157 
158 /**
159  * strstr - Find the first substring in a %NUL terminated string
160  * @s1: The string to be searched
161  * @s2: The string to search for
162  */
163 char *strstr(const char *s1, const char *s2)
164 {
165 	size_t l1, l2;
166 
167 	l2 = strlen(s2);
168 	if (!l2)
169 		return (char *)s1;
170 	l1 = strlen(s1);
171 	while (l1 >= l2) {
172 		l1--;
173 		if (!memcmp(s1, s2, l2))
174 			return (char *)s1;
175 		s1++;
176 	}
177 	return NULL;
178 }
179 
180 /**
181  * strchr - Find the first occurrence of the character c in the string s.
182  * @s: the string to be searched
183  * @c: the character to search for
184  */
185 char *strchr(const char *s, int c)
186 {
187 	while (*s != (char)c)
188 		if (*s++ == '\0')
189 			return NULL;
190 	return (char *)s;
191 }
192 
193 static inline u64 __div_u64_rem(u64 dividend, u32 divisor, u32 *remainder)
194 {
195 	union {
196 		u64 v64;
197 		u32 v32[2];
198 	} d = { dividend };
199 	u32 upper;
200 
201 	upper = d.v32[1];
202 	d.v32[1] = 0;
203 	if (upper >= divisor) {
204 		d.v32[1] = upper / divisor;
205 		upper %= divisor;
206 	}
207 	asm ("divl %2" : "=a" (d.v32[0]), "=d" (*remainder) :
208 		"rm" (divisor), "0" (d.v32[0]), "1" (upper));
209 	return d.v64;
210 }
211 
212 static inline u64 __div_u64(u64 dividend, u32 divisor)
213 {
214 	u32 remainder;
215 
216 	return __div_u64_rem(dividend, divisor, &remainder);
217 }
218 
219 static inline char _tolower(const char c)
220 {
221 	return c | 0x20;
222 }
223 
224 static const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
225 {
226 	if (*base == 0) {
227 		if (s[0] == '0') {
228 			if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
229 				*base = 16;
230 			else
231 				*base = 8;
232 		} else
233 			*base = 10;
234 	}
235 	if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
236 		s += 2;
237 	return s;
238 }
239 
240 /*
241  * Convert non-negative integer string representation in explicitly given radix
242  * to an integer.
243  * Return number of characters consumed maybe or-ed with overflow bit.
244  * If overflow occurs, result integer (incorrect) is still returned.
245  *
246  * Don't you dare use this function.
247  */
248 static unsigned int _parse_integer(const char *s,
249 				   unsigned int base,
250 				   unsigned long long *p)
251 {
252 	unsigned long long res;
253 	unsigned int rv;
254 
255 	res = 0;
256 	rv = 0;
257 	while (1) {
258 		unsigned int c = *s;
259 		unsigned int lc = c | 0x20; /* don't tolower() this line */
260 		unsigned int val;
261 
262 		if ('0' <= c && c <= '9')
263 			val = c - '0';
264 		else if ('a' <= lc && lc <= 'f')
265 			val = lc - 'a' + 10;
266 		else
267 			break;
268 
269 		if (val >= base)
270 			break;
271 		/*
272 		 * Check for overflow only if we are within range of
273 		 * it in the max base we support (16)
274 		 */
275 		if (unlikely(res & (~0ull << 60))) {
276 			if (res > __div_u64(ULLONG_MAX - val, base))
277 				rv |= KSTRTOX_OVERFLOW;
278 		}
279 		res = res * base + val;
280 		rv++;
281 		s++;
282 	}
283 	*p = res;
284 	return rv;
285 }
286 
287 static int _kstrtoull(const char *s, unsigned int base, unsigned long long *res)
288 {
289 	unsigned long long _res;
290 	unsigned int rv;
291 
292 	s = _parse_integer_fixup_radix(s, &base);
293 	rv = _parse_integer(s, base, &_res);
294 	if (rv & KSTRTOX_OVERFLOW)
295 		return -ERANGE;
296 	if (rv == 0)
297 		return -EINVAL;
298 	s += rv;
299 	if (*s == '\n')
300 		s++;
301 	if (*s)
302 		return -EINVAL;
303 	*res = _res;
304 	return 0;
305 }
306 
307 /**
308  * kstrtoull - convert a string to an unsigned long long
309  * @s: The start of the string. The string must be null-terminated, and may also
310  *  include a single newline before its terminating null. The first character
311  *  may also be a plus sign, but not a minus sign.
312  * @base: The number base to use. The maximum supported base is 16. If base is
313  *  given as 0, then the base of the string is automatically detected with the
314  *  conventional semantics - If it begins with 0x the number will be parsed as a
315  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
316  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
317  * @res: Where to write the result of the conversion on success.
318  *
319  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
320  * Used as a replacement for the obsolete simple_strtoull. Return code must
321  * be checked.
322  */
323 int kstrtoull(const char *s, unsigned int base, unsigned long long *res)
324 {
325 	if (s[0] == '+')
326 		s++;
327 	return _kstrtoull(s, base, res);
328 }
329 
330 static int _kstrtoul(const char *s, unsigned int base, unsigned long *res)
331 {
332 	unsigned long long tmp;
333 	int rv;
334 
335 	rv = kstrtoull(s, base, &tmp);
336 	if (rv < 0)
337 		return rv;
338 	if (tmp != (unsigned long)tmp)
339 		return -ERANGE;
340 	*res = tmp;
341 	return 0;
342 }
343 
344 /**
345  * boot_kstrtoul - convert a string to an unsigned long
346  * @s: The start of the string. The string must be null-terminated, and may also
347  *  include a single newline before its terminating null. The first character
348  *  may also be a plus sign, but not a minus sign.
349  * @base: The number base to use. The maximum supported base is 16. If base is
350  *  given as 0, then the base of the string is automatically detected with the
351  *  conventional semantics - If it begins with 0x the number will be parsed as a
352  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
353  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
354  * @res: Where to write the result of the conversion on success.
355  *
356  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
357  * Used as a replacement for the simple_strtoull.
358  */
359 int boot_kstrtoul(const char *s, unsigned int base, unsigned long *res)
360 {
361 	/*
362 	 * We want to shortcut function call, but
363 	 * __builtin_types_compatible_p(unsigned long, unsigned long long) = 0.
364 	 */
365 	if (sizeof(unsigned long) == sizeof(unsigned long long) &&
366 	    __alignof__(unsigned long) == __alignof__(unsigned long long))
367 		return kstrtoull(s, base, (unsigned long long *)res);
368 	else
369 		return _kstrtoul(s, base, res);
370 }
371