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