]> git.ipfire.org Git - thirdparty/linux.git/blame - lib/string_helpers.c
fortify: Improve buffer overflow reporting
[thirdparty/linux.git] / lib / string_helpers.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
3c9f3681
JB
2/*
3 * Helpers for formatting and printing strings
4 *
5 * Copyright 31 August 2008 James Bottomley
16c7fa05 6 * Copyright (C) 2013, Intel Corporation
3c9f3681 7 */
b9f28d86 8#include <linux/bug.h>
3c9f3681
JB
9#include <linux/kernel.h>
10#include <linux/math64.h>
8bc3bcc9 11#include <linux/export.h>
16c7fa05 12#include <linux/ctype.h>
acdb89b6 13#include <linux/device.h>
c8250381 14#include <linux/errno.h>
21985319
KC
15#include <linux/fs.h>
16#include <linux/limits.h>
0d044328 17#include <linux/mm.h>
b53f27e4 18#include <linux/slab.h>
c8250381 19#include <linux/string.h>
3c9f3681 20#include <linux/string_helpers.h>
4ce615e7
KC
21#include <kunit/test.h>
22#include <kunit/test-bug.h>
3c9f3681
JB
23
24/**
25 * string_get_size - get the size in the specified units
b9f28d86
JB
26 * @size: The size to be converted in blocks
27 * @blk_size: Size of the block (use 1 for size in bytes)
3c9f3681
JB
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
d1214c65
RV
33 * giving the size in the required units. @buf should have room for
34 * at least 9 bytes and will always be zero terminated.
3c9f3681 35 *
83feeb19
KO
36 * Return value: number of characters of output that would have been written
37 * (which may be greater than len, if output was truncated).
3c9f3681 38 */
83feeb19
KO
39int string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
40 char *buf, int len)
3c9f3681 41{
142cda5d 42 static const char *const units_10[] = {
b9f28d86 43 "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
142cda5d
MK
44 };
45 static const char *const units_2[] = {
b9f28d86 46 "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
142cda5d
MK
47 };
48 static const char *const *const units_str[] = {
49 [STRING_UNITS_10] = units_10,
3c9f3681
JB
50 [STRING_UNITS_2] = units_2,
51 };
68aecfb9 52 static const unsigned int divisor[] = {
3c9f3681
JB
53 [STRING_UNITS_10] = 1000,
54 [STRING_UNITS_2] = 1024,
55 };
564b026f
JB
56 static const unsigned int rounding[] = { 500, 50, 5 };
57 int i = 0, j;
58 u32 remainder = 0, sf_cap;
3c9f3681 59 char tmp[8];
b9f28d86 60 const char *unit;
3c9f3681
JB
61
62 tmp[0] = '\0';
564b026f
JB
63
64 if (blk_size == 0)
65 size = 0;
66 if (size == 0)
b9f28d86 67 goto out;
3c9f3681 68
564b026f
JB
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]);
b9f28d86
JB
82 i++;
83 }
84
564b026f
JB
85 while (size >> 32) {
86 do_div(size, divisor[units]);
b9f28d86 87 i++;
b9f28d86
JB
88 }
89
564b026f
JB
90 /* now perform the actual multiplication keeping i as the sum of the
91 * two logarithms */
b9f28d86 92 size *= blk_size;
3c9f3681 93
564b026f 94 /* and logarithmically reduce it until it's just under the divisor */
b9f28d86
JB
95 while (size >= divisor[units]) {
96 remainder = do_div(size, divisor[units]);
97 i++;
3c9f3681
JB
98 }
99
564b026f
JB
100 /* work out in j how many digits of precision we need from the
101 * remainder */
b9f28d86
JB
102 sf_cap = size;
103 for (j = 0; sf_cap*10 < 1000; j++)
104 sf_cap *= 10;
105
564b026f
JB
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 */
b9f28d86 110 remainder *= 1000;
564b026f
JB
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) {
b9f28d86
JB
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
83feeb19
KO
133 return snprintf(buf, len, "%u%s %s", (u32)size,
134 tmp, unit);
3c9f3681
JB
135}
136EXPORT_SYMBOL(string_get_size);
16c7fa05 137
f0b93323
CR
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 */
151int 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
176free_buf:
177 kfree(buf);
178 return ret;
179}
180EXPORT_SYMBOL(parse_int_array_user);
181
16c7fa05
AS
182static 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
210static 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
229static 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
253static 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
d295634e
AS
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)
b4658cdd
JC
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:
d295634e
AS
296 * '\f' - form feed
297 * '\n' - new line
298 * '\r' - carriage return
299 * '\t' - horizontal tab
300 * '\v' - vertical tab
b4658cdd 301 * UNESCAPE_OCTAL:
d295634e 302 * '\NNN' - byte with octal value NNN (1 to 3 digits)
b4658cdd 303 * UNESCAPE_HEX:
d295634e 304 * '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
b4658cdd 305 * UNESCAPE_SPECIAL:
d295634e
AS
306 * '\"' - double quote
307 * '\\' - backslash
308 * '\a' - alert (BEL)
309 * '\e' - escape
b4658cdd 310 * UNESCAPE_ANY:
d295634e
AS
311 * all previous together
312 *
d295634e
AS
313 * Return:
314 * The amount of the characters processed to the destination buffer excluding
315 * trailing '\0' is returned.
316 */
16c7fa05
AS
317int 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}
350EXPORT_SYMBOL(string_unescape);
c8250381 351
3aeddc7d 352static bool escape_passthrough(unsigned char c, char **dst, char *end)
c8250381
AS
353{
354 char *out = *dst;
355
3aeddc7d
RV
356 if (out < end)
357 *out = c;
358 *dst = out + 1;
359 return true;
c8250381
AS
360}
361
3aeddc7d 362static bool escape_space(unsigned char c, char **dst, char *end)
c8250381
AS
363{
364 char *out = *dst;
365 unsigned char to;
366
c8250381
AS
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:
3aeddc7d 384 return false;
c8250381
AS
385 }
386
3aeddc7d
RV
387 if (out < end)
388 *out = '\\';
389 ++out;
390 if (out < end)
391 *out = to;
392 ++out;
c8250381 393
3aeddc7d
RV
394 *dst = out;
395 return true;
c8250381
AS
396}
397
3aeddc7d 398static bool escape_special(unsigned char c, char **dst, char *end)
c8250381
AS
399{
400 char *out = *dst;
401 unsigned char to;
402
c8250381
AS
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;
91027d0a
CD
413 case '"':
414 to = '"';
415 break;
c8250381 416 default:
3aeddc7d 417 return false;
c8250381
AS
418 }
419
3aeddc7d
RV
420 if (out < end)
421 *out = '\\';
422 ++out;
423 if (out < end)
424 *out = to;
425 ++out;
c8250381 426
3aeddc7d
RV
427 *dst = out;
428 return true;
c8250381
AS
429}
430
3aeddc7d 431static bool escape_null(unsigned char c, char **dst, char *end)
c8250381
AS
432{
433 char *out = *dst;
434
c8250381 435 if (c)
3aeddc7d 436 return false;
c8250381 437
3aeddc7d
RV
438 if (out < end)
439 *out = '\\';
440 ++out;
441 if (out < end)
442 *out = '0';
443 ++out;
c8250381 444
3aeddc7d
RV
445 *dst = out;
446 return true;
c8250381
AS
447}
448
3aeddc7d 449static bool escape_octal(unsigned char c, char **dst, char *end)
c8250381
AS
450{
451 char *out = *dst;
452
3aeddc7d
RV
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;
c8250381
AS
465
466 *dst = out;
3aeddc7d 467 return true;
c8250381
AS
468}
469
3aeddc7d 470static bool escape_hex(unsigned char c, char **dst, char *end)
c8250381
AS
471{
472 char *out = *dst;
473
3aeddc7d
RV
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;
c8250381
AS
486
487 *dst = out;
3aeddc7d 488 return true;
c8250381
AS
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
b4658cdd
JC
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 *
62519b88 507 * 1. The character is not matched to the one from @only string and thus
b4658cdd 508 * must go as-is to the output.
0362c27f 509 * 2. The character is matched to the printable and ASCII classes, if asked,
a0809783 510 * and in case of match it passes through to the output.
0362c27f
AS
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.
b4658cdd
JC
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
a0809783 520 * it if needs. The supported flags are::
b4658cdd 521 *
d89a3f73 522 * %ESCAPE_SPACE: (special white space, not space itself)
c8250381
AS
523 * '\f' - form feed
524 * '\n' - new line
525 * '\r' - carriage return
526 * '\t' - horizontal tab
527 * '\v' - vertical tab
528 * %ESCAPE_SPECIAL:
91027d0a 529 * '\"' - double quote
c8250381
AS
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:
a0809783 540 * escape only non-printable characters, checked by isprint()
c8250381
AS
541 * %ESCAPE_ANY_NP:
542 * all previous together
543 * %ESCAPE_HEX:
544 * '\xHH' - byte with hexadecimal value HH (2 digits)
a0809783
AS
545 * %ESCAPE_NA:
546 * escape only non-ascii characters, checked by isascii()
0362c27f
AS
547 * %ESCAPE_NAP:
548 * escape only non-printable or non-ascii characters
aec0d096
AS
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.
a0809783 554 *
0362c27f
AS
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).
a0809783
AS
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.
0362c27f
AS
559 * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
560 * the above.
c8250381
AS
561 *
562 * Return:
41416f23
RV
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.
c8250381 567 */
41416f23 568int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
b40bdb7f 569 unsigned int flags, const char *only)
c8250381 570{
41416f23 571 char *p = dst;
3aeddc7d 572 char *end = p + osz;
b40bdb7f 573 bool is_dict = only && *only;
aec0d096 574 bool is_append = flags & ESCAPE_APPEND;
c8250381
AS
575
576 while (isz--) {
577 unsigned char c = *src++;
aec0d096 578 bool in_dict = is_dict && strchr(only, c);
c8250381
AS
579
580 /*
581 * Apply rules in the following sequence:
b40bdb7f 582 * - the @only string is supplied and does not contain a
c8250381 583 * character under question
0362c27f
AS
584 * - the character is printable and ASCII, when @flags has
585 * %ESCAPE_NAP bit set
62519b88
AS
586 * - the character is printable, when @flags has
587 * %ESCAPE_NP bit set
a0809783
AS
588 * - the character is ASCII, when @flags has
589 * %ESCAPE_NA bit set
c8250381
AS
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.
aec0d096
AS
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.
c8250381 598 */
aec0d096 599 if (!(is_append || in_dict) && is_dict &&
7e5969ae
AS
600 escape_passthrough(c, &p, end))
601 continue;
62519b88 602
aec0d096 603 if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
0362c27f
AS
604 flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
605 continue;
606
aec0d096 607 if (!(is_append && in_dict) && isprint(c) &&
7e5969ae
AS
608 flags & ESCAPE_NP && escape_passthrough(c, &p, end))
609 continue;
3aeddc7d 610
aec0d096 611 if (!(is_append && in_dict) && isascii(c) &&
a0809783
AS
612 flags & ESCAPE_NA && escape_passthrough(c, &p, end))
613 continue;
614
7e5969ae
AS
615 if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
616 continue;
3aeddc7d 617
7e5969ae
AS
618 if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
619 continue;
c8250381 620
7e5969ae
AS
621 if (flags & ESCAPE_NULL && escape_null(c, &p, end))
622 continue;
3aeddc7d 623
7e5969ae
AS
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;
c8250381 630
3aeddc7d 631 escape_passthrough(c, &p, end);
c8250381
AS
632 }
633
41416f23 634 return p - dst;
c8250381
AS
635}
636EXPORT_SYMBOL(string_escape_mem);
b53f27e4
KC
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 */
642char *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}
663EXPORT_SYMBOL_GPL(kstrdup_quotable);
0d044328
KC
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 */
670char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
671{
672 char *buffer, *quoted;
673 int i, res;
674
0ee931c4 675 buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
0d044328
KC
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}
696EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
21985319
KC
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 */
703char *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 */
0ee931c4 711 temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
21985319
KC
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}
724EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
0fd16012 725
045ad464
AS
726/*
727 * Returns duplicate string in which the @old characters are replaced by @new.
728 */
729char *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}
739EXPORT_SYMBOL_GPL(kstrdup_and_replace);
740
418e0a35
AS
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 */
753char **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}
772EXPORT_SYMBOL_GPL(kasprintf_strarray);
773
0fd16012
BG
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 */
784void 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}
795EXPORT_SYMBOL_GPL(kfree_strarray);
cfecea6e 796
acdb89b6
AS
797struct strarray {
798 char **array;
799 size_t n;
800};
801
802static 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
809char **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
cd290a98
PL
823 ptr->n = n;
824 devres_add(dev, ptr);
825
acdb89b6
AS
826 return ptr->array;
827}
828EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
829
cfecea6e
KC
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 */
836char *skip_spaces(const char *str)
837{
838 while (isspace(*str))
839 ++str;
840 return (char *)str;
841}
842EXPORT_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 */
852char *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}
868EXPORT_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 */
880bool 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}
895EXPORT_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 */
914int 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}
929EXPORT_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 */
948int __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}
963EXPORT_SYMBOL(__sysfs_match_string);
964
965/**
966 * strreplace - Replace all occurrences of character in string.
d01a77af 967 * @str: The string to operate on.
cfecea6e
KC
968 * @old: The character being replaced.
969 * @new: The character @old is replaced with.
970 *
d01a77af
AS
971 * Replaces the each @old character with a @new one in the given string @str.
972 *
973 * Return: pointer to the string @str itself.
cfecea6e 974 */
d01a77af 975char *strreplace(char *str, char old, char new)
cfecea6e 976{
d01a77af
AS
977 char *s = str;
978
cfecea6e
KC
979 for (; *s; ++s)
980 if (*s == old)
981 *s = new;
d01a77af 982 return str;
cfecea6e
KC
983}
984EXPORT_SYMBOL(strreplace);
985
5c4e0a21
GR
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 */
994void 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}
1004EXPORT_SYMBOL(memcpy_and_pad);
1005
c430f600 1006#ifdef CONFIG_FORTIFY_SOURCE
f68f2ff9
KC
1007/* These are placeholders for fortify compile-time warnings. */
1008void __read_overflow2_field(size_t avail, size_t wanted) { }
1009EXPORT_SYMBOL(__read_overflow2_field);
1010void __write_overflow_field(size_t avail, size_t wanted) { }
1011EXPORT_SYMBOL(__write_overflow_field);
1012
475ddf1f
KC
1013static 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
3d965b33 1019void __fortify_report(const u8 reason, const size_t avail, const size_t size)
475ddf1f
KC
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)];
3d965b33
KC
1026 WARN(1, "%s: detected buffer overflow: %zu byte %s of buffer size %zu\n",
1027 name, size, str_read_write(!write), avail);
475ddf1f
KC
1028}
1029EXPORT_SYMBOL(__fortify_report);
1030
3d965b33 1031void __fortify_panic(const u8 reason, const size_t avail, const size_t size)
cfecea6e 1032{
3d965b33 1033 __fortify_report(reason, avail, size);
cfecea6e
KC
1034 BUG();
1035}
475ddf1f 1036EXPORT_SYMBOL(__fortify_panic);
c430f600 1037#endif /* CONFIG_FORTIFY_SOURCE */