xref: /linux-6.15/lib/string_helpers.c (revision 4ce615e7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Helpers for formatting and printing strings
4  *
5  * Copyright 31 August 2008 James Bottomley
6  * Copyright (C) 2013, Intel Corporation
7  */
8 #include <linux/bug.h>
9 #include <linux/kernel.h>
10 #include <linux/math64.h>
11 #include <linux/export.h>
12 #include <linux/ctype.h>
13 #include <linux/device.h>
14 #include <linux/errno.h>
15 #include <linux/fs.h>
16 #include <linux/limits.h>
17 #include <linux/mm.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/string_helpers.h>
21 #include <kunit/test.h>
22 #include <kunit/test-bug.h>
23 
24 /**
25  * string_get_size - get the size in the specified units
26  * @size:	The size to be converted in blocks
27  * @blk_size:	Size of the block (use 1 for size in bytes)
28  * @units:	units to use (powers of 1000 or 1024)
29  * @buf:	buffer to format to
30  * @len:	length of buffer
31  *
32  * This function returns a string formatted to 3 significant figures
33  * giving the size in the required units.  @buf should have room for
34  * at least 9 bytes and will always be zero terminated.
35  *
36  * Return value: number of characters of output that would have been written
37  * (which may be greater than len, if output was truncated).
38  */
39 int string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
40 		    char *buf, int len)
41 {
42 	static const char *const units_10[] = {
43 		"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
44 	};
45 	static const char *const units_2[] = {
46 		"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
47 	};
48 	static const char *const *const units_str[] = {
49 		[STRING_UNITS_10] = units_10,
50 		[STRING_UNITS_2] = units_2,
51 	};
52 	static const unsigned int divisor[] = {
53 		[STRING_UNITS_10] = 1000,
54 		[STRING_UNITS_2] = 1024,
55 	};
56 	static const unsigned int rounding[] = { 500, 50, 5 };
57 	int i = 0, j;
58 	u32 remainder = 0, sf_cap;
59 	char tmp[8];
60 	const char *unit;
61 
62 	tmp[0] = '\0';
63 
64 	if (blk_size == 0)
65 		size = 0;
66 	if (size == 0)
67 		goto out;
68 
69 	/* This is Napier's algorithm.  Reduce the original block size to
70 	 *
71 	 * coefficient * divisor[units]^i
72 	 *
73 	 * we do the reduction so both coefficients are just under 32 bits so
74 	 * that multiplying them together won't overflow 64 bits and we keep
75 	 * as much precision as possible in the numbers.
76 	 *
77 	 * Note: it's safe to throw away the remainders here because all the
78 	 * precision is in the coefficients.
79 	 */
80 	while (blk_size >> 32) {
81 		do_div(blk_size, divisor[units]);
82 		i++;
83 	}
84 
85 	while (size >> 32) {
86 		do_div(size, divisor[units]);
87 		i++;
88 	}
89 
90 	/* now perform the actual multiplication keeping i as the sum of the
91 	 * two logarithms */
92 	size *= blk_size;
93 
94 	/* and logarithmically reduce it until it's just under the divisor */
95 	while (size >= divisor[units]) {
96 		remainder = do_div(size, divisor[units]);
97 		i++;
98 	}
99 
100 	/* work out in j how many digits of precision we need from the
101 	 * remainder */
102 	sf_cap = size;
103 	for (j = 0; sf_cap*10 < 1000; j++)
104 		sf_cap *= 10;
105 
106 	if (units == STRING_UNITS_2) {
107 		/* express the remainder as a decimal.  It's currently the
108 		 * numerator of a fraction whose denominator is
109 		 * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
110 		remainder *= 1000;
111 		remainder >>= 10;
112 	}
113 
114 	/* add a 5 to the digit below what will be printed to ensure
115 	 * an arithmetical round up and carry it through to size */
116 	remainder += rounding[j];
117 	if (remainder >= 1000) {
118 		remainder -= 1000;
119 		size += 1;
120 	}
121 
122 	if (j) {
123 		snprintf(tmp, sizeof(tmp), ".%03u", remainder);
124 		tmp[j+1] = '\0';
125 	}
126 
127  out:
128 	if (i >= ARRAY_SIZE(units_2))
129 		unit = "UNK";
130 	else
131 		unit = units_str[units][i];
132 
133 	return snprintf(buf, len, "%u%s %s", (u32)size,
134 			tmp, unit);
135 }
136 EXPORT_SYMBOL(string_get_size);
137 
138 /**
139  * parse_int_array_user - Split string into a sequence of integers
140  * @from:	The user space buffer to read from
141  * @count:	The maximum number of bytes to read
142  * @array:	Returned pointer to sequence of integers
143  *
144  * On success @array is allocated and initialized with a sequence of
145  * integers extracted from the @from plus an additional element that
146  * begins the sequence and specifies the integers count.
147  *
148  * Caller takes responsibility for freeing @array when it is no longer
149  * needed.
150  */
151 int parse_int_array_user(const char __user *from, size_t count, int **array)
152 {
153 	int *ints, nints;
154 	char *buf;
155 	int ret = 0;
156 
157 	buf = memdup_user_nul(from, count);
158 	if (IS_ERR(buf))
159 		return PTR_ERR(buf);
160 
161 	get_options(buf, 0, &nints);
162 	if (!nints) {
163 		ret = -ENOENT;
164 		goto free_buf;
165 	}
166 
167 	ints = kcalloc(nints + 1, sizeof(*ints), GFP_KERNEL);
168 	if (!ints) {
169 		ret = -ENOMEM;
170 		goto free_buf;
171 	}
172 
173 	get_options(buf, nints + 1, ints);
174 	*array = ints;
175 
176 free_buf:
177 	kfree(buf);
178 	return ret;
179 }
180 EXPORT_SYMBOL(parse_int_array_user);
181 
182 static bool unescape_space(char **src, char **dst)
183 {
184 	char *p = *dst, *q = *src;
185 
186 	switch (*q) {
187 	case 'n':
188 		*p = '\n';
189 		break;
190 	case 'r':
191 		*p = '\r';
192 		break;
193 	case 't':
194 		*p = '\t';
195 		break;
196 	case 'v':
197 		*p = '\v';
198 		break;
199 	case 'f':
200 		*p = '\f';
201 		break;
202 	default:
203 		return false;
204 	}
205 	*dst += 1;
206 	*src += 1;
207 	return true;
208 }
209 
210 static bool unescape_octal(char **src, char **dst)
211 {
212 	char *p = *dst, *q = *src;
213 	u8 num;
214 
215 	if (isodigit(*q) == 0)
216 		return false;
217 
218 	num = (*q++) & 7;
219 	while (num < 32 && isodigit(*q) && (q - *src < 3)) {
220 		num <<= 3;
221 		num += (*q++) & 7;
222 	}
223 	*p = num;
224 	*dst += 1;
225 	*src = q;
226 	return true;
227 }
228 
229 static bool unescape_hex(char **src, char **dst)
230 {
231 	char *p = *dst, *q = *src;
232 	int digit;
233 	u8 num;
234 
235 	if (*q++ != 'x')
236 		return false;
237 
238 	num = digit = hex_to_bin(*q++);
239 	if (digit < 0)
240 		return false;
241 
242 	digit = hex_to_bin(*q);
243 	if (digit >= 0) {
244 		q++;
245 		num = (num << 4) | digit;
246 	}
247 	*p = num;
248 	*dst += 1;
249 	*src = q;
250 	return true;
251 }
252 
253 static bool unescape_special(char **src, char **dst)
254 {
255 	char *p = *dst, *q = *src;
256 
257 	switch (*q) {
258 	case '\"':
259 		*p = '\"';
260 		break;
261 	case '\\':
262 		*p = '\\';
263 		break;
264 	case 'a':
265 		*p = '\a';
266 		break;
267 	case 'e':
268 		*p = '\e';
269 		break;
270 	default:
271 		return false;
272 	}
273 	*dst += 1;
274 	*src += 1;
275 	return true;
276 }
277 
278 /**
279  * string_unescape - unquote characters in the given string
280  * @src:	source buffer (escaped)
281  * @dst:	destination buffer (unescaped)
282  * @size:	size of the destination buffer (0 to unlimit)
283  * @flags:	combination of the flags.
284  *
285  * Description:
286  * The function unquotes characters in the given string.
287  *
288  * Because the size of the output will be the same as or less than the size of
289  * the input, the transformation may be performed in place.
290  *
291  * Caller must provide valid source and destination pointers. Be aware that
292  * destination buffer will always be NULL-terminated. Source string must be
293  * NULL-terminated as well.  The supported flags are::
294  *
295  *	UNESCAPE_SPACE:
296  *		'\f' - form feed
297  *		'\n' - new line
298  *		'\r' - carriage return
299  *		'\t' - horizontal tab
300  *		'\v' - vertical tab
301  *	UNESCAPE_OCTAL:
302  *		'\NNN' - byte with octal value NNN (1 to 3 digits)
303  *	UNESCAPE_HEX:
304  *		'\xHH' - byte with hexadecimal value HH (1 to 2 digits)
305  *	UNESCAPE_SPECIAL:
306  *		'\"' - double quote
307  *		'\\' - backslash
308  *		'\a' - alert (BEL)
309  *		'\e' - escape
310  *	UNESCAPE_ANY:
311  *		all previous together
312  *
313  * Return:
314  * The amount of the characters processed to the destination buffer excluding
315  * trailing '\0' is returned.
316  */
317 int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
318 {
319 	char *out = dst;
320 
321 	while (*src && --size) {
322 		if (src[0] == '\\' && src[1] != '\0' && size > 1) {
323 			src++;
324 			size--;
325 
326 			if (flags & UNESCAPE_SPACE &&
327 					unescape_space(&src, &out))
328 				continue;
329 
330 			if (flags & UNESCAPE_OCTAL &&
331 					unescape_octal(&src, &out))
332 				continue;
333 
334 			if (flags & UNESCAPE_HEX &&
335 					unescape_hex(&src, &out))
336 				continue;
337 
338 			if (flags & UNESCAPE_SPECIAL &&
339 					unescape_special(&src, &out))
340 				continue;
341 
342 			*out++ = '\\';
343 		}
344 		*out++ = *src++;
345 	}
346 	*out = '\0';
347 
348 	return out - dst;
349 }
350 EXPORT_SYMBOL(string_unescape);
351 
352 static bool escape_passthrough(unsigned char c, char **dst, char *end)
353 {
354 	char *out = *dst;
355 
356 	if (out < end)
357 		*out = c;
358 	*dst = out + 1;
359 	return true;
360 }
361 
362 static bool escape_space(unsigned char c, char **dst, char *end)
363 {
364 	char *out = *dst;
365 	unsigned char to;
366 
367 	switch (c) {
368 	case '\n':
369 		to = 'n';
370 		break;
371 	case '\r':
372 		to = 'r';
373 		break;
374 	case '\t':
375 		to = 't';
376 		break;
377 	case '\v':
378 		to = 'v';
379 		break;
380 	case '\f':
381 		to = 'f';
382 		break;
383 	default:
384 		return false;
385 	}
386 
387 	if (out < end)
388 		*out = '\\';
389 	++out;
390 	if (out < end)
391 		*out = to;
392 	++out;
393 
394 	*dst = out;
395 	return true;
396 }
397 
398 static bool escape_special(unsigned char c, char **dst, char *end)
399 {
400 	char *out = *dst;
401 	unsigned char to;
402 
403 	switch (c) {
404 	case '\\':
405 		to = '\\';
406 		break;
407 	case '\a':
408 		to = 'a';
409 		break;
410 	case '\e':
411 		to = 'e';
412 		break;
413 	case '"':
414 		to = '"';
415 		break;
416 	default:
417 		return false;
418 	}
419 
420 	if (out < end)
421 		*out = '\\';
422 	++out;
423 	if (out < end)
424 		*out = to;
425 	++out;
426 
427 	*dst = out;
428 	return true;
429 }
430 
431 static bool escape_null(unsigned char c, char **dst, char *end)
432 {
433 	char *out = *dst;
434 
435 	if (c)
436 		return false;
437 
438 	if (out < end)
439 		*out = '\\';
440 	++out;
441 	if (out < end)
442 		*out = '0';
443 	++out;
444 
445 	*dst = out;
446 	return true;
447 }
448 
449 static bool escape_octal(unsigned char c, char **dst, char *end)
450 {
451 	char *out = *dst;
452 
453 	if (out < end)
454 		*out = '\\';
455 	++out;
456 	if (out < end)
457 		*out = ((c >> 6) & 0x07) + '0';
458 	++out;
459 	if (out < end)
460 		*out = ((c >> 3) & 0x07) + '0';
461 	++out;
462 	if (out < end)
463 		*out = ((c >> 0) & 0x07) + '0';
464 	++out;
465 
466 	*dst = out;
467 	return true;
468 }
469 
470 static bool escape_hex(unsigned char c, char **dst, char *end)
471 {
472 	char *out = *dst;
473 
474 	if (out < end)
475 		*out = '\\';
476 	++out;
477 	if (out < end)
478 		*out = 'x';
479 	++out;
480 	if (out < end)
481 		*out = hex_asc_hi(c);
482 	++out;
483 	if (out < end)
484 		*out = hex_asc_lo(c);
485 	++out;
486 
487 	*dst = out;
488 	return true;
489 }
490 
491 /**
492  * string_escape_mem - quote characters in the given memory buffer
493  * @src:	source buffer (unescaped)
494  * @isz:	source buffer size
495  * @dst:	destination buffer (escaped)
496  * @osz:	destination buffer size
497  * @flags:	combination of the flags
498  * @only:	NULL-terminated string containing characters used to limit
499  *		the selected escape class. If characters are included in @only
500  *		that would not normally be escaped by the classes selected
501  *		in @flags, they will be copied to @dst unescaped.
502  *
503  * Description:
504  * The process of escaping byte buffer includes several parts. They are applied
505  * in the following sequence.
506  *
507  *	1. The character is not matched to the one from @only string and thus
508  *	   must go as-is to the output.
509  *	2. The character is matched to the printable and ASCII classes, if asked,
510  *	   and in case of match it passes through to the output.
511  *	3. The character is matched to the printable or ASCII class, if asked,
512  *	   and in case of match it passes through to the output.
513  *	4. The character is checked if it falls into the class given by @flags.
514  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
515  *	   character. Note that they actually can't go together, otherwise
516  *	   %ESCAPE_HEX will be ignored.
517  *
518  * Caller must provide valid source and destination pointers. Be aware that
519  * destination buffer will not be NULL-terminated, thus caller have to append
520  * it if needs. The supported flags are::
521  *
522  *	%ESCAPE_SPACE: (special white space, not space itself)
523  *		'\f' - form feed
524  *		'\n' - new line
525  *		'\r' - carriage return
526  *		'\t' - horizontal tab
527  *		'\v' - vertical tab
528  *	%ESCAPE_SPECIAL:
529  *		'\"' - double quote
530  *		'\\' - backslash
531  *		'\a' - alert (BEL)
532  *		'\e' - escape
533  *	%ESCAPE_NULL:
534  *		'\0' - null
535  *	%ESCAPE_OCTAL:
536  *		'\NNN' - byte with octal value NNN (3 digits)
537  *	%ESCAPE_ANY:
538  *		all previous together
539  *	%ESCAPE_NP:
540  *		escape only non-printable characters, checked by isprint()
541  *	%ESCAPE_ANY_NP:
542  *		all previous together
543  *	%ESCAPE_HEX:
544  *		'\xHH' - byte with hexadecimal value HH (2 digits)
545  *	%ESCAPE_NA:
546  *		escape only non-ascii characters, checked by isascii()
547  *	%ESCAPE_NAP:
548  *		escape only non-printable or non-ascii characters
549  *	%ESCAPE_APPEND:
550  *		append characters from @only to be escaped by the given classes
551  *
552  * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
553  * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
554  *
555  * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
556  * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
557  * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
558  * or %ESCAPE_HEX, because they cover most of the other character classes.
559  * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
560  * the above.
561  *
562  * Return:
563  * The total size of the escaped output that would be generated for
564  * the given input and flags. To check whether the output was
565  * truncated, compare the return value to osz. There is room left in
566  * dst for a '\0' terminator if and only if ret < osz.
567  */
568 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
569 		      unsigned int flags, const char *only)
570 {
571 	char *p = dst;
572 	char *end = p + osz;
573 	bool is_dict = only && *only;
574 	bool is_append = flags & ESCAPE_APPEND;
575 
576 	while (isz--) {
577 		unsigned char c = *src++;
578 		bool in_dict = is_dict && strchr(only, c);
579 
580 		/*
581 		 * Apply rules in the following sequence:
582 		 *	- the @only string is supplied and does not contain a
583 		 *	  character under question
584 		 *	- the character is printable and ASCII, when @flags has
585 		 *	  %ESCAPE_NAP bit set
586 		 *	- the character is printable, when @flags has
587 		 *	  %ESCAPE_NP bit set
588 		 *	- the character is ASCII, when @flags has
589 		 *	  %ESCAPE_NA bit set
590 		 *	- the character doesn't fall into a class of symbols
591 		 *	  defined by given @flags
592 		 * In these cases we just pass through a character to the
593 		 * output buffer.
594 		 *
595 		 * When %ESCAPE_APPEND is passed, the characters from @only
596 		 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
597 		 * %ESCAPE_NA cases.
598 		 */
599 		if (!(is_append || in_dict) && is_dict &&
600 					  escape_passthrough(c, &p, end))
601 			continue;
602 
603 		if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
604 		    flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
605 			continue;
606 
607 		if (!(is_append && in_dict) && isprint(c) &&
608 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
609 			continue;
610 
611 		if (!(is_append && in_dict) && isascii(c) &&
612 		    flags & ESCAPE_NA && escape_passthrough(c, &p, end))
613 			continue;
614 
615 		if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
616 			continue;
617 
618 		if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
619 			continue;
620 
621 		if (flags & ESCAPE_NULL && escape_null(c, &p, end))
622 			continue;
623 
624 		/* ESCAPE_OCTAL and ESCAPE_HEX always go last */
625 		if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
626 			continue;
627 
628 		if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
629 			continue;
630 
631 		escape_passthrough(c, &p, end);
632 	}
633 
634 	return p - dst;
635 }
636 EXPORT_SYMBOL(string_escape_mem);
637 
638 /*
639  * Return an allocated string that has been escaped of special characters
640  * and double quotes, making it safe to log in quotes.
641  */
642 char *kstrdup_quotable(const char *src, gfp_t gfp)
643 {
644 	size_t slen, dlen;
645 	char *dst;
646 	const int flags = ESCAPE_HEX;
647 	const char esc[] = "\f\n\r\t\v\a\e\\\"";
648 
649 	if (!src)
650 		return NULL;
651 	slen = strlen(src);
652 
653 	dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
654 	dst = kmalloc(dlen + 1, gfp);
655 	if (!dst)
656 		return NULL;
657 
658 	WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
659 	dst[dlen] = '\0';
660 
661 	return dst;
662 }
663 EXPORT_SYMBOL_GPL(kstrdup_quotable);
664 
665 /*
666  * Returns allocated NULL-terminated string containing process
667  * command line, with inter-argument NULLs replaced with spaces,
668  * and other special characters escaped.
669  */
670 char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
671 {
672 	char *buffer, *quoted;
673 	int i, res;
674 
675 	buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
676 	if (!buffer)
677 		return NULL;
678 
679 	res = get_cmdline(task, buffer, PAGE_SIZE - 1);
680 	buffer[res] = '\0';
681 
682 	/* Collapse trailing NULLs, leave res pointing to last non-NULL. */
683 	while (--res >= 0 && buffer[res] == '\0')
684 		;
685 
686 	/* Replace inter-argument NULLs. */
687 	for (i = 0; i <= res; i++)
688 		if (buffer[i] == '\0')
689 			buffer[i] = ' ';
690 
691 	/* Make sure result is printable. */
692 	quoted = kstrdup_quotable(buffer, gfp);
693 	kfree(buffer);
694 	return quoted;
695 }
696 EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
697 
698 /*
699  * Returns allocated NULL-terminated string containing pathname,
700  * with special characters escaped, able to be safely logged. If
701  * there is an error, the leading character will be "<".
702  */
703 char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
704 {
705 	char *temp, *pathname;
706 
707 	if (!file)
708 		return kstrdup("<unknown>", gfp);
709 
710 	/* We add 11 spaces for ' (deleted)' to be appended */
711 	temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
712 	if (!temp)
713 		return kstrdup("<no_memory>", gfp);
714 
715 	pathname = file_path(file, temp, PATH_MAX + 11);
716 	if (IS_ERR(pathname))
717 		pathname = kstrdup("<too_long>", gfp);
718 	else
719 		pathname = kstrdup_quotable(pathname, gfp);
720 
721 	kfree(temp);
722 	return pathname;
723 }
724 EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
725 
726 /*
727  * Returns duplicate string in which the @old characters are replaced by @new.
728  */
729 char *kstrdup_and_replace(const char *src, char old, char new, gfp_t gfp)
730 {
731 	char *dst;
732 
733 	dst = kstrdup(src, gfp);
734 	if (!dst)
735 		return NULL;
736 
737 	return strreplace(dst, old, new);
738 }
739 EXPORT_SYMBOL_GPL(kstrdup_and_replace);
740 
741 /**
742  * kasprintf_strarray - allocate and fill array of sequential strings
743  * @gfp: flags for the slab allocator
744  * @prefix: prefix to be used
745  * @n: amount of lines to be allocated and filled
746  *
747  * Allocates and fills @n strings using pattern "%s-%zu", where prefix
748  * is provided by caller. The caller is responsible to free them with
749  * kfree_strarray() after use.
750  *
751  * Returns array of strings or NULL when memory can't be allocated.
752  */
753 char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
754 {
755 	char **names;
756 	size_t i;
757 
758 	names = kcalloc(n + 1, sizeof(char *), gfp);
759 	if (!names)
760 		return NULL;
761 
762 	for (i = 0; i < n; i++) {
763 		names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
764 		if (!names[i]) {
765 			kfree_strarray(names, i);
766 			return NULL;
767 		}
768 	}
769 
770 	return names;
771 }
772 EXPORT_SYMBOL_GPL(kasprintf_strarray);
773 
774 /**
775  * kfree_strarray - free a number of dynamically allocated strings contained
776  *                  in an array and the array itself
777  *
778  * @array: Dynamically allocated array of strings to free.
779  * @n: Number of strings (starting from the beginning of the array) to free.
780  *
781  * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
782  * use-cases. If @array is NULL, the function does nothing.
783  */
784 void kfree_strarray(char **array, size_t n)
785 {
786 	unsigned int i;
787 
788 	if (!array)
789 		return;
790 
791 	for (i = 0; i < n; i++)
792 		kfree(array[i]);
793 	kfree(array);
794 }
795 EXPORT_SYMBOL_GPL(kfree_strarray);
796 
797 struct strarray {
798 	char **array;
799 	size_t n;
800 };
801 
802 static void devm_kfree_strarray(struct device *dev, void *res)
803 {
804 	struct strarray *array = res;
805 
806 	kfree_strarray(array->array, array->n);
807 }
808 
809 char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
810 {
811 	struct strarray *ptr;
812 
813 	ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
814 	if (!ptr)
815 		return ERR_PTR(-ENOMEM);
816 
817 	ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
818 	if (!ptr->array) {
819 		devres_free(ptr);
820 		return ERR_PTR(-ENOMEM);
821 	}
822 
823 	ptr->n = n;
824 	devres_add(dev, ptr);
825 
826 	return ptr->array;
827 }
828 EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
829 
830 /**
831  * skip_spaces - Removes leading whitespace from @str.
832  * @str: The string to be stripped.
833  *
834  * Returns a pointer to the first non-whitespace character in @str.
835  */
836 char *skip_spaces(const char *str)
837 {
838 	while (isspace(*str))
839 		++str;
840 	return (char *)str;
841 }
842 EXPORT_SYMBOL(skip_spaces);
843 
844 /**
845  * strim - Removes leading and trailing whitespace from @s.
846  * @s: The string to be stripped.
847  *
848  * Note that the first trailing whitespace is replaced with a %NUL-terminator
849  * in the given string @s. Returns a pointer to the first non-whitespace
850  * character in @s.
851  */
852 char *strim(char *s)
853 {
854 	size_t size;
855 	char *end;
856 
857 	size = strlen(s);
858 	if (!size)
859 		return s;
860 
861 	end = s + size - 1;
862 	while (end >= s && isspace(*end))
863 		end--;
864 	*(end + 1) = '\0';
865 
866 	return skip_spaces(s);
867 }
868 EXPORT_SYMBOL(strim);
869 
870 /**
871  * sysfs_streq - return true if strings are equal, modulo trailing newline
872  * @s1: one string
873  * @s2: another string
874  *
875  * This routine returns true iff two strings are equal, treating both
876  * NUL and newline-then-NUL as equivalent string terminations.  It's
877  * geared for use with sysfs input strings, which generally terminate
878  * with newlines but are compared against values without newlines.
879  */
880 bool sysfs_streq(const char *s1, const char *s2)
881 {
882 	while (*s1 && *s1 == *s2) {
883 		s1++;
884 		s2++;
885 	}
886 
887 	if (*s1 == *s2)
888 		return true;
889 	if (!*s1 && *s2 == '\n' && !s2[1])
890 		return true;
891 	if (*s1 == '\n' && !s1[1] && !*s2)
892 		return true;
893 	return false;
894 }
895 EXPORT_SYMBOL(sysfs_streq);
896 
897 /**
898  * match_string - matches given string in an array
899  * @array:	array of strings
900  * @n:		number of strings in the array or -1 for NULL terminated arrays
901  * @string:	string to match with
902  *
903  * This routine will look for a string in an array of strings up to the
904  * n-th element in the array or until the first NULL element.
905  *
906  * Historically the value of -1 for @n, was used to search in arrays that
907  * are NULL terminated. However, the function does not make a distinction
908  * when finishing the search: either @n elements have been compared OR
909  * the first NULL element was found.
910  *
911  * Return:
912  * index of a @string in the @array if matches, or %-EINVAL otherwise.
913  */
914 int match_string(const char * const *array, size_t n, const char *string)
915 {
916 	int index;
917 	const char *item;
918 
919 	for (index = 0; index < n; index++) {
920 		item = array[index];
921 		if (!item)
922 			break;
923 		if (!strcmp(item, string))
924 			return index;
925 	}
926 
927 	return -EINVAL;
928 }
929 EXPORT_SYMBOL(match_string);
930 
931 /**
932  * __sysfs_match_string - matches given string in an array
933  * @array: array of strings
934  * @n: number of strings in the array or -1 for NULL terminated arrays
935  * @str: string to match with
936  *
937  * Returns index of @str in the @array or -EINVAL, just like match_string().
938  * Uses sysfs_streq instead of strcmp for matching.
939  *
940  * This routine will look for a string in an array of strings up to the
941  * n-th element in the array or until the first NULL element.
942  *
943  * Historically the value of -1 for @n, was used to search in arrays that
944  * are NULL terminated. However, the function does not make a distinction
945  * when finishing the search: either @n elements have been compared OR
946  * the first NULL element was found.
947  */
948 int __sysfs_match_string(const char * const *array, size_t n, const char *str)
949 {
950 	const char *item;
951 	int index;
952 
953 	for (index = 0; index < n; index++) {
954 		item = array[index];
955 		if (!item)
956 			break;
957 		if (sysfs_streq(item, str))
958 			return index;
959 	}
960 
961 	return -EINVAL;
962 }
963 EXPORT_SYMBOL(__sysfs_match_string);
964 
965 /**
966  * strreplace - Replace all occurrences of character in string.
967  * @str: The string to operate on.
968  * @old: The character being replaced.
969  * @new: The character @old is replaced with.
970  *
971  * Replaces the each @old character with a @new one in the given string @str.
972  *
973  * Return: pointer to the string @str itself.
974  */
975 char *strreplace(char *str, char old, char new)
976 {
977 	char *s = str;
978 
979 	for (; *s; ++s)
980 		if (*s == old)
981 			*s = new;
982 	return str;
983 }
984 EXPORT_SYMBOL(strreplace);
985 
986 /**
987  * memcpy_and_pad - Copy one buffer to another with padding
988  * @dest: Where to copy to
989  * @dest_len: The destination buffer size
990  * @src: Where to copy from
991  * @count: The number of bytes to copy
992  * @pad: Character to use for padding if space is left in destination.
993  */
994 void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
995 		    int pad)
996 {
997 	if (dest_len > count) {
998 		memcpy(dest, src, count);
999 		memset(dest + count, pad,  dest_len - count);
1000 	} else {
1001 		memcpy(dest, src, dest_len);
1002 	}
1003 }
1004 EXPORT_SYMBOL(memcpy_and_pad);
1005 
1006 #ifdef CONFIG_FORTIFY_SOURCE
1007 /* These are placeholders for fortify compile-time warnings. */
1008 void __read_overflow2_field(size_t avail, size_t wanted) { }
1009 EXPORT_SYMBOL(__read_overflow2_field);
1010 void __write_overflow_field(size_t avail, size_t wanted) { }
1011 EXPORT_SYMBOL(__write_overflow_field);
1012 
1013 static const char * const fortify_func_name[] = {
1014 #define MAKE_FORTIFY_FUNC_NAME(func)	[MAKE_FORTIFY_FUNC(func)] = #func
1015 	EACH_FORTIFY_FUNC(MAKE_FORTIFY_FUNC_NAME)
1016 #undef  MAKE_FORTIFY_FUNC_NAME
1017 };
1018 
1019 void __fortify_report(const u8 reason)
1020 {
1021 	const u8 func = FORTIFY_REASON_FUNC(reason);
1022 	const bool write = FORTIFY_REASON_DIR(reason);
1023 	const char *name;
1024 
1025 	name = fortify_func_name[umin(func, FORTIFY_FUNC_UNKNOWN)];
1026 	WARN(1, "%s: detected buffer %s overflow\n", name, str_read_write(!write));
1027 }
1028 EXPORT_SYMBOL(__fortify_report);
1029 
1030 void __fortify_panic(const u8 reason)
1031 {
1032 	__fortify_report(reason);
1033 	BUG();
1034 }
1035 EXPORT_SYMBOL(__fortify_panic);
1036 #endif /* CONFIG_FORTIFY_SOURCE */
1037