Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Helpers for formatting and printing strings
0004  *
0005  * Copyright 31 August 2008 James Bottomley
0006  * Copyright (C) 2013, Intel Corporation
0007  */
0008 #include <linux/bug.h>
0009 #include <linux/kernel.h>
0010 #include <linux/math64.h>
0011 #include <linux/export.h>
0012 #include <linux/ctype.h>
0013 #include <linux/device.h>
0014 #include <linux/errno.h>
0015 #include <linux/fs.h>
0016 #include <linux/limits.h>
0017 #include <linux/mm.h>
0018 #include <linux/slab.h>
0019 #include <linux/string.h>
0020 #include <linux/string_helpers.h>
0021 
0022 /**
0023  * string_get_size - get the size in the specified units
0024  * @size:   The size to be converted in blocks
0025  * @blk_size:   Size of the block (use 1 for size in bytes)
0026  * @units:  units to use (powers of 1000 or 1024)
0027  * @buf:    buffer to format to
0028  * @len:    length of buffer
0029  *
0030  * This function returns a string formatted to 3 significant figures
0031  * giving the size in the required units.  @buf should have room for
0032  * at least 9 bytes and will always be zero terminated.
0033  *
0034  */
0035 void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
0036              char *buf, int len)
0037 {
0038     static const char *const units_10[] = {
0039         "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
0040     };
0041     static const char *const units_2[] = {
0042         "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
0043     };
0044     static const char *const *const units_str[] = {
0045         [STRING_UNITS_10] = units_10,
0046         [STRING_UNITS_2] = units_2,
0047     };
0048     static const unsigned int divisor[] = {
0049         [STRING_UNITS_10] = 1000,
0050         [STRING_UNITS_2] = 1024,
0051     };
0052     static const unsigned int rounding[] = { 500, 50, 5 };
0053     int i = 0, j;
0054     u32 remainder = 0, sf_cap;
0055     char tmp[8];
0056     const char *unit;
0057 
0058     tmp[0] = '\0';
0059 
0060     if (blk_size == 0)
0061         size = 0;
0062     if (size == 0)
0063         goto out;
0064 
0065     /* This is Napier's algorithm.  Reduce the original block size to
0066      *
0067      * coefficient * divisor[units]^i
0068      *
0069      * we do the reduction so both coefficients are just under 32 bits so
0070      * that multiplying them together won't overflow 64 bits and we keep
0071      * as much precision as possible in the numbers.
0072      *
0073      * Note: it's safe to throw away the remainders here because all the
0074      * precision is in the coefficients.
0075      */
0076     while (blk_size >> 32) {
0077         do_div(blk_size, divisor[units]);
0078         i++;
0079     }
0080 
0081     while (size >> 32) {
0082         do_div(size, divisor[units]);
0083         i++;
0084     }
0085 
0086     /* now perform the actual multiplication keeping i as the sum of the
0087      * two logarithms */
0088     size *= blk_size;
0089 
0090     /* and logarithmically reduce it until it's just under the divisor */
0091     while (size >= divisor[units]) {
0092         remainder = do_div(size, divisor[units]);
0093         i++;
0094     }
0095 
0096     /* work out in j how many digits of precision we need from the
0097      * remainder */
0098     sf_cap = size;
0099     for (j = 0; sf_cap*10 < 1000; j++)
0100         sf_cap *= 10;
0101 
0102     if (units == STRING_UNITS_2) {
0103         /* express the remainder as a decimal.  It's currently the
0104          * numerator of a fraction whose denominator is
0105          * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
0106         remainder *= 1000;
0107         remainder >>= 10;
0108     }
0109 
0110     /* add a 5 to the digit below what will be printed to ensure
0111      * an arithmetical round up and carry it through to size */
0112     remainder += rounding[j];
0113     if (remainder >= 1000) {
0114         remainder -= 1000;
0115         size += 1;
0116     }
0117 
0118     if (j) {
0119         snprintf(tmp, sizeof(tmp), ".%03u", remainder);
0120         tmp[j+1] = '\0';
0121     }
0122 
0123  out:
0124     if (i >= ARRAY_SIZE(units_2))
0125         unit = "UNK";
0126     else
0127         unit = units_str[units][i];
0128 
0129     snprintf(buf, len, "%u%s %s", (u32)size,
0130          tmp, unit);
0131 }
0132 EXPORT_SYMBOL(string_get_size);
0133 
0134 static bool unescape_space(char **src, char **dst)
0135 {
0136     char *p = *dst, *q = *src;
0137 
0138     switch (*q) {
0139     case 'n':
0140         *p = '\n';
0141         break;
0142     case 'r':
0143         *p = '\r';
0144         break;
0145     case 't':
0146         *p = '\t';
0147         break;
0148     case 'v':
0149         *p = '\v';
0150         break;
0151     case 'f':
0152         *p = '\f';
0153         break;
0154     default:
0155         return false;
0156     }
0157     *dst += 1;
0158     *src += 1;
0159     return true;
0160 }
0161 
0162 static bool unescape_octal(char **src, char **dst)
0163 {
0164     char *p = *dst, *q = *src;
0165     u8 num;
0166 
0167     if (isodigit(*q) == 0)
0168         return false;
0169 
0170     num = (*q++) & 7;
0171     while (num < 32 && isodigit(*q) && (q - *src < 3)) {
0172         num <<= 3;
0173         num += (*q++) & 7;
0174     }
0175     *p = num;
0176     *dst += 1;
0177     *src = q;
0178     return true;
0179 }
0180 
0181 static bool unescape_hex(char **src, char **dst)
0182 {
0183     char *p = *dst, *q = *src;
0184     int digit;
0185     u8 num;
0186 
0187     if (*q++ != 'x')
0188         return false;
0189 
0190     num = digit = hex_to_bin(*q++);
0191     if (digit < 0)
0192         return false;
0193 
0194     digit = hex_to_bin(*q);
0195     if (digit >= 0) {
0196         q++;
0197         num = (num << 4) | digit;
0198     }
0199     *p = num;
0200     *dst += 1;
0201     *src = q;
0202     return true;
0203 }
0204 
0205 static bool unescape_special(char **src, char **dst)
0206 {
0207     char *p = *dst, *q = *src;
0208 
0209     switch (*q) {
0210     case '\"':
0211         *p = '\"';
0212         break;
0213     case '\\':
0214         *p = '\\';
0215         break;
0216     case 'a':
0217         *p = '\a';
0218         break;
0219     case 'e':
0220         *p = '\e';
0221         break;
0222     default:
0223         return false;
0224     }
0225     *dst += 1;
0226     *src += 1;
0227     return true;
0228 }
0229 
0230 /**
0231  * string_unescape - unquote characters in the given string
0232  * @src:    source buffer (escaped)
0233  * @dst:    destination buffer (unescaped)
0234  * @size:   size of the destination buffer (0 to unlimit)
0235  * @flags:  combination of the flags.
0236  *
0237  * Description:
0238  * The function unquotes characters in the given string.
0239  *
0240  * Because the size of the output will be the same as or less than the size of
0241  * the input, the transformation may be performed in place.
0242  *
0243  * Caller must provide valid source and destination pointers. Be aware that
0244  * destination buffer will always be NULL-terminated. Source string must be
0245  * NULL-terminated as well.  The supported flags are::
0246  *
0247  *  UNESCAPE_SPACE:
0248  *      '\f' - form feed
0249  *      '\n' - new line
0250  *      '\r' - carriage return
0251  *      '\t' - horizontal tab
0252  *      '\v' - vertical tab
0253  *  UNESCAPE_OCTAL:
0254  *      '\NNN' - byte with octal value NNN (1 to 3 digits)
0255  *  UNESCAPE_HEX:
0256  *      '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
0257  *  UNESCAPE_SPECIAL:
0258  *      '\"' - double quote
0259  *      '\\' - backslash
0260  *      '\a' - alert (BEL)
0261  *      '\e' - escape
0262  *  UNESCAPE_ANY:
0263  *      all previous together
0264  *
0265  * Return:
0266  * The amount of the characters processed to the destination buffer excluding
0267  * trailing '\0' is returned.
0268  */
0269 int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
0270 {
0271     char *out = dst;
0272 
0273     while (*src && --size) {
0274         if (src[0] == '\\' && src[1] != '\0' && size > 1) {
0275             src++;
0276             size--;
0277 
0278             if (flags & UNESCAPE_SPACE &&
0279                     unescape_space(&src, &out))
0280                 continue;
0281 
0282             if (flags & UNESCAPE_OCTAL &&
0283                     unescape_octal(&src, &out))
0284                 continue;
0285 
0286             if (flags & UNESCAPE_HEX &&
0287                     unescape_hex(&src, &out))
0288                 continue;
0289 
0290             if (flags & UNESCAPE_SPECIAL &&
0291                     unescape_special(&src, &out))
0292                 continue;
0293 
0294             *out++ = '\\';
0295         }
0296         *out++ = *src++;
0297     }
0298     *out = '\0';
0299 
0300     return out - dst;
0301 }
0302 EXPORT_SYMBOL(string_unescape);
0303 
0304 static bool escape_passthrough(unsigned char c, char **dst, char *end)
0305 {
0306     char *out = *dst;
0307 
0308     if (out < end)
0309         *out = c;
0310     *dst = out + 1;
0311     return true;
0312 }
0313 
0314 static bool escape_space(unsigned char c, char **dst, char *end)
0315 {
0316     char *out = *dst;
0317     unsigned char to;
0318 
0319     switch (c) {
0320     case '\n':
0321         to = 'n';
0322         break;
0323     case '\r':
0324         to = 'r';
0325         break;
0326     case '\t':
0327         to = 't';
0328         break;
0329     case '\v':
0330         to = 'v';
0331         break;
0332     case '\f':
0333         to = 'f';
0334         break;
0335     default:
0336         return false;
0337     }
0338 
0339     if (out < end)
0340         *out = '\\';
0341     ++out;
0342     if (out < end)
0343         *out = to;
0344     ++out;
0345 
0346     *dst = out;
0347     return true;
0348 }
0349 
0350 static bool escape_special(unsigned char c, char **dst, char *end)
0351 {
0352     char *out = *dst;
0353     unsigned char to;
0354 
0355     switch (c) {
0356     case '\\':
0357         to = '\\';
0358         break;
0359     case '\a':
0360         to = 'a';
0361         break;
0362     case '\e':
0363         to = 'e';
0364         break;
0365     case '"':
0366         to = '"';
0367         break;
0368     default:
0369         return false;
0370     }
0371 
0372     if (out < end)
0373         *out = '\\';
0374     ++out;
0375     if (out < end)
0376         *out = to;
0377     ++out;
0378 
0379     *dst = out;
0380     return true;
0381 }
0382 
0383 static bool escape_null(unsigned char c, char **dst, char *end)
0384 {
0385     char *out = *dst;
0386 
0387     if (c)
0388         return false;
0389 
0390     if (out < end)
0391         *out = '\\';
0392     ++out;
0393     if (out < end)
0394         *out = '0';
0395     ++out;
0396 
0397     *dst = out;
0398     return true;
0399 }
0400 
0401 static bool escape_octal(unsigned char c, char **dst, char *end)
0402 {
0403     char *out = *dst;
0404 
0405     if (out < end)
0406         *out = '\\';
0407     ++out;
0408     if (out < end)
0409         *out = ((c >> 6) & 0x07) + '0';
0410     ++out;
0411     if (out < end)
0412         *out = ((c >> 3) & 0x07) + '0';
0413     ++out;
0414     if (out < end)
0415         *out = ((c >> 0) & 0x07) + '0';
0416     ++out;
0417 
0418     *dst = out;
0419     return true;
0420 }
0421 
0422 static bool escape_hex(unsigned char c, char **dst, char *end)
0423 {
0424     char *out = *dst;
0425 
0426     if (out < end)
0427         *out = '\\';
0428     ++out;
0429     if (out < end)
0430         *out = 'x';
0431     ++out;
0432     if (out < end)
0433         *out = hex_asc_hi(c);
0434     ++out;
0435     if (out < end)
0436         *out = hex_asc_lo(c);
0437     ++out;
0438 
0439     *dst = out;
0440     return true;
0441 }
0442 
0443 /**
0444  * string_escape_mem - quote characters in the given memory buffer
0445  * @src:    source buffer (unescaped)
0446  * @isz:    source buffer size
0447  * @dst:    destination buffer (escaped)
0448  * @osz:    destination buffer size
0449  * @flags:  combination of the flags
0450  * @only:   NULL-terminated string containing characters used to limit
0451  *      the selected escape class. If characters are included in @only
0452  *      that would not normally be escaped by the classes selected
0453  *      in @flags, they will be copied to @dst unescaped.
0454  *
0455  * Description:
0456  * The process of escaping byte buffer includes several parts. They are applied
0457  * in the following sequence.
0458  *
0459  *  1. The character is not matched to the one from @only string and thus
0460  *     must go as-is to the output.
0461  *  2. The character is matched to the printable and ASCII classes, if asked,
0462  *     and in case of match it passes through to the output.
0463  *  3. The character is matched to the printable or ASCII class, if asked,
0464  *     and in case of match it passes through to the output.
0465  *  4. The character is checked if it falls into the class given by @flags.
0466  *     %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
0467  *     character. Note that they actually can't go together, otherwise
0468  *     %ESCAPE_HEX will be ignored.
0469  *
0470  * Caller must provide valid source and destination pointers. Be aware that
0471  * destination buffer will not be NULL-terminated, thus caller have to append
0472  * it if needs. The supported flags are::
0473  *
0474  *  %ESCAPE_SPACE: (special white space, not space itself)
0475  *      '\f' - form feed
0476  *      '\n' - new line
0477  *      '\r' - carriage return
0478  *      '\t' - horizontal tab
0479  *      '\v' - vertical tab
0480  *  %ESCAPE_SPECIAL:
0481  *      '\"' - double quote
0482  *      '\\' - backslash
0483  *      '\a' - alert (BEL)
0484  *      '\e' - escape
0485  *  %ESCAPE_NULL:
0486  *      '\0' - null
0487  *  %ESCAPE_OCTAL:
0488  *      '\NNN' - byte with octal value NNN (3 digits)
0489  *  %ESCAPE_ANY:
0490  *      all previous together
0491  *  %ESCAPE_NP:
0492  *      escape only non-printable characters, checked by isprint()
0493  *  %ESCAPE_ANY_NP:
0494  *      all previous together
0495  *  %ESCAPE_HEX:
0496  *      '\xHH' - byte with hexadecimal value HH (2 digits)
0497  *  %ESCAPE_NA:
0498  *      escape only non-ascii characters, checked by isascii()
0499  *  %ESCAPE_NAP:
0500  *      escape only non-printable or non-ascii characters
0501  *  %ESCAPE_APPEND:
0502  *      append characters from @only to be escaped by the given classes
0503  *
0504  * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
0505  * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
0506  *
0507  * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
0508  * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
0509  * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
0510  * or %ESCAPE_HEX, because they cover most of the other character classes.
0511  * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
0512  * the above.
0513  *
0514  * Return:
0515  * The total size of the escaped output that would be generated for
0516  * the given input and flags. To check whether the output was
0517  * truncated, compare the return value to osz. There is room left in
0518  * dst for a '\0' terminator if and only if ret < osz.
0519  */
0520 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
0521               unsigned int flags, const char *only)
0522 {
0523     char *p = dst;
0524     char *end = p + osz;
0525     bool is_dict = only && *only;
0526     bool is_append = flags & ESCAPE_APPEND;
0527 
0528     while (isz--) {
0529         unsigned char c = *src++;
0530         bool in_dict = is_dict && strchr(only, c);
0531 
0532         /*
0533          * Apply rules in the following sequence:
0534          *  - the @only string is supplied and does not contain a
0535          *    character under question
0536          *  - the character is printable and ASCII, when @flags has
0537          *    %ESCAPE_NAP bit set
0538          *  - the character is printable, when @flags has
0539          *    %ESCAPE_NP bit set
0540          *  - the character is ASCII, when @flags has
0541          *    %ESCAPE_NA bit set
0542          *  - the character doesn't fall into a class of symbols
0543          *    defined by given @flags
0544          * In these cases we just pass through a character to the
0545          * output buffer.
0546          *
0547          * When %ESCAPE_APPEND is passed, the characters from @only
0548          * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
0549          * %ESCAPE_NA cases.
0550          */
0551         if (!(is_append || in_dict) && is_dict &&
0552                       escape_passthrough(c, &p, end))
0553             continue;
0554 
0555         if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
0556             flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
0557             continue;
0558 
0559         if (!(is_append && in_dict) && isprint(c) &&
0560             flags & ESCAPE_NP && escape_passthrough(c, &p, end))
0561             continue;
0562 
0563         if (!(is_append && in_dict) && isascii(c) &&
0564             flags & ESCAPE_NA && escape_passthrough(c, &p, end))
0565             continue;
0566 
0567         if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
0568             continue;
0569 
0570         if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
0571             continue;
0572 
0573         if (flags & ESCAPE_NULL && escape_null(c, &p, end))
0574             continue;
0575 
0576         /* ESCAPE_OCTAL and ESCAPE_HEX always go last */
0577         if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
0578             continue;
0579 
0580         if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
0581             continue;
0582 
0583         escape_passthrough(c, &p, end);
0584     }
0585 
0586     return p - dst;
0587 }
0588 EXPORT_SYMBOL(string_escape_mem);
0589 
0590 /*
0591  * Return an allocated string that has been escaped of special characters
0592  * and double quotes, making it safe to log in quotes.
0593  */
0594 char *kstrdup_quotable(const char *src, gfp_t gfp)
0595 {
0596     size_t slen, dlen;
0597     char *dst;
0598     const int flags = ESCAPE_HEX;
0599     const char esc[] = "\f\n\r\t\v\a\e\\\"";
0600 
0601     if (!src)
0602         return NULL;
0603     slen = strlen(src);
0604 
0605     dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
0606     dst = kmalloc(dlen + 1, gfp);
0607     if (!dst)
0608         return NULL;
0609 
0610     WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
0611     dst[dlen] = '\0';
0612 
0613     return dst;
0614 }
0615 EXPORT_SYMBOL_GPL(kstrdup_quotable);
0616 
0617 /*
0618  * Returns allocated NULL-terminated string containing process
0619  * command line, with inter-argument NULLs replaced with spaces,
0620  * and other special characters escaped.
0621  */
0622 char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
0623 {
0624     char *buffer, *quoted;
0625     int i, res;
0626 
0627     buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
0628     if (!buffer)
0629         return NULL;
0630 
0631     res = get_cmdline(task, buffer, PAGE_SIZE - 1);
0632     buffer[res] = '\0';
0633 
0634     /* Collapse trailing NULLs, leave res pointing to last non-NULL. */
0635     while (--res >= 0 && buffer[res] == '\0')
0636         ;
0637 
0638     /* Replace inter-argument NULLs. */
0639     for (i = 0; i <= res; i++)
0640         if (buffer[i] == '\0')
0641             buffer[i] = ' ';
0642 
0643     /* Make sure result is printable. */
0644     quoted = kstrdup_quotable(buffer, gfp);
0645     kfree(buffer);
0646     return quoted;
0647 }
0648 EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
0649 
0650 /*
0651  * Returns allocated NULL-terminated string containing pathname,
0652  * with special characters escaped, able to be safely logged. If
0653  * there is an error, the leading character will be "<".
0654  */
0655 char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
0656 {
0657     char *temp, *pathname;
0658 
0659     if (!file)
0660         return kstrdup("<unknown>", gfp);
0661 
0662     /* We add 11 spaces for ' (deleted)' to be appended */
0663     temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
0664     if (!temp)
0665         return kstrdup("<no_memory>", gfp);
0666 
0667     pathname = file_path(file, temp, PATH_MAX + 11);
0668     if (IS_ERR(pathname))
0669         pathname = kstrdup("<too_long>", gfp);
0670     else
0671         pathname = kstrdup_quotable(pathname, gfp);
0672 
0673     kfree(temp);
0674     return pathname;
0675 }
0676 EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
0677 
0678 /**
0679  * kasprintf_strarray - allocate and fill array of sequential strings
0680  * @gfp: flags for the slab allocator
0681  * @prefix: prefix to be used
0682  * @n: amount of lines to be allocated and filled
0683  *
0684  * Allocates and fills @n strings using pattern "%s-%zu", where prefix
0685  * is provided by caller. The caller is responsible to free them with
0686  * kfree_strarray() after use.
0687  *
0688  * Returns array of strings or NULL when memory can't be allocated.
0689  */
0690 char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
0691 {
0692     char **names;
0693     size_t i;
0694 
0695     names = kcalloc(n + 1, sizeof(char *), gfp);
0696     if (!names)
0697         return NULL;
0698 
0699     for (i = 0; i < n; i++) {
0700         names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
0701         if (!names[i]) {
0702             kfree_strarray(names, i);
0703             return NULL;
0704         }
0705     }
0706 
0707     return names;
0708 }
0709 EXPORT_SYMBOL_GPL(kasprintf_strarray);
0710 
0711 /**
0712  * kfree_strarray - free a number of dynamically allocated strings contained
0713  *                  in an array and the array itself
0714  *
0715  * @array: Dynamically allocated array of strings to free.
0716  * @n: Number of strings (starting from the beginning of the array) to free.
0717  *
0718  * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
0719  * use-cases. If @array is NULL, the function does nothing.
0720  */
0721 void kfree_strarray(char **array, size_t n)
0722 {
0723     unsigned int i;
0724 
0725     if (!array)
0726         return;
0727 
0728     for (i = 0; i < n; i++)
0729         kfree(array[i]);
0730     kfree(array);
0731 }
0732 EXPORT_SYMBOL_GPL(kfree_strarray);
0733 
0734 struct strarray {
0735     char **array;
0736     size_t n;
0737 };
0738 
0739 static void devm_kfree_strarray(struct device *dev, void *res)
0740 {
0741     struct strarray *array = res;
0742 
0743     kfree_strarray(array->array, array->n);
0744 }
0745 
0746 char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
0747 {
0748     struct strarray *ptr;
0749 
0750     ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
0751     if (!ptr)
0752         return ERR_PTR(-ENOMEM);
0753 
0754     ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
0755     if (!ptr->array) {
0756         devres_free(ptr);
0757         return ERR_PTR(-ENOMEM);
0758     }
0759 
0760     ptr->n = n;
0761     devres_add(dev, ptr);
0762 
0763     return ptr->array;
0764 }
0765 EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
0766 
0767 /**
0768  * strscpy_pad() - Copy a C-string into a sized buffer
0769  * @dest: Where to copy the string to
0770  * @src: Where to copy the string from
0771  * @count: Size of destination buffer
0772  *
0773  * Copy the string, or as much of it as fits, into the dest buffer.  The
0774  * behavior is undefined if the string buffers overlap.  The destination
0775  * buffer is always %NUL terminated, unless it's zero-sized.
0776  *
0777  * If the source string is shorter than the destination buffer, zeros
0778  * the tail of the destination buffer.
0779  *
0780  * For full explanation of why you may want to consider using the
0781  * 'strscpy' functions please see the function docstring for strscpy().
0782  *
0783  * Returns:
0784  * * The number of characters copied (not including the trailing %NUL)
0785  * * -E2BIG if count is 0 or @src was truncated.
0786  */
0787 ssize_t strscpy_pad(char *dest, const char *src, size_t count)
0788 {
0789     ssize_t written;
0790 
0791     written = strscpy(dest, src, count);
0792     if (written < 0 || written == count - 1)
0793         return written;
0794 
0795     memset(dest + written + 1, 0, count - written - 1);
0796 
0797     return written;
0798 }
0799 EXPORT_SYMBOL(strscpy_pad);
0800 
0801 /**
0802  * skip_spaces - Removes leading whitespace from @str.
0803  * @str: The string to be stripped.
0804  *
0805  * Returns a pointer to the first non-whitespace character in @str.
0806  */
0807 char *skip_spaces(const char *str)
0808 {
0809     while (isspace(*str))
0810         ++str;
0811     return (char *)str;
0812 }
0813 EXPORT_SYMBOL(skip_spaces);
0814 
0815 /**
0816  * strim - Removes leading and trailing whitespace from @s.
0817  * @s: The string to be stripped.
0818  *
0819  * Note that the first trailing whitespace is replaced with a %NUL-terminator
0820  * in the given string @s. Returns a pointer to the first non-whitespace
0821  * character in @s.
0822  */
0823 char *strim(char *s)
0824 {
0825     size_t size;
0826     char *end;
0827 
0828     size = strlen(s);
0829     if (!size)
0830         return s;
0831 
0832     end = s + size - 1;
0833     while (end >= s && isspace(*end))
0834         end--;
0835     *(end + 1) = '\0';
0836 
0837     return skip_spaces(s);
0838 }
0839 EXPORT_SYMBOL(strim);
0840 
0841 /**
0842  * sysfs_streq - return true if strings are equal, modulo trailing newline
0843  * @s1: one string
0844  * @s2: another string
0845  *
0846  * This routine returns true iff two strings are equal, treating both
0847  * NUL and newline-then-NUL as equivalent string terminations.  It's
0848  * geared for use with sysfs input strings, which generally terminate
0849  * with newlines but are compared against values without newlines.
0850  */
0851 bool sysfs_streq(const char *s1, const char *s2)
0852 {
0853     while (*s1 && *s1 == *s2) {
0854         s1++;
0855         s2++;
0856     }
0857 
0858     if (*s1 == *s2)
0859         return true;
0860     if (!*s1 && *s2 == '\n' && !s2[1])
0861         return true;
0862     if (*s1 == '\n' && !s1[1] && !*s2)
0863         return true;
0864     return false;
0865 }
0866 EXPORT_SYMBOL(sysfs_streq);
0867 
0868 /**
0869  * match_string - matches given string in an array
0870  * @array:  array of strings
0871  * @n:      number of strings in the array or -1 for NULL terminated arrays
0872  * @string: string to match with
0873  *
0874  * This routine will look for a string in an array of strings up to the
0875  * n-th element in the array or until the first NULL element.
0876  *
0877  * Historically the value of -1 for @n, was used to search in arrays that
0878  * are NULL terminated. However, the function does not make a distinction
0879  * when finishing the search: either @n elements have been compared OR
0880  * the first NULL element was found.
0881  *
0882  * Return:
0883  * index of a @string in the @array if matches, or %-EINVAL otherwise.
0884  */
0885 int match_string(const char * const *array, size_t n, const char *string)
0886 {
0887     int index;
0888     const char *item;
0889 
0890     for (index = 0; index < n; index++) {
0891         item = array[index];
0892         if (!item)
0893             break;
0894         if (!strcmp(item, string))
0895             return index;
0896     }
0897 
0898     return -EINVAL;
0899 }
0900 EXPORT_SYMBOL(match_string);
0901 
0902 /**
0903  * __sysfs_match_string - matches given string in an array
0904  * @array: array of strings
0905  * @n: number of strings in the array or -1 for NULL terminated arrays
0906  * @str: string to match with
0907  *
0908  * Returns index of @str in the @array or -EINVAL, just like match_string().
0909  * Uses sysfs_streq instead of strcmp for matching.
0910  *
0911  * This routine will look for a string in an array of strings up to the
0912  * n-th element in the array or until the first NULL element.
0913  *
0914  * Historically the value of -1 for @n, was used to search in arrays that
0915  * are NULL terminated. However, the function does not make a distinction
0916  * when finishing the search: either @n elements have been compared OR
0917  * the first NULL element was found.
0918  */
0919 int __sysfs_match_string(const char * const *array, size_t n, const char *str)
0920 {
0921     const char *item;
0922     int index;
0923 
0924     for (index = 0; index < n; index++) {
0925         item = array[index];
0926         if (!item)
0927             break;
0928         if (sysfs_streq(item, str))
0929             return index;
0930     }
0931 
0932     return -EINVAL;
0933 }
0934 EXPORT_SYMBOL(__sysfs_match_string);
0935 
0936 /**
0937  * strreplace - Replace all occurrences of character in string.
0938  * @s: The string to operate on.
0939  * @old: The character being replaced.
0940  * @new: The character @old is replaced with.
0941  *
0942  * Returns pointer to the nul byte at the end of @s.
0943  */
0944 char *strreplace(char *s, char old, char new)
0945 {
0946     for (; *s; ++s)
0947         if (*s == old)
0948             *s = new;
0949     return s;
0950 }
0951 EXPORT_SYMBOL(strreplace);
0952 
0953 /**
0954  * memcpy_and_pad - Copy one buffer to another with padding
0955  * @dest: Where to copy to
0956  * @dest_len: The destination buffer size
0957  * @src: Where to copy from
0958  * @count: The number of bytes to copy
0959  * @pad: Character to use for padding if space is left in destination.
0960  */
0961 void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
0962             int pad)
0963 {
0964     if (dest_len > count) {
0965         memcpy(dest, src, count);
0966         memset(dest + count, pad,  dest_len - count);
0967     } else {
0968         memcpy(dest, src, dest_len);
0969     }
0970 }
0971 EXPORT_SYMBOL(memcpy_and_pad);
0972 
0973 #ifdef CONFIG_FORTIFY_SOURCE
0974 /* These are placeholders for fortify compile-time warnings. */
0975 void __read_overflow2_field(size_t avail, size_t wanted) { }
0976 EXPORT_SYMBOL(__read_overflow2_field);
0977 void __write_overflow_field(size_t avail, size_t wanted) { }
0978 EXPORT_SYMBOL(__write_overflow_field);
0979 
0980 void fortify_panic(const char *name)
0981 {
0982     pr_emerg("detected buffer overflow in %s\n", name);
0983     BUG();
0984 }
0985 EXPORT_SYMBOL(fortify_panic);
0986 #endif /* CONFIG_FORTIFY_SOURCE */