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);
135 * parse_int_array_user - Split string into a sequence of integers
136 * @from: The user space buffer to read from
137 * @count: The maximum number of bytes to read
138 * @array: Returned pointer to sequence of integers
140 * On success @array is allocated and initialized with a sequence of
141 * integers extracted from the @from plus an additional element that
142 * begins the sequence and specifies the integers count.
144 * Caller takes responsibility for freeing @array when it is no longer
147 int parse_int_array_user(const char __user *from, size_t count, int **array)
153 buf = memdup_user_nul(from, count);
157 get_options(buf, 0, &nints);
163 ints = kcalloc(nints + 1, sizeof(*ints), GFP_KERNEL);
169 get_options(buf, nints + 1, ints);
176 EXPORT_SYMBOL(parse_int_array_user);
178 static bool unescape_space(char **src, char **dst)
180 char *p = *dst, *q = *src;
206 static bool unescape_octal(char **src, char **dst)
208 char *p = *dst, *q = *src;
211 if (isodigit(*q) == 0)
215 while (num < 32 && isodigit(*q) && (q - *src < 3)) {
225 static bool unescape_hex(char **src, char **dst)
227 char *p = *dst, *q = *src;
234 num = digit = hex_to_bin(*q++);
238 digit = hex_to_bin(*q);
241 num = (num << 4) | digit;
249 static bool unescape_special(char **src, char **dst)
251 char *p = *dst, *q = *src;
275 * string_unescape - unquote characters in the given string
276 * @src: source buffer (escaped)
277 * @dst: destination buffer (unescaped)
278 * @size: size of the destination buffer (0 to unlimit)
279 * @flags: combination of the flags.
282 * The function unquotes characters in the given string.
284 * Because the size of the output will be the same as or less than the size of
285 * the input, the transformation may be performed in place.
287 * Caller must provide valid source and destination pointers. Be aware that
288 * destination buffer will always be NULL-terminated. Source string must be
289 * NULL-terminated as well. The supported flags are::
294 * '\r' - carriage return
295 * '\t' - horizontal tab
296 * '\v' - vertical tab
298 * '\NNN' - byte with octal value NNN (1 to 3 digits)
300 * '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
302 * '\"' - double quote
307 * all previous together
310 * The amount of the characters processed to the destination buffer excluding
311 * trailing '\0' is returned.
313 int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
317 while (*src && --size) {
318 if (src[0] == '\\' && src[1] != '\0' && size > 1) {
322 if (flags & UNESCAPE_SPACE &&
323 unescape_space(&src, &out))
326 if (flags & UNESCAPE_OCTAL &&
327 unescape_octal(&src, &out))
330 if (flags & UNESCAPE_HEX &&
331 unescape_hex(&src, &out))
334 if (flags & UNESCAPE_SPECIAL &&
335 unescape_special(&src, &out))
346 EXPORT_SYMBOL(string_unescape);
348 static bool escape_passthrough(unsigned char c, char **dst, char *end)
358 static bool escape_space(unsigned char c, char **dst, char *end)
394 static bool escape_special(unsigned char c, char **dst, char *end)
427 static bool escape_null(unsigned char c, char **dst, char *end)
445 static bool escape_octal(unsigned char c, char **dst, char *end)
453 *out = ((c >> 6) & 0x07) + '0';
456 *out = ((c >> 3) & 0x07) + '0';
459 *out = ((c >> 0) & 0x07) + '0';
466 static bool escape_hex(unsigned char c, char **dst, char *end)
477 *out = hex_asc_hi(c);
480 *out = hex_asc_lo(c);
488 * string_escape_mem - quote characters in the given memory buffer
489 * @src: source buffer (unescaped)
490 * @isz: source buffer size
491 * @dst: destination buffer (escaped)
492 * @osz: destination buffer size
493 * @flags: combination of the flags
494 * @only: NULL-terminated string containing characters used to limit
495 * the selected escape class. If characters are included in @only
496 * that would not normally be escaped by the classes selected
497 * in @flags, they will be copied to @dst unescaped.
500 * The process of escaping byte buffer includes several parts. They are applied
501 * in the following sequence.
503 * 1. The character is not matched to the one from @only string and thus
504 * must go as-is to the output.
505 * 2. The character is matched to the printable and ASCII classes, if asked,
506 * and in case of match it passes through to the output.
507 * 3. The character is matched to the printable or ASCII class, if asked,
508 * and in case of match it passes through to the output.
509 * 4. The character is checked if it falls into the class given by @flags.
510 * %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
511 * character. Note that they actually can't go together, otherwise
512 * %ESCAPE_HEX will be ignored.
514 * Caller must provide valid source and destination pointers. Be aware that
515 * destination buffer will not be NULL-terminated, thus caller have to append
516 * it if needs. The supported flags are::
518 * %ESCAPE_SPACE: (special white space, not space itself)
521 * '\r' - carriage return
522 * '\t' - horizontal tab
523 * '\v' - vertical tab
525 * '\"' - double quote
532 * '\NNN' - byte with octal value NNN (3 digits)
534 * all previous together
536 * escape only non-printable characters, checked by isprint()
538 * all previous together
540 * '\xHH' - byte with hexadecimal value HH (2 digits)
542 * escape only non-ascii characters, checked by isascii()
544 * escape only non-printable or non-ascii characters
546 * append characters from @only to be escaped by the given classes
548 * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
549 * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
551 * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
552 * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
553 * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
554 * or %ESCAPE_HEX, because they cover most of the other character classes.
555 * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
559 * The total size of the escaped output that would be generated for
560 * the given input and flags. To check whether the output was
561 * truncated, compare the return value to osz. There is room left in
562 * dst for a '\0' terminator if and only if ret < osz.
564 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
565 unsigned int flags, const char *only)
569 bool is_dict = only && *only;
570 bool is_append = flags & ESCAPE_APPEND;
573 unsigned char c = *src++;
574 bool in_dict = is_dict && strchr(only, c);
577 * Apply rules in the following sequence:
578 * - the @only string is supplied and does not contain a
579 * character under question
580 * - the character is printable and ASCII, when @flags has
581 * %ESCAPE_NAP bit set
582 * - the character is printable, when @flags has
584 * - the character is ASCII, when @flags has
586 * - the character doesn't fall into a class of symbols
587 * defined by given @flags
588 * In these cases we just pass through a character to the
591 * When %ESCAPE_APPEND is passed, the characters from @only
592 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
595 if (!(is_append || in_dict) && is_dict &&
596 escape_passthrough(c, &p, end))
599 if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
600 flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
603 if (!(is_append && in_dict) && isprint(c) &&
604 flags & ESCAPE_NP && escape_passthrough(c, &p, end))
607 if (!(is_append && in_dict) && isascii(c) &&
608 flags & ESCAPE_NA && escape_passthrough(c, &p, end))
611 if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
614 if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
617 if (flags & ESCAPE_NULL && escape_null(c, &p, end))
620 /* ESCAPE_OCTAL and ESCAPE_HEX always go last */
621 if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
624 if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
627 escape_passthrough(c, &p, end);
632 EXPORT_SYMBOL(string_escape_mem);
635 * Return an allocated string that has been escaped of special characters
636 * and double quotes, making it safe to log in quotes.
638 char *kstrdup_quotable(const char *src, gfp_t gfp)
642 const int flags = ESCAPE_HEX;
643 const char esc[] = "\f\n\r\t\v\a\e\\\"";
649 dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
650 dst = kmalloc(dlen + 1, gfp);
654 WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
659 EXPORT_SYMBOL_GPL(kstrdup_quotable);
662 * Returns allocated NULL-terminated string containing process
663 * command line, with inter-argument NULLs replaced with spaces,
664 * and other special characters escaped.
666 char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
668 char *buffer, *quoted;
671 buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
675 res = get_cmdline(task, buffer, PAGE_SIZE - 1);
678 /* Collapse trailing NULLs, leave res pointing to last non-NULL. */
679 while (--res >= 0 && buffer[res] == '\0')
682 /* Replace inter-argument NULLs. */
683 for (i = 0; i <= res; i++)
684 if (buffer[i] == '\0')
687 /* Make sure result is printable. */
688 quoted = kstrdup_quotable(buffer, gfp);
692 EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
695 * Returns allocated NULL-terminated string containing pathname,
696 * with special characters escaped, able to be safely logged. If
697 * there is an error, the leading character will be "<".
699 char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
701 char *temp, *pathname;
704 return kstrdup("<unknown>", gfp);
706 /* We add 11 spaces for ' (deleted)' to be appended */
707 temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
709 return kstrdup("<no_memory>", gfp);
711 pathname = file_path(file, temp, PATH_MAX + 11);
712 if (IS_ERR(pathname))
713 pathname = kstrdup("<too_long>", gfp);
715 pathname = kstrdup_quotable(pathname, gfp);
720 EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
723 * kasprintf_strarray - allocate and fill array of sequential strings
724 * @gfp: flags for the slab allocator
725 * @prefix: prefix to be used
726 * @n: amount of lines to be allocated and filled
728 * Allocates and fills @n strings using pattern "%s-%zu", where prefix
729 * is provided by caller. The caller is responsible to free them with
730 * kfree_strarray() after use.
732 * Returns array of strings or NULL when memory can't be allocated.
734 char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
739 names = kcalloc(n + 1, sizeof(char *), gfp);
743 for (i = 0; i < n; i++) {
744 names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
746 kfree_strarray(names, i);
753 EXPORT_SYMBOL_GPL(kasprintf_strarray);
756 * kfree_strarray - free a number of dynamically allocated strings contained
757 * in an array and the array itself
759 * @array: Dynamically allocated array of strings to free.
760 * @n: Number of strings (starting from the beginning of the array) to free.
762 * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
763 * use-cases. If @array is NULL, the function does nothing.
765 void kfree_strarray(char **array, size_t n)
772 for (i = 0; i < n; i++)
776 EXPORT_SYMBOL_GPL(kfree_strarray);
783 static void devm_kfree_strarray(struct device *dev, void *res)
785 struct strarray *array = res;
787 kfree_strarray(array->array, array->n);
790 char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
792 struct strarray *ptr;
794 ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
796 return ERR_PTR(-ENOMEM);
798 ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
801 return ERR_PTR(-ENOMEM);
805 devres_add(dev, ptr);
809 EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
812 * strscpy_pad() - Copy a C-string into a sized buffer
813 * @dest: Where to copy the string to
814 * @src: Where to copy the string from
815 * @count: Size of destination buffer
817 * Copy the string, or as much of it as fits, into the dest buffer. The
818 * behavior is undefined if the string buffers overlap. The destination
819 * buffer is always %NUL terminated, unless it's zero-sized.
821 * If the source string is shorter than the destination buffer, zeros
822 * the tail of the destination buffer.
824 * For full explanation of why you may want to consider using the
825 * 'strscpy' functions please see the function docstring for strscpy().
828 * * The number of characters copied (not including the trailing %NUL)
829 * * -E2BIG if count is 0 or @src was truncated.
831 ssize_t strscpy_pad(char *dest, const char *src, size_t count)
835 written = strscpy(dest, src, count);
836 if (written < 0 || written == count - 1)
839 memset(dest + written + 1, 0, count - written - 1);
843 EXPORT_SYMBOL(strscpy_pad);
846 * skip_spaces - Removes leading whitespace from @str.
847 * @str: The string to be stripped.
849 * Returns a pointer to the first non-whitespace character in @str.
851 char *skip_spaces(const char *str)
853 while (isspace(*str))
857 EXPORT_SYMBOL(skip_spaces);
860 * strim - Removes leading and trailing whitespace from @s.
861 * @s: The string to be stripped.
863 * Note that the first trailing whitespace is replaced with a %NUL-terminator
864 * in the given string @s. Returns a pointer to the first non-whitespace
877 while (end >= s && isspace(*end))
881 return skip_spaces(s);
883 EXPORT_SYMBOL(strim);
886 * sysfs_streq - return true if strings are equal, modulo trailing newline
888 * @s2: another string
890 * This routine returns true iff two strings are equal, treating both
891 * NUL and newline-then-NUL as equivalent string terminations. It's
892 * geared for use with sysfs input strings, which generally terminate
893 * with newlines but are compared against values without newlines.
895 bool sysfs_streq(const char *s1, const char *s2)
897 while (*s1 && *s1 == *s2) {
904 if (!*s1 && *s2 == '\n' && !s2[1])
906 if (*s1 == '\n' && !s1[1] && !*s2)
910 EXPORT_SYMBOL(sysfs_streq);
913 * match_string - matches given string in an array
914 * @array: array of strings
915 * @n: number of strings in the array or -1 for NULL terminated arrays
916 * @string: string to match with
918 * This routine will look for a string in an array of strings up to the
919 * n-th element in the array or until the first NULL element.
921 * Historically the value of -1 for @n, was used to search in arrays that
922 * are NULL terminated. However, the function does not make a distinction
923 * when finishing the search: either @n elements have been compared OR
924 * the first NULL element was found.
927 * index of a @string in the @array if matches, or %-EINVAL otherwise.
929 int match_string(const char * const *array, size_t n, const char *string)
934 for (index = 0; index < n; index++) {
938 if (!strcmp(item, string))
944 EXPORT_SYMBOL(match_string);
947 * __sysfs_match_string - matches given string in an array
948 * @array: array of strings
949 * @n: number of strings in the array or -1 for NULL terminated arrays
950 * @str: string to match with
952 * Returns index of @str in the @array or -EINVAL, just like match_string().
953 * Uses sysfs_streq instead of strcmp for matching.
955 * This routine will look for a string in an array of strings up to the
956 * n-th element in the array or until the first NULL element.
958 * Historically the value of -1 for @n, was used to search in arrays that
959 * are NULL terminated. However, the function does not make a distinction
960 * when finishing the search: either @n elements have been compared OR
961 * the first NULL element was found.
963 int __sysfs_match_string(const char * const *array, size_t n, const char *str)
968 for (index = 0; index < n; index++) {
972 if (sysfs_streq(item, str))
978 EXPORT_SYMBOL(__sysfs_match_string);
981 * strreplace - Replace all occurrences of character in string.
982 * @str: The string to operate on.
983 * @old: The character being replaced.
984 * @new: The character @old is replaced with.
986 * Replaces the each @old character with a @new one in the given string @str.
988 * Return: pointer to the string @str itself.
990 char *strreplace(char *str, char old, char new)
999 EXPORT_SYMBOL(strreplace);
1002 * memcpy_and_pad - Copy one buffer to another with padding
1003 * @dest: Where to copy to
1004 * @dest_len: The destination buffer size
1005 * @src: Where to copy from
1006 * @count: The number of bytes to copy
1007 * @pad: Character to use for padding if space is left in destination.
1009 void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
1012 if (dest_len > count) {
1013 memcpy(dest, src, count);
1014 memset(dest + count, pad, dest_len - count);
1016 memcpy(dest, src, dest_len);
1019 EXPORT_SYMBOL(memcpy_and_pad);
1021 #ifdef CONFIG_FORTIFY_SOURCE
1022 /* These are placeholders for fortify compile-time warnings. */
1023 void __read_overflow2_field(size_t avail, size_t wanted) { }
1024 EXPORT_SYMBOL(__read_overflow2_field);
1025 void __write_overflow_field(size_t avail, size_t wanted) { }
1026 EXPORT_SYMBOL(__write_overflow_field);
1028 void fortify_panic(const char *name)
1030 pr_emerg("detected buffer overflow in %s\n", name);
1033 EXPORT_SYMBOL(fortify_panic);
1034 #endif /* CONFIG_FORTIFY_SOURCE */