1 // SPDX-License-Identifier: GPL-2.0-only
3 * Helpers for formatting and printing strings
5 * Copyright 31 August 2008 James Bottomley
6 * Copyright (C) 2013, Intel Corporation
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>
16 #include <linux/limits.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/string_helpers.h>
23 * string_get_size - get the size in the specified units
24 * @size: The size to be converted in blocks
25 * @blk_size: Size of the block (use 1 for size in bytes)
26 * @units: units to use (powers of 1000 or 1024)
27 * @buf: buffer to format to
28 * @len: length of buffer
30 * This function returns a string formatted to 3 significant figures
31 * giving the size in the required units. @buf should have room for
32 * at least 9 bytes and will always be zero terminated.
35 void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
38 static const char *const units_10[] = {
39 "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
41 static const char *const units_2[] = {
42 "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
44 static const char *const *const units_str[] = {
45 [STRING_UNITS_10] = units_10,
46 [STRING_UNITS_2] = units_2,
48 static const unsigned int divisor[] = {
49 [STRING_UNITS_10] = 1000,
50 [STRING_UNITS_2] = 1024,
52 static const unsigned int rounding[] = { 500, 50, 5 };
54 u32 remainder = 0, sf_cap;
65 /* This is Napier's algorithm. Reduce the original block size to
67 * coefficient * divisor[units]^i
69 * we do the reduction so both coefficients are just under 32 bits so
70 * that multiplying them together won't overflow 64 bits and we keep
71 * as much precision as possible in the numbers.
73 * Note: it's safe to throw away the remainders here because all the
74 * precision is in the coefficients.
76 while (blk_size >> 32) {
77 do_div(blk_size, divisor[units]);
82 do_div(size, divisor[units]);
86 /* now perform the actual multiplication keeping i as the sum of the
90 /* and logarithmically reduce it until it's just under the divisor */
91 while (size >= divisor[units]) {
92 remainder = do_div(size, divisor[units]);
96 /* work out in j how many digits of precision we need from the
99 for (j = 0; sf_cap*10 < 1000; j++)
102 if (units == STRING_UNITS_2) {
103 /* express the remainder as a decimal. It's currently the
104 * numerator of a fraction whose denominator is
105 * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
110 /* add a 5 to the digit below what will be printed to ensure
111 * an arithmetical round up and carry it through to size */
112 remainder += rounding[j];
113 if (remainder >= 1000) {
119 snprintf(tmp, sizeof(tmp), ".%03u", remainder);
124 if (i >= ARRAY_SIZE(units_2))
127 unit = units_str[units][i];
129 snprintf(buf, len, "%u%s %s", (u32)size,
132 EXPORT_SYMBOL(string_get_size);
134 static bool unescape_space(char **src, char **dst)
136 char *p = *dst, *q = *src;
162 static bool unescape_octal(char **src, char **dst)
164 char *p = *dst, *q = *src;
167 if (isodigit(*q) == 0)
171 while (num < 32 && isodigit(*q) && (q - *src < 3)) {
181 static bool unescape_hex(char **src, char **dst)
183 char *p = *dst, *q = *src;
190 num = digit = hex_to_bin(*q++);
194 digit = hex_to_bin(*q);
197 num = (num << 4) | digit;
205 static bool unescape_special(char **src, char **dst)
207 char *p = *dst, *q = *src;
231 * string_unescape - unquote characters in the given string
232 * @src: source buffer (escaped)
233 * @dst: destination buffer (unescaped)
234 * @size: size of the destination buffer (0 to unlimit)
235 * @flags: combination of the flags.
238 * The function unquotes characters in the given string.
240 * Because the size of the output will be the same as or less than the size of
241 * the input, the transformation may be performed in place.
243 * Caller must provide valid source and destination pointers. Be aware that
244 * destination buffer will always be NULL-terminated. Source string must be
245 * NULL-terminated as well. The supported flags are::
250 * '\r' - carriage return
251 * '\t' - horizontal tab
252 * '\v' - vertical tab
254 * '\NNN' - byte with octal value NNN (1 to 3 digits)
256 * '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
258 * '\"' - double quote
263 * all previous together
266 * The amount of the characters processed to the destination buffer excluding
267 * trailing '\0' is returned.
269 int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
273 while (*src && --size) {
274 if (src[0] == '\\' && src[1] != '\0' && size > 1) {
278 if (flags & UNESCAPE_SPACE &&
279 unescape_space(&src, &out))
282 if (flags & UNESCAPE_OCTAL &&
283 unescape_octal(&src, &out))
286 if (flags & UNESCAPE_HEX &&
287 unescape_hex(&src, &out))
290 if (flags & UNESCAPE_SPECIAL &&
291 unescape_special(&src, &out))
302 EXPORT_SYMBOL(string_unescape);
304 static bool escape_passthrough(unsigned char c, char **dst, char *end)
314 static bool escape_space(unsigned char c, char **dst, char *end)
350 static bool escape_special(unsigned char c, char **dst, char *end)
383 static bool escape_null(unsigned char c, char **dst, char *end)
401 static bool escape_octal(unsigned char c, char **dst, char *end)
409 *out = ((c >> 6) & 0x07) + '0';
412 *out = ((c >> 3) & 0x07) + '0';
415 *out = ((c >> 0) & 0x07) + '0';
422 static bool escape_hex(unsigned char c, char **dst, char *end)
433 *out = hex_asc_hi(c);
436 *out = hex_asc_lo(c);
444 * string_escape_mem - quote characters in the given memory buffer
445 * @src: source buffer (unescaped)
446 * @isz: source buffer size
447 * @dst: destination buffer (escaped)
448 * @osz: destination buffer size
449 * @flags: combination of the flags
450 * @only: NULL-terminated string containing characters used to limit
451 * the selected escape class. If characters are included in @only
452 * that would not normally be escaped by the classes selected
453 * in @flags, they will be copied to @dst unescaped.
456 * The process of escaping byte buffer includes several parts. They are applied
457 * in the following sequence.
459 * 1. The character is not matched to the one from @only string and thus
460 * must go as-is to the output.
461 * 2. The character is matched to the printable and ASCII classes, if asked,
462 * and in case of match it passes through to the output.
463 * 3. The character is matched to the printable or ASCII class, if asked,
464 * and in case of match it passes through to the output.
465 * 4. The character is checked if it falls into the class given by @flags.
466 * %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
467 * character. Note that they actually can't go together, otherwise
468 * %ESCAPE_HEX will be ignored.
470 * Caller must provide valid source and destination pointers. Be aware that
471 * destination buffer will not be NULL-terminated, thus caller have to append
472 * it if needs. The supported flags are::
474 * %ESCAPE_SPACE: (special white space, not space itself)
477 * '\r' - carriage return
478 * '\t' - horizontal tab
479 * '\v' - vertical tab
481 * '\"' - double quote
488 * '\NNN' - byte with octal value NNN (3 digits)
490 * all previous together
492 * escape only non-printable characters, checked by isprint()
494 * all previous together
496 * '\xHH' - byte with hexadecimal value HH (2 digits)
498 * escape only non-ascii characters, checked by isascii()
500 * escape only non-printable or non-ascii characters
502 * append characters from @only to be escaped by the given classes
504 * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
505 * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
507 * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
508 * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
509 * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
510 * or %ESCAPE_HEX, because they cover most of the other character classes.
511 * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
515 * The total size of the escaped output that would be generated for
516 * the given input and flags. To check whether the output was
517 * truncated, compare the return value to osz. There is room left in
518 * dst for a '\0' terminator if and only if ret < osz.
520 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
521 unsigned int flags, const char *only)
525 bool is_dict = only && *only;
526 bool is_append = flags & ESCAPE_APPEND;
529 unsigned char c = *src++;
530 bool in_dict = is_dict && strchr(only, c);
533 * Apply rules in the following sequence:
534 * - the @only string is supplied and does not contain a
535 * character under question
536 * - the character is printable and ASCII, when @flags has
537 * %ESCAPE_NAP bit set
538 * - the character is printable, when @flags has
540 * - the character is ASCII, when @flags has
542 * - the character doesn't fall into a class of symbols
543 * defined by given @flags
544 * In these cases we just pass through a character to the
547 * When %ESCAPE_APPEND is passed, the characters from @only
548 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
551 if (!(is_append || in_dict) && is_dict &&
552 escape_passthrough(c, &p, end))
555 if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
556 flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
559 if (!(is_append && in_dict) && isprint(c) &&
560 flags & ESCAPE_NP && escape_passthrough(c, &p, end))
563 if (!(is_append && in_dict) && isascii(c) &&
564 flags & ESCAPE_NA && escape_passthrough(c, &p, end))
567 if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
570 if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
573 if (flags & ESCAPE_NULL && escape_null(c, &p, end))
576 /* ESCAPE_OCTAL and ESCAPE_HEX always go last */
577 if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
580 if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
583 escape_passthrough(c, &p, end);
588 EXPORT_SYMBOL(string_escape_mem);
591 * Return an allocated string that has been escaped of special characters
592 * and double quotes, making it safe to log in quotes.
594 char *kstrdup_quotable(const char *src, gfp_t gfp)
598 const int flags = ESCAPE_HEX;
599 const char esc[] = "\f\n\r\t\v\a\e\\\"";
605 dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
606 dst = kmalloc(dlen + 1, gfp);
610 WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
615 EXPORT_SYMBOL_GPL(kstrdup_quotable);
618 * Returns allocated NULL-terminated string containing process
619 * command line, with inter-argument NULLs replaced with spaces,
620 * and other special characters escaped.
622 char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
624 char *buffer, *quoted;
627 buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
631 res = get_cmdline(task, buffer, PAGE_SIZE - 1);
634 /* Collapse trailing NULLs, leave res pointing to last non-NULL. */
635 while (--res >= 0 && buffer[res] == '\0')
638 /* Replace inter-argument NULLs. */
639 for (i = 0; i <= res; i++)
640 if (buffer[i] == '\0')
643 /* Make sure result is printable. */
644 quoted = kstrdup_quotable(buffer, gfp);
648 EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
651 * Returns allocated NULL-terminated string containing pathname,
652 * with special characters escaped, able to be safely logged. If
653 * there is an error, the leading character will be "<".
655 char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
657 char *temp, *pathname;
660 return kstrdup("<unknown>", gfp);
662 /* We add 11 spaces for ' (deleted)' to be appended */
663 temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
665 return kstrdup("<no_memory>", gfp);
667 pathname = file_path(file, temp, PATH_MAX + 11);
668 if (IS_ERR(pathname))
669 pathname = kstrdup("<too_long>", gfp);
671 pathname = kstrdup_quotable(pathname, gfp);
676 EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
679 * kasprintf_strarray - allocate and fill array of sequential strings
680 * @gfp: flags for the slab allocator
681 * @prefix: prefix to be used
682 * @n: amount of lines to be allocated and filled
684 * Allocates and fills @n strings using pattern "%s-%zu", where prefix
685 * is provided by caller. The caller is responsible to free them with
686 * kfree_strarray() after use.
688 * Returns array of strings or NULL when memory can't be allocated.
690 char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
695 names = kcalloc(n + 1, sizeof(char *), gfp);
699 for (i = 0; i < n; i++) {
700 names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
702 kfree_strarray(names, i);
709 EXPORT_SYMBOL_GPL(kasprintf_strarray);
712 * kfree_strarray - free a number of dynamically allocated strings contained
713 * in an array and the array itself
715 * @array: Dynamically allocated array of strings to free.
716 * @n: Number of strings (starting from the beginning of the array) to free.
718 * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
719 * use-cases. If @array is NULL, the function does nothing.
721 void kfree_strarray(char **array, size_t n)
728 for (i = 0; i < n; i++)
732 EXPORT_SYMBOL_GPL(kfree_strarray);
739 static void devm_kfree_strarray(struct device *dev, void *res)
741 struct strarray *array = res;
743 kfree_strarray(array->array, array->n);
746 char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
748 struct strarray *ptr;
750 ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
752 return ERR_PTR(-ENOMEM);
754 ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
757 return ERR_PTR(-ENOMEM);
762 EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
765 * strscpy_pad() - Copy a C-string into a sized buffer
766 * @dest: Where to copy the string to
767 * @src: Where to copy the string from
768 * @count: Size of destination buffer
770 * Copy the string, or as much of it as fits, into the dest buffer. The
771 * behavior is undefined if the string buffers overlap. The destination
772 * buffer is always %NUL terminated, unless it's zero-sized.
774 * If the source string is shorter than the destination buffer, zeros
775 * the tail of the destination buffer.
777 * For full explanation of why you may want to consider using the
778 * 'strscpy' functions please see the function docstring for strscpy().
781 * * The number of characters copied (not including the trailing %NUL)
782 * * -E2BIG if count is 0 or @src was truncated.
784 ssize_t strscpy_pad(char *dest, const char *src, size_t count)
788 written = strscpy(dest, src, count);
789 if (written < 0 || written == count - 1)
792 memset(dest + written + 1, 0, count - written - 1);
796 EXPORT_SYMBOL(strscpy_pad);
799 * skip_spaces - Removes leading whitespace from @str.
800 * @str: The string to be stripped.
802 * Returns a pointer to the first non-whitespace character in @str.
804 char *skip_spaces(const char *str)
806 while (isspace(*str))
810 EXPORT_SYMBOL(skip_spaces);
813 * strim - Removes leading and trailing whitespace from @s.
814 * @s: The string to be stripped.
816 * Note that the first trailing whitespace is replaced with a %NUL-terminator
817 * in the given string @s. Returns a pointer to the first non-whitespace
830 while (end >= s && isspace(*end))
834 return skip_spaces(s);
836 EXPORT_SYMBOL(strim);
839 * sysfs_streq - return true if strings are equal, modulo trailing newline
841 * @s2: another string
843 * This routine returns true iff two strings are equal, treating both
844 * NUL and newline-then-NUL as equivalent string terminations. It's
845 * geared for use with sysfs input strings, which generally terminate
846 * with newlines but are compared against values without newlines.
848 bool sysfs_streq(const char *s1, const char *s2)
850 while (*s1 && *s1 == *s2) {
857 if (!*s1 && *s2 == '\n' && !s2[1])
859 if (*s1 == '\n' && !s1[1] && !*s2)
863 EXPORT_SYMBOL(sysfs_streq);
866 * match_string - matches given string in an array
867 * @array: array of strings
868 * @n: number of strings in the array or -1 for NULL terminated arrays
869 * @string: string to match with
871 * This routine will look for a string in an array of strings up to the
872 * n-th element in the array or until the first NULL element.
874 * Historically the value of -1 for @n, was used to search in arrays that
875 * are NULL terminated. However, the function does not make a distinction
876 * when finishing the search: either @n elements have been compared OR
877 * the first NULL element was found.
880 * index of a @string in the @array if matches, or %-EINVAL otherwise.
882 int match_string(const char * const *array, size_t n, const char *string)
887 for (index = 0; index < n; index++) {
891 if (!strcmp(item, string))
897 EXPORT_SYMBOL(match_string);
900 * __sysfs_match_string - matches given string in an array
901 * @array: array of strings
902 * @n: number of strings in the array or -1 for NULL terminated arrays
903 * @str: string to match with
905 * Returns index of @str in the @array or -EINVAL, just like match_string().
906 * Uses sysfs_streq instead of strcmp for matching.
908 * This routine will look for a string in an array of strings up to the
909 * n-th element in the array or until the first NULL element.
911 * Historically the value of -1 for @n, was used to search in arrays that
912 * are NULL terminated. However, the function does not make a distinction
913 * when finishing the search: either @n elements have been compared OR
914 * the first NULL element was found.
916 int __sysfs_match_string(const char * const *array, size_t n, const char *str)
921 for (index = 0; index < n; index++) {
925 if (sysfs_streq(item, str))
931 EXPORT_SYMBOL(__sysfs_match_string);
934 * strreplace - Replace all occurrences of character in string.
935 * @s: The string to operate on.
936 * @old: The character being replaced.
937 * @new: The character @old is replaced with.
939 * Returns pointer to the nul byte at the end of @s.
941 char *strreplace(char *s, char old, char new)
948 EXPORT_SYMBOL(strreplace);
951 * memcpy_and_pad - Copy one buffer to another with padding
952 * @dest: Where to copy to
953 * @dest_len: The destination buffer size
954 * @src: Where to copy from
955 * @count: The number of bytes to copy
956 * @pad: Character to use for padding if space is left in destination.
958 void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
961 if (dest_len > count) {
962 memcpy(dest, src, count);
963 memset(dest + count, pad, dest_len - count);
965 memcpy(dest, src, dest_len);
968 EXPORT_SYMBOL(memcpy_and_pad);
970 #ifdef CONFIG_FORTIFY_SOURCE
971 void fortify_panic(const char *name)
973 pr_emerg("detected buffer overflow in %s\n", name);
976 EXPORT_SYMBOL(fortify_panic);
977 #endif /* CONFIG_FORTIFY_SOURCE */