4 * Copyright (C) 1991, 1992 Linus Torvalds
7 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
9 * Wirzenius wrote this portably, Torvalds fucked it up :-)
13 * Fri Jul 13 2001 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
14 * - changed to provide snprintf and vsnprintf functions
15 * So Feb 1 16:51:32 CET 2004 Juergen Quade <quade@hsnr.de>
16 * - scnprintf and vscnprintf
20 #include <linux/clk.h>
21 #include <linux/clk-provider.h>
22 #include <linux/module.h> /* for KSYM_SYMBOL_LEN */
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/ctype.h>
26 #include <linux/kernel.h>
27 #include <linux/kallsyms.h>
28 #include <linux/math64.h>
29 #include <linux/uaccess.h>
30 #include <linux/ioport.h>
31 #include <linux/dcache.h>
32 #include <linux/cred.h>
33 #include <net/addrconf.h>
35 #include <linux/blkdev.h>
38 #include <asm/page.h> /* for PAGE_SIZE */
39 #include <asm/sections.h> /* for dereference_function_descriptor() */
40 #include <asm/byteorder.h> /* cpu_to_le16 */
42 #include <linux/string_helpers.h>
46 * simple_strtoull - convert a string to an unsigned long long
47 * @cp: The start of the string
48 * @endp: A pointer to the end of the parsed string will be placed here
49 * @base: The number base to use
51 * This function is obsolete. Please use kstrtoull instead.
53 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
55 unsigned long long result;
58 cp = _parse_integer_fixup_radix(cp, &base);
59 rv = _parse_integer(cp, base, &result);
61 cp += (rv & ~KSTRTOX_OVERFLOW);
68 EXPORT_SYMBOL(simple_strtoull);
71 * simple_strtoul - convert a string to an unsigned long
72 * @cp: The start of the string
73 * @endp: A pointer to the end of the parsed string will be placed here
74 * @base: The number base to use
76 * This function is obsolete. Please use kstrtoul instead.
78 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
80 return simple_strtoull(cp, endp, base);
82 EXPORT_SYMBOL(simple_strtoul);
85 * simple_strtol - convert a string to a signed long
86 * @cp: The start of the string
87 * @endp: A pointer to the end of the parsed string will be placed here
88 * @base: The number base to use
90 * This function is obsolete. Please use kstrtol instead.
92 long simple_strtol(const char *cp, char **endp, unsigned int base)
95 return -simple_strtoul(cp + 1, endp, base);
97 return simple_strtoul(cp, endp, base);
99 EXPORT_SYMBOL(simple_strtol);
102 * simple_strtoll - convert a string to a signed long long
103 * @cp: The start of the string
104 * @endp: A pointer to the end of the parsed string will be placed here
105 * @base: The number base to use
107 * This function is obsolete. Please use kstrtoll instead.
109 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
112 return -simple_strtoull(cp + 1, endp, base);
114 return simple_strtoull(cp, endp, base);
116 EXPORT_SYMBOL(simple_strtoll);
118 static noinline_for_stack
119 int skip_atoi(const char **s)
124 i = i*10 + *((*s)++) - '0';
125 } while (isdigit(**s));
131 * Decimal conversion is by far the most typical, and is used for
132 * /proc and /sys data. This directly impacts e.g. top performance
133 * with many processes running. We optimize it for speed by emitting
134 * two characters at a time, using a 200 byte lookup table. This
135 * roughly halves the number of multiplications compared to computing
136 * the digits one at a time. Implementation strongly inspired by the
137 * previous version, which in turn used ideas described at
138 * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
139 * from the author, Douglas W. Jones).
141 * It turns out there is precisely one 26 bit fixed-point
142 * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
143 * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
144 * range happens to be somewhat larger (x <= 1073741898), but that's
145 * irrelevant for our purpose.
147 * For dividing a number in the range [10^4, 10^6-1] by 100, we still
148 * need a 32x32->64 bit multiply, so we simply use the same constant.
150 * For dividing a number in the range [100, 10^4-1] by 100, there are
151 * several options. The simplest is (x * 0x147b) >> 19, which is valid
152 * for all x <= 43698.
155 static const u16 decpair[100] = {
156 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
157 _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
158 _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
159 _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
160 _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
161 _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
162 _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
163 _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
164 _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
165 _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
166 _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
171 * This will print a single '0' even if r == 0, since we would
172 * immediately jump to out_r where two 0s would be written but only
173 * one of them accounted for in buf. This is needed by ip4_string
174 * below. All other callers pass a non-zero value of r.
176 static noinline_for_stack
177 char *put_dec_trunc8(char *buf, unsigned r)
185 /* 100 <= r < 10^8 */
186 q = (r * (u64)0x28f5c29) >> 32;
187 *((u16 *)buf) = decpair[r - 100*q];
194 /* 100 <= q < 10^6 */
195 r = (q * (u64)0x28f5c29) >> 32;
196 *((u16 *)buf) = decpair[q - 100*r];
203 /* 100 <= r < 10^4 */
204 q = (r * 0x147b) >> 19;
205 *((u16 *)buf) = decpair[r - 100*q];
212 *((u16 *)buf) = decpair[r];
213 buf += r < 10 ? 1 : 2;
217 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
218 static noinline_for_stack
219 char *put_dec_full8(char *buf, unsigned r)
224 q = (r * (u64)0x28f5c29) >> 32;
225 *((u16 *)buf) = decpair[r - 100*q];
229 r = (q * (u64)0x28f5c29) >> 32;
230 *((u16 *)buf) = decpair[q - 100*r];
234 q = (r * 0x147b) >> 19;
235 *((u16 *)buf) = decpair[r - 100*q];
239 *((u16 *)buf) = decpair[q];
244 static noinline_for_stack
245 char *put_dec(char *buf, unsigned long long n)
247 if (n >= 100*1000*1000)
248 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
249 /* 1 <= n <= 1.6e11 */
250 if (n >= 100*1000*1000)
251 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
253 return put_dec_trunc8(buf, n);
256 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
259 put_dec_full4(char *buf, unsigned r)
264 q = (r * 0x147b) >> 19;
265 *((u16 *)buf) = decpair[r - 100*q];
268 *((u16 *)buf) = decpair[q];
272 * Call put_dec_full4 on x % 10000, return x / 10000.
273 * The approximation x/10000 == (x * 0x346DC5D7) >> 43
274 * holds for all x < 1,128,869,999. The largest value this
275 * helper will ever be asked to convert is 1,125,520,955.
276 * (second call in the put_dec code, assuming n is all-ones).
278 static noinline_for_stack
279 unsigned put_dec_helper4(char *buf, unsigned x)
281 uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
283 put_dec_full4(buf, x - q * 10000);
287 /* Based on code by Douglas W. Jones found at
288 * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
289 * (with permission from the author).
290 * Performs no 64-bit division and hence should be fast on 32-bit machines.
293 char *put_dec(char *buf, unsigned long long n)
295 uint32_t d3, d2, d1, q, h;
297 if (n < 100*1000*1000)
298 return put_dec_trunc8(buf, n);
300 d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
303 d3 = (h >> 16); /* implicit "& 0xffff" */
305 /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
306 = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
307 q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
308 q = put_dec_helper4(buf, q);
310 q += 7671 * d3 + 9496 * d2 + 6 * d1;
311 q = put_dec_helper4(buf+4, q);
313 q += 4749 * d3 + 42 * d2;
314 q = put_dec_helper4(buf+8, q);
319 buf = put_dec_trunc8(buf, q);
320 else while (buf[-1] == '0')
329 * Convert passed number to decimal string.
330 * Returns the length of string. On buffer overflow, returns 0.
332 * If speed is not important, use snprintf(). It's easy to read the code.
334 int num_to_str(char *buf, int size, unsigned long long num)
336 /* put_dec requires 2-byte alignment of the buffer. */
337 char tmp[sizeof(num) * 3] __aligned(2);
340 /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
345 len = put_dec(tmp, num) - tmp;
350 for (idx = 0; idx < len; ++idx)
351 buf[idx] = tmp[len - idx - 1];
355 #define SIGN 1 /* unsigned/signed, must be 1 */
356 #define LEFT 2 /* left justified */
357 #define PLUS 4 /* show plus */
358 #define SPACE 8 /* space if plus */
359 #define ZEROPAD 16 /* pad with zero, must be 16 == '0' - ' ' */
360 #define SMALL 32 /* use lowercase in hex (must be 32 == 0x20) */
361 #define SPECIAL 64 /* prefix hex with "0x", octal with "0" */
364 FORMAT_TYPE_NONE, /* Just a string part */
366 FORMAT_TYPE_PRECISION,
370 FORMAT_TYPE_PERCENT_CHAR,
372 FORMAT_TYPE_LONG_LONG,
386 u8 type; /* format_type enum */
387 u8 flags; /* flags to number() */
388 u8 base; /* number base, 8, 10 or 16 only */
389 u8 qualifier; /* number qualifier, one of 'hHlLtzZ' */
390 s16 field_width; /* width of output field */
391 s16 precision; /* # of digits/chars */
394 static noinline_for_stack
395 char *number(char *buf, char *end, unsigned long long num,
396 struct printf_spec spec)
398 /* put_dec requires 2-byte alignment of the buffer. */
399 char tmp[3 * sizeof(num)] __aligned(2);
402 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
404 bool is_zero = num == 0LL;
406 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
407 * produces same digits or (maybe lowercased) letters */
408 locase = (spec.flags & SMALL);
409 if (spec.flags & LEFT)
410 spec.flags &= ~ZEROPAD;
412 if (spec.flags & SIGN) {
413 if ((signed long long)num < 0) {
415 num = -(signed long long)num;
417 } else if (spec.flags & PLUS) {
420 } else if (spec.flags & SPACE) {
427 spec.field_width -= 2;
432 /* generate full string in tmp[], in reverse order */
435 tmp[i++] = hex_asc_upper[num] | locase;
436 else if (spec.base != 10) { /* 8 or 16 */
437 int mask = spec.base - 1;
443 tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
446 } else { /* base 10 */
447 i = put_dec(tmp, num) - tmp;
450 /* printing 100 using %2d gives "100", not "00" */
451 if (i > spec.precision)
453 /* leading space padding */
454 spec.field_width -= spec.precision;
455 if (!(spec.flags & (ZEROPAD | LEFT))) {
456 while (--spec.field_width >= 0) {
468 /* "0x" / "0" prefix */
470 if (spec.base == 16 || !is_zero) {
475 if (spec.base == 16) {
477 *buf = ('X' | locase);
481 /* zero or space padding */
482 if (!(spec.flags & LEFT)) {
483 char c = ' ' + (spec.flags & ZEROPAD);
484 BUILD_BUG_ON(' ' + ZEROPAD != '0');
485 while (--spec.field_width >= 0) {
491 /* hmm even more zero padding? */
492 while (i <= --spec.precision) {
497 /* actual digits of result */
503 /* trailing space padding */
504 while (--spec.field_width >= 0) {
513 static noinline_for_stack
514 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
518 if ((unsigned long)s < PAGE_SIZE)
521 len = strnlen(s, spec.precision);
523 if (!(spec.flags & LEFT)) {
524 while (len < spec.field_width--) {
530 for (i = 0; i < len; ++i) {
535 while (len < spec.field_width--) {
544 static void move_right(char *buf, char *end, unsigned len, unsigned spaces)
547 if (buf >= end) /* nowhere to put anything */
550 if (size <= spaces) {
551 memset(buf, ' ', size);
555 if (len > size - spaces)
557 memmove(buf + spaces, buf, len);
559 memset(buf, ' ', spaces);
563 * Handle field width padding for a string.
564 * @buf: current buffer position
565 * @n: length of string
566 * @end: end of output buffer
567 * @spec: for field width and flags
568 * Returns: new buffer position after padding.
570 static noinline_for_stack
571 char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
575 if (likely(n >= spec.field_width))
577 /* we want to pad the sucker */
578 spaces = spec.field_width - n;
579 if (!(spec.flags & LEFT)) {
580 move_right(buf - n, end, n, spaces);
591 static noinline_for_stack
592 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
595 const char *array[4], *s;
596 const struct dentry *p;
601 case '2': case '3': case '4':
602 depth = fmt[1] - '0';
609 for (i = 0; i < depth; i++, d = p) {
610 p = ACCESS_ONCE(d->d_parent);
611 array[i] = ACCESS_ONCE(d->d_name.name);
620 for (n = 0; n != spec.precision; n++, buf++) {
632 return widen_string(buf, n, end, spec);
636 static noinline_for_stack
637 char *bdev_name(char *buf, char *end, struct block_device *bdev,
638 struct printf_spec spec, const char *fmt)
640 struct gendisk *hd = bdev->bd_disk;
642 buf = string(buf, end, hd->disk_name, spec);
643 if (bdev->bd_part->partno) {
644 if (isdigit(hd->disk_name[strlen(hd->disk_name)-1])) {
649 buf = number(buf, end, bdev->bd_part->partno, spec);
655 static noinline_for_stack
656 char *symbol_string(char *buf, char *end, void *ptr,
657 struct printf_spec spec, const char *fmt)
660 #ifdef CONFIG_KALLSYMS
661 char sym[KSYM_SYMBOL_LEN];
665 ptr = __builtin_extract_return_addr(ptr);
666 value = (unsigned long)ptr;
668 #ifdef CONFIG_KALLSYMS
670 sprint_backtrace(sym, value);
671 else if (*fmt != 'f' && *fmt != 's')
672 sprint_symbol(sym, value);
674 sprint_symbol_no_offset(sym, value);
676 return string(buf, end, sym, spec);
678 spec.field_width = 2 * sizeof(void *);
679 spec.flags |= SPECIAL | SMALL | ZEROPAD;
682 return number(buf, end, value, spec);
686 static noinline_for_stack
687 char *resource_string(char *buf, char *end, struct resource *res,
688 struct printf_spec spec, const char *fmt)
690 #ifndef IO_RSRC_PRINTK_SIZE
691 #define IO_RSRC_PRINTK_SIZE 6
694 #ifndef MEM_RSRC_PRINTK_SIZE
695 #define MEM_RSRC_PRINTK_SIZE 10
697 static const struct printf_spec io_spec = {
699 .field_width = IO_RSRC_PRINTK_SIZE,
701 .flags = SPECIAL | SMALL | ZEROPAD,
703 static const struct printf_spec mem_spec = {
705 .field_width = MEM_RSRC_PRINTK_SIZE,
707 .flags = SPECIAL | SMALL | ZEROPAD,
709 static const struct printf_spec bus_spec = {
713 .flags = SMALL | ZEROPAD,
715 static const struct printf_spec dec_spec = {
720 static const struct printf_spec str_spec = {
725 static const struct printf_spec flag_spec = {
728 .flags = SPECIAL | SMALL,
731 /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
732 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
733 #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
734 #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
735 #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
736 #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
737 char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
738 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
740 char *p = sym, *pend = sym + sizeof(sym);
741 int decode = (fmt[0] == 'R') ? 1 : 0;
742 const struct printf_spec *specp;
745 if (res->flags & IORESOURCE_IO) {
746 p = string(p, pend, "io ", str_spec);
748 } else if (res->flags & IORESOURCE_MEM) {
749 p = string(p, pend, "mem ", str_spec);
751 } else if (res->flags & IORESOURCE_IRQ) {
752 p = string(p, pend, "irq ", str_spec);
754 } else if (res->flags & IORESOURCE_DMA) {
755 p = string(p, pend, "dma ", str_spec);
757 } else if (res->flags & IORESOURCE_BUS) {
758 p = string(p, pend, "bus ", str_spec);
761 p = string(p, pend, "??? ", str_spec);
765 if (decode && res->flags & IORESOURCE_UNSET) {
766 p = string(p, pend, "size ", str_spec);
767 p = number(p, pend, resource_size(res), *specp);
769 p = number(p, pend, res->start, *specp);
770 if (res->start != res->end) {
772 p = number(p, pend, res->end, *specp);
776 if (res->flags & IORESOURCE_MEM_64)
777 p = string(p, pend, " 64bit", str_spec);
778 if (res->flags & IORESOURCE_PREFETCH)
779 p = string(p, pend, " pref", str_spec);
780 if (res->flags & IORESOURCE_WINDOW)
781 p = string(p, pend, " window", str_spec);
782 if (res->flags & IORESOURCE_DISABLED)
783 p = string(p, pend, " disabled", str_spec);
785 p = string(p, pend, " flags ", str_spec);
786 p = number(p, pend, res->flags, flag_spec);
791 return string(buf, end, sym, spec);
794 static noinline_for_stack
795 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
798 int i, len = 1; /* if we pass '%ph[CDN]', field width remains
799 negative value, fallback to the default */
802 if (spec.field_width == 0)
803 /* nothing to print */
806 if (ZERO_OR_NULL_PTR(addr))
808 return string(buf, end, NULL, spec);
825 if (spec.field_width > 0)
826 len = min_t(int, spec.field_width, 64);
828 for (i = 0; i < len; ++i) {
830 *buf = hex_asc_hi(addr[i]);
833 *buf = hex_asc_lo(addr[i]);
836 if (separator && i != len - 1) {
846 static noinline_for_stack
847 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
848 struct printf_spec spec, const char *fmt)
850 const int CHUNKSZ = 32;
851 int nr_bits = max_t(int, spec.field_width, 0);
855 /* reused to print numbers */
856 spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
858 chunksz = nr_bits & (CHUNKSZ - 1);
862 i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
863 for (; i >= 0; i -= CHUNKSZ) {
867 chunkmask = ((1ULL << chunksz) - 1);
868 word = i / BITS_PER_LONG;
869 bit = i % BITS_PER_LONG;
870 val = (bitmap[word] >> bit) & chunkmask;
879 spec.field_width = DIV_ROUND_UP(chunksz, 4);
880 buf = number(buf, end, val, spec);
887 static noinline_for_stack
888 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
889 struct printf_spec spec, const char *fmt)
891 int nr_bits = max_t(int, spec.field_width, 0);
892 /* current bit is 'cur', most recently seen range is [rbot, rtop] */
896 /* reused to print numbers */
897 spec = (struct printf_spec){ .base = 10 };
899 rbot = cur = find_first_bit(bitmap, nr_bits);
900 while (cur < nr_bits) {
902 cur = find_next_bit(bitmap, nr_bits, cur + 1);
903 if (cur < nr_bits && cur <= rtop + 1)
913 buf = number(buf, end, rbot, spec);
919 buf = number(buf, end, rtop, spec);
927 static noinline_for_stack
928 char *mac_address_string(char *buf, char *end, u8 *addr,
929 struct printf_spec spec, const char *fmt)
931 char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
935 bool reversed = false;
951 for (i = 0; i < 6; i++) {
953 p = hex_byte_pack(p, addr[5 - i]);
955 p = hex_byte_pack(p, addr[i]);
957 if (fmt[0] == 'M' && i != 5)
962 return string(buf, end, mac_addr, spec);
965 static noinline_for_stack
966 char *ip4_string(char *p, const u8 *addr, const char *fmt)
969 bool leading_zeros = (fmt[0] == 'i');
994 for (i = 0; i < 4; i++) {
995 char temp[4] __aligned(2); /* hold each IP quad in reverse order */
996 int digits = put_dec_trunc8(temp, addr[index]) - temp;
1003 /* reverse the digits in the quad */
1005 *p++ = temp[digits];
1015 static noinline_for_stack
1016 char *ip6_compressed_string(char *p, const char *addr)
1019 unsigned char zerolength[8];
1024 bool needcolon = false;
1026 struct in6_addr in6;
1028 memcpy(&in6, addr, sizeof(struct in6_addr));
1030 useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
1032 memset(zerolength, 0, sizeof(zerolength));
1039 /* find position of longest 0 run */
1040 for (i = 0; i < range; i++) {
1041 for (j = i; j < range; j++) {
1042 if (in6.s6_addr16[j] != 0)
1047 for (i = 0; i < range; i++) {
1048 if (zerolength[i] > longest) {
1049 longest = zerolength[i];
1053 if (longest == 1) /* don't compress a single 0 */
1057 for (i = 0; i < range; i++) {
1058 if (i == colonpos) {
1059 if (needcolon || i == 0)
1070 /* hex u16 without leading 0s */
1071 word = ntohs(in6.s6_addr16[i]);
1076 p = hex_byte_pack(p, hi);
1078 *p++ = hex_asc_lo(hi);
1079 p = hex_byte_pack(p, lo);
1082 p = hex_byte_pack(p, lo);
1084 *p++ = hex_asc_lo(lo);
1091 p = ip4_string(p, &in6.s6_addr[12], "I4");
1098 static noinline_for_stack
1099 char *ip6_string(char *p, const char *addr, const char *fmt)
1103 for (i = 0; i < 8; i++) {
1104 p = hex_byte_pack(p, *addr++);
1105 p = hex_byte_pack(p, *addr++);
1106 if (fmt[0] == 'I' && i != 7)
1114 static noinline_for_stack
1115 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1116 struct printf_spec spec, const char *fmt)
1118 char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1120 if (fmt[0] == 'I' && fmt[2] == 'c')
1121 ip6_compressed_string(ip6_addr, addr);
1123 ip6_string(ip6_addr, addr, fmt);
1125 return string(buf, end, ip6_addr, spec);
1128 static noinline_for_stack
1129 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1130 struct printf_spec spec, const char *fmt)
1132 char ip4_addr[sizeof("255.255.255.255")];
1134 ip4_string(ip4_addr, addr, fmt);
1136 return string(buf, end, ip4_addr, spec);
1139 static noinline_for_stack
1140 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1141 struct printf_spec spec, const char *fmt)
1143 bool have_p = false, have_s = false, have_f = false, have_c = false;
1144 char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1145 sizeof(":12345") + sizeof("/123456789") +
1146 sizeof("%1234567890")];
1147 char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1148 const u8 *addr = (const u8 *) &sa->sin6_addr;
1149 char fmt6[2] = { fmt[0], '6' };
1153 while (isalpha(*++fmt)) {
1170 if (have_p || have_s || have_f) {
1175 if (fmt6[0] == 'I' && have_c)
1176 p = ip6_compressed_string(ip6_addr + off, addr);
1178 p = ip6_string(ip6_addr + off, addr, fmt6);
1180 if (have_p || have_s || have_f)
1185 p = number(p, pend, ntohs(sa->sin6_port), spec);
1189 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1190 IPV6_FLOWINFO_MASK), spec);
1194 p = number(p, pend, sa->sin6_scope_id, spec);
1198 return string(buf, end, ip6_addr, spec);
1201 static noinline_for_stack
1202 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1203 struct printf_spec spec, const char *fmt)
1205 bool have_p = false;
1206 char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1207 char *pend = ip4_addr + sizeof(ip4_addr);
1208 const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1209 char fmt4[3] = { fmt[0], '4', 0 };
1212 while (isalpha(*++fmt)) {
1226 p = ip4_string(ip4_addr, addr, fmt4);
1229 p = number(p, pend, ntohs(sa->sin_port), spec);
1233 return string(buf, end, ip4_addr, spec);
1236 static noinline_for_stack
1237 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1242 unsigned int flags = 0;
1245 if (spec.field_width == 0)
1246 return buf; /* nothing to print */
1248 if (ZERO_OR_NULL_PTR(addr))
1249 return string(buf, end, NULL, spec); /* NULL pointer */
1253 switch (fmt[count++]) {
1255 flags |= ESCAPE_ANY;
1258 flags |= ESCAPE_SPECIAL;
1261 flags |= ESCAPE_HEX;
1264 flags |= ESCAPE_NULL;
1267 flags |= ESCAPE_OCTAL;
1273 flags |= ESCAPE_SPACE;
1282 flags = ESCAPE_ANY_NP;
1284 len = spec.field_width < 0 ? 1 : spec.field_width;
1287 * string_escape_mem() writes as many characters as it can to
1288 * the given buffer, and returns the total size of the output
1289 * had the buffer been big enough.
1291 buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1296 static noinline_for_stack
1297 char *uuid_string(char *buf, char *end, const u8 *addr,
1298 struct printf_spec spec, const char *fmt)
1300 char uuid[sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")];
1303 static const u8 be[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
1304 static const u8 le[16] = {3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15};
1305 const u8 *index = be;
1310 uc = true; /* fall-through */
1319 for (i = 0; i < 16; i++) {
1320 p = hex_byte_pack(p, addr[index[i]]);
1340 return string(buf, end, uuid, spec);
1344 char *netdev_feature_string(char *buf, char *end, const u8 *addr,
1345 struct printf_spec spec)
1347 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1348 if (spec.field_width == -1)
1349 spec.field_width = 2 + 2 * sizeof(netdev_features_t);
1352 return number(buf, end, *(const netdev_features_t *)addr, spec);
1355 static noinline_for_stack
1356 char *address_val(char *buf, char *end, const void *addr,
1357 struct printf_spec spec, const char *fmt)
1359 unsigned long long num;
1361 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1366 num = *(const dma_addr_t *)addr;
1367 spec.field_width = sizeof(dma_addr_t) * 2 + 2;
1371 num = *(const phys_addr_t *)addr;
1372 spec.field_width = sizeof(phys_addr_t) * 2 + 2;
1376 return number(buf, end, num, spec);
1379 static noinline_for_stack
1380 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1383 if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1384 return string(buf, end, NULL, spec);
1388 return number(buf, end, clk_get_rate(clk), spec);
1392 #ifdef CONFIG_COMMON_CLK
1393 return string(buf, end, __clk_get_name(clk), spec);
1396 spec.field_width = sizeof(unsigned long) * 2 + 2;
1397 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1398 return number(buf, end, (unsigned long)clk, spec);
1403 int kptr_restrict __read_mostly;
1406 * Show a '%p' thing. A kernel extension is that the '%p' is followed
1407 * by an extra set of alphanumeric characters that are extended format
1410 * Right now we handle:
1412 * - 'F' For symbolic function descriptor pointers with offset
1413 * - 'f' For simple symbolic function names without offset
1414 * - 'S' For symbolic direct pointers with offset
1415 * - 's' For symbolic direct pointers without offset
1416 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1417 * - 'B' For backtraced symbolic direct pointers with offset
1418 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1419 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1420 * - 'b[l]' For a bitmap, the number of bits is determined by the field
1421 * width which must be explicitly specified either as part of the
1422 * format string '%32b[l]' or through '%*b[l]', [l] selects
1423 * range-list format instead of hex format
1424 * - 'M' For a 6-byte MAC address, it prints the address in the
1425 * usual colon-separated hex notation
1426 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1427 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1428 * with a dash-separated hex notation
1429 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1430 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1431 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1432 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
1434 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1435 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1436 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1437 * IPv6 omits the colons (01020304...0f)
1438 * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1440 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1441 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1442 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1443 * - 'I[6S]c' for IPv6 addresses printed as specified by
1444 * http://tools.ietf.org/html/rfc5952
1445 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1446 * of the following flags (see string_escape_mem() for the
1449 * c - ESCAPE_SPECIAL
1455 * By default ESCAPE_ANY_NP is used.
1456 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1457 * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1458 * Options for %pU are:
1459 * b big endian lower case hex (default)
1460 * B big endian UPPER case hex
1461 * l little endian lower case hex
1462 * L little endian UPPER case hex
1463 * big endian output byte order is:
1464 * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1465 * little endian output byte order is:
1466 * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1467 * - 'V' For a struct va_format which contains a format string * and va_list *,
1468 * call vsnprintf(->format, *->va_list).
1469 * Implements a "recursive vsnprintf".
1470 * Do not use this feature without some mechanism to verify the
1471 * correctness of the format string and va_list arguments.
1472 * - 'K' For a kernel pointer that should be hidden from unprivileged users
1473 * - 'NF' For a netdev_features_t
1474 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1475 * a certain separator (' ' by default):
1479 * The maximum supported length is 64 bytes of the input. Consider
1480 * to use print_hex_dump() for the larger input.
1481 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1482 * (default assumed to be phys_addr_t, passed by reference)
1483 * - 'd[234]' For a dentry name (optionally 2-4 last components)
1484 * - 'D[234]' Same as 'd' but for a struct file
1485 * - 'g' For block_device name (gendisk + partition number)
1486 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1487 * (legacy clock framework) of the clock
1488 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1489 * (legacy clock framework) of the clock
1490 * - 'Cr' For a clock, it prints the current rate of the clock
1492 * ** Please update also Documentation/printk-formats.txt when making changes **
1494 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1495 * function pointers are really function descriptors, which contain a
1496 * pointer to the real address.
1498 static noinline_for_stack
1499 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1500 struct printf_spec spec)
1502 const int default_width = 2 * sizeof(void *);
1504 if (!ptr && *fmt != 'K') {
1506 * Print (null) with the same width as a pointer so it makes
1507 * tabular output look nice.
1509 if (spec.field_width == -1)
1510 spec.field_width = default_width;
1511 return string(buf, end, "(null)", spec);
1517 ptr = dereference_function_descriptor(ptr);
1522 return symbol_string(buf, end, ptr, spec, fmt);
1525 return resource_string(buf, end, ptr, spec, fmt);
1527 return hex_string(buf, end, ptr, spec, fmt);
1531 return bitmap_list_string(buf, end, ptr, spec, fmt);
1533 return bitmap_string(buf, end, ptr, spec, fmt);
1535 case 'M': /* Colon separated: 00:01:02:03:04:05 */
1536 case 'm': /* Contiguous: 000102030405 */
1538 /* [mM]R (Reverse order; Bluetooth) */
1539 return mac_address_string(buf, end, ptr, spec, fmt);
1540 case 'I': /* Formatted IP supported
1542 * 6: 0001:0203:...:0708
1543 * 6c: 1::708 or 1::1.2.3.4
1545 case 'i': /* Contiguous:
1546 * 4: 001.002.003.004
1551 return ip6_addr_string(buf, end, ptr, spec, fmt);
1553 return ip4_addr_string(buf, end, ptr, spec, fmt);
1556 struct sockaddr raw;
1557 struct sockaddr_in v4;
1558 struct sockaddr_in6 v6;
1561 switch (sa->raw.sa_family) {
1563 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1565 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1567 return string(buf, end, "(invalid address)", spec);
1572 return escaped_string(buf, end, ptr, spec, fmt);
1574 return uuid_string(buf, end, ptr, spec, fmt);
1579 va_copy(va, *((struct va_format *)ptr)->va);
1580 buf += vsnprintf(buf, end > buf ? end - buf : 0,
1581 ((struct va_format *)ptr)->fmt, va);
1587 * %pK cannot be used in IRQ context because its test
1588 * for CAP_SYSLOG would be meaningless.
1590 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
1592 if (spec.field_width == -1)
1593 spec.field_width = default_width;
1594 return string(buf, end, "pK-error", spec);
1597 switch (kptr_restrict) {
1599 /* Always print %pK values */
1603 * Only print the real pointer value if the current
1604 * process has CAP_SYSLOG and is running with the
1605 * same credentials it started with. This is because
1606 * access to files is checked at open() time, but %pK
1607 * checks permission at read() time. We don't want to
1608 * leak pointer values if a binary opens a file using
1609 * %pK and then elevates privileges before reading it.
1611 const struct cred *cred = current_cred();
1613 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
1614 !uid_eq(cred->euid, cred->uid) ||
1615 !gid_eq(cred->egid, cred->gid))
1621 /* Always print 0's for %pK */
1630 return netdev_feature_string(buf, end, ptr, spec);
1634 return address_val(buf, end, ptr, spec, fmt);
1636 return dentry_name(buf, end, ptr, spec, fmt);
1638 return clock(buf, end, ptr, spec, fmt);
1640 return dentry_name(buf, end,
1641 ((const struct file *)ptr)->f_path.dentry,
1645 return bdev_name(buf, end, ptr, spec, fmt);
1649 spec.flags |= SMALL;
1650 if (spec.field_width == -1) {
1651 spec.field_width = default_width;
1652 spec.flags |= ZEROPAD;
1656 return number(buf, end, (unsigned long) ptr, spec);
1660 * Helper function to decode printf style format.
1661 * Each call decode a token from the format and return the
1662 * number of characters read (or likely the delta where it wants
1663 * to go on the next call).
1664 * The decoded token is returned through the parameters
1666 * 'h', 'l', or 'L' for integer fields
1667 * 'z' support added 23/7/1999 S.H.
1668 * 'z' changed to 'Z' --davidm 1/25/99
1669 * 't' added for ptrdiff_t
1671 * @fmt: the format string
1672 * @type of the token returned
1673 * @flags: various flags such as +, -, # tokens..
1674 * @field_width: overwritten width
1675 * @base: base of the number (octal, hex, ...)
1676 * @precision: precision of a number
1677 * @qualifier: qualifier of a number (long, size_t, ...)
1679 static noinline_for_stack
1680 int format_decode(const char *fmt, struct printf_spec *spec)
1682 const char *start = fmt;
1684 /* we finished early by reading the field width */
1685 if (spec->type == FORMAT_TYPE_WIDTH) {
1686 if (spec->field_width < 0) {
1687 spec->field_width = -spec->field_width;
1688 spec->flags |= LEFT;
1690 spec->type = FORMAT_TYPE_NONE;
1694 /* we finished early by reading the precision */
1695 if (spec->type == FORMAT_TYPE_PRECISION) {
1696 if (spec->precision < 0)
1697 spec->precision = 0;
1699 spec->type = FORMAT_TYPE_NONE;
1704 spec->type = FORMAT_TYPE_NONE;
1706 for (; *fmt ; ++fmt) {
1711 /* Return the current non-format string */
1712 if (fmt != start || !*fmt)
1718 while (1) { /* this also skips first '%' */
1724 case '-': spec->flags |= LEFT; break;
1725 case '+': spec->flags |= PLUS; break;
1726 case ' ': spec->flags |= SPACE; break;
1727 case '#': spec->flags |= SPECIAL; break;
1728 case '0': spec->flags |= ZEROPAD; break;
1729 default: found = false;
1736 /* get field width */
1737 spec->field_width = -1;
1740 spec->field_width = skip_atoi(&fmt);
1741 else if (*fmt == '*') {
1742 /* it's the next argument */
1743 spec->type = FORMAT_TYPE_WIDTH;
1744 return ++fmt - start;
1748 /* get the precision */
1749 spec->precision = -1;
1752 if (isdigit(*fmt)) {
1753 spec->precision = skip_atoi(&fmt);
1754 if (spec->precision < 0)
1755 spec->precision = 0;
1756 } else if (*fmt == '*') {
1757 /* it's the next argument */
1758 spec->type = FORMAT_TYPE_PRECISION;
1759 return ++fmt - start;
1764 /* get the conversion qualifier */
1765 spec->qualifier = -1;
1766 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1767 _tolower(*fmt) == 'z' || *fmt == 't') {
1768 spec->qualifier = *fmt++;
1769 if (unlikely(spec->qualifier == *fmt)) {
1770 if (spec->qualifier == 'l') {
1771 spec->qualifier = 'L';
1773 } else if (spec->qualifier == 'h') {
1774 spec->qualifier = 'H';
1784 spec->type = FORMAT_TYPE_CHAR;
1785 return ++fmt - start;
1788 spec->type = FORMAT_TYPE_STR;
1789 return ++fmt - start;
1792 spec->type = FORMAT_TYPE_PTR;
1793 return ++fmt - start;
1796 spec->type = FORMAT_TYPE_PERCENT_CHAR;
1797 return ++fmt - start;
1799 /* integer number formats - set up the flags and "break" */
1805 spec->flags |= SMALL;
1813 spec->flags |= SIGN;
1819 * Since %n poses a greater security risk than
1820 * utility, treat it as any other invalid or
1821 * unsupported format specifier.
1826 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
1827 spec->type = FORMAT_TYPE_INVALID;
1831 if (spec->qualifier == 'L')
1832 spec->type = FORMAT_TYPE_LONG_LONG;
1833 else if (spec->qualifier == 'l') {
1834 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
1835 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
1836 } else if (_tolower(spec->qualifier) == 'z') {
1837 spec->type = FORMAT_TYPE_SIZE_T;
1838 } else if (spec->qualifier == 't') {
1839 spec->type = FORMAT_TYPE_PTRDIFF;
1840 } else if (spec->qualifier == 'H') {
1841 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
1842 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
1843 } else if (spec->qualifier == 'h') {
1844 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
1845 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
1847 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
1848 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
1851 return ++fmt - start;
1855 * vsnprintf - Format a string and place it in a buffer
1856 * @buf: The buffer to place the result into
1857 * @size: The size of the buffer, including the trailing null space
1858 * @fmt: The format string to use
1859 * @args: Arguments for the format string
1861 * This function generally follows C99 vsnprintf, but has some
1862 * extensions and a few limitations:
1865 * %p* is handled by pointer()
1867 * See pointer() or Documentation/printk-formats.txt for more
1868 * extensive description.
1870 * ** Please update the documentation in both places when making changes **
1872 * The return value is the number of characters which would
1873 * be generated for the given input, excluding the trailing
1874 * '\0', as per ISO C99. If you want to have the exact
1875 * number of characters written into @buf as return value
1876 * (not including the trailing '\0'), use vscnprintf(). If the
1877 * return is greater than or equal to @size, the resulting
1878 * string is truncated.
1880 * If you're not already dealing with a va_list consider using snprintf().
1882 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1884 unsigned long long num;
1886 struct printf_spec spec = {0};
1888 /* Reject out-of-range values early. Large positive sizes are
1889 used for unknown buffer sizes. */
1890 if (WARN_ON_ONCE(size > INT_MAX))
1896 /* Make sure end is always >= buf */
1903 const char *old_fmt = fmt;
1904 int read = format_decode(fmt, &spec);
1908 switch (spec.type) {
1909 case FORMAT_TYPE_NONE: {
1912 if (copy > end - str)
1914 memcpy(str, old_fmt, copy);
1920 case FORMAT_TYPE_WIDTH:
1921 spec.field_width = va_arg(args, int);
1924 case FORMAT_TYPE_PRECISION:
1925 spec.precision = va_arg(args, int);
1928 case FORMAT_TYPE_CHAR: {
1931 if (!(spec.flags & LEFT)) {
1932 while (--spec.field_width > 0) {
1939 c = (unsigned char) va_arg(args, int);
1943 while (--spec.field_width > 0) {
1951 case FORMAT_TYPE_STR:
1952 str = string(str, end, va_arg(args, char *), spec);
1955 case FORMAT_TYPE_PTR:
1956 str = pointer(fmt, str, end, va_arg(args, void *),
1958 while (isalnum(*fmt))
1962 case FORMAT_TYPE_PERCENT_CHAR:
1968 case FORMAT_TYPE_INVALID:
1970 * Presumably the arguments passed gcc's type
1971 * checking, but there is no safe or sane way
1972 * for us to continue parsing the format and
1973 * fetching from the va_list; the remaining
1974 * specifiers and arguments would be out of
1980 switch (spec.type) {
1981 case FORMAT_TYPE_LONG_LONG:
1982 num = va_arg(args, long long);
1984 case FORMAT_TYPE_ULONG:
1985 num = va_arg(args, unsigned long);
1987 case FORMAT_TYPE_LONG:
1988 num = va_arg(args, long);
1990 case FORMAT_TYPE_SIZE_T:
1991 if (spec.flags & SIGN)
1992 num = va_arg(args, ssize_t);
1994 num = va_arg(args, size_t);
1996 case FORMAT_TYPE_PTRDIFF:
1997 num = va_arg(args, ptrdiff_t);
1999 case FORMAT_TYPE_UBYTE:
2000 num = (unsigned char) va_arg(args, int);
2002 case FORMAT_TYPE_BYTE:
2003 num = (signed char) va_arg(args, int);
2005 case FORMAT_TYPE_USHORT:
2006 num = (unsigned short) va_arg(args, int);
2008 case FORMAT_TYPE_SHORT:
2009 num = (short) va_arg(args, int);
2011 case FORMAT_TYPE_INT:
2012 num = (int) va_arg(args, int);
2015 num = va_arg(args, unsigned int);
2018 str = number(str, end, num, spec);
2030 /* the trailing null byte doesn't count towards the total */
2034 EXPORT_SYMBOL(vsnprintf);
2037 * vscnprintf - Format a string and place it in a buffer
2038 * @buf: The buffer to place the result into
2039 * @size: The size of the buffer, including the trailing null space
2040 * @fmt: The format string to use
2041 * @args: Arguments for the format string
2043 * The return value is the number of characters which have been written into
2044 * the @buf not including the trailing '\0'. If @size is == 0 the function
2047 * If you're not already dealing with a va_list consider using scnprintf().
2049 * See the vsnprintf() documentation for format string extensions over C99.
2051 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2055 i = vsnprintf(buf, size, fmt, args);
2057 if (likely(i < size))
2063 EXPORT_SYMBOL(vscnprintf);
2066 * snprintf - Format a string and place it in a buffer
2067 * @buf: The buffer to place the result into
2068 * @size: The size of the buffer, including the trailing null space
2069 * @fmt: The format string to use
2070 * @...: Arguments for the format string
2072 * The return value is the number of characters which would be
2073 * generated for the given input, excluding the trailing null,
2074 * as per ISO C99. If the return is greater than or equal to
2075 * @size, the resulting string is truncated.
2077 * See the vsnprintf() documentation for format string extensions over C99.
2079 int snprintf(char *buf, size_t size, const char *fmt, ...)
2084 va_start(args, fmt);
2085 i = vsnprintf(buf, size, fmt, args);
2090 EXPORT_SYMBOL(snprintf);
2093 * scnprintf - Format a string and place it in a buffer
2094 * @buf: The buffer to place the result into
2095 * @size: The size of the buffer, including the trailing null space
2096 * @fmt: The format string to use
2097 * @...: Arguments for the format string
2099 * The return value is the number of characters written into @buf not including
2100 * the trailing '\0'. If @size is == 0 the function returns 0.
2103 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2108 va_start(args, fmt);
2109 i = vscnprintf(buf, size, fmt, args);
2114 EXPORT_SYMBOL(scnprintf);
2117 * vsprintf - Format a string and place it in a buffer
2118 * @buf: The buffer to place the result into
2119 * @fmt: The format string to use
2120 * @args: Arguments for the format string
2122 * The function returns the number of characters written
2123 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2126 * If you're not already dealing with a va_list consider using sprintf().
2128 * See the vsnprintf() documentation for format string extensions over C99.
2130 int vsprintf(char *buf, const char *fmt, va_list args)
2132 return vsnprintf(buf, INT_MAX, fmt, args);
2134 EXPORT_SYMBOL(vsprintf);
2137 * sprintf - Format a string and place it in a buffer
2138 * @buf: The buffer to place the result into
2139 * @fmt: The format string to use
2140 * @...: Arguments for the format string
2142 * The function returns the number of characters written
2143 * into @buf. Use snprintf() or scnprintf() in order to avoid
2146 * See the vsnprintf() documentation for format string extensions over C99.
2148 int sprintf(char *buf, const char *fmt, ...)
2153 va_start(args, fmt);
2154 i = vsnprintf(buf, INT_MAX, fmt, args);
2159 EXPORT_SYMBOL(sprintf);
2161 #ifdef CONFIG_BINARY_PRINTF
2164 * vbin_printf() - VA arguments to binary data
2165 * bstr_printf() - Binary data to text string
2169 * vbin_printf - Parse a format string and place args' binary value in a buffer
2170 * @bin_buf: The buffer to place args' binary value
2171 * @size: The size of the buffer(by words(32bits), not characters)
2172 * @fmt: The format string to use
2173 * @args: Arguments for the format string
2175 * The format follows C99 vsnprintf, except %n is ignored, and its argument
2178 * The return value is the number of words(32bits) which would be generated for
2182 * If the return value is greater than @size, the resulting bin_buf is NOT
2183 * valid for bstr_printf().
2185 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2187 struct printf_spec spec = {0};
2190 str = (char *)bin_buf;
2191 end = (char *)(bin_buf + size);
2193 #define save_arg(type) \
2195 if (sizeof(type) == 8) { \
2196 unsigned long long value; \
2197 str = PTR_ALIGN(str, sizeof(u32)); \
2198 value = va_arg(args, unsigned long long); \
2199 if (str + sizeof(type) <= end) { \
2200 *(u32 *)str = *(u32 *)&value; \
2201 *(u32 *)(str + 4) = *((u32 *)&value + 1); \
2204 unsigned long value; \
2205 str = PTR_ALIGN(str, sizeof(type)); \
2206 value = va_arg(args, int); \
2207 if (str + sizeof(type) <= end) \
2208 *(typeof(type) *)str = (type)value; \
2210 str += sizeof(type); \
2214 int read = format_decode(fmt, &spec);
2218 switch (spec.type) {
2219 case FORMAT_TYPE_NONE:
2220 case FORMAT_TYPE_PERCENT_CHAR:
2222 case FORMAT_TYPE_INVALID:
2225 case FORMAT_TYPE_WIDTH:
2226 case FORMAT_TYPE_PRECISION:
2230 case FORMAT_TYPE_CHAR:
2234 case FORMAT_TYPE_STR: {
2235 const char *save_str = va_arg(args, char *);
2238 if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2239 || (unsigned long)save_str < PAGE_SIZE)
2240 save_str = "(null)";
2241 len = strlen(save_str) + 1;
2242 if (str + len < end)
2243 memcpy(str, save_str, len);
2248 case FORMAT_TYPE_PTR:
2250 /* skip all alphanumeric pointer suffixes */
2251 while (isalnum(*fmt))
2256 switch (spec.type) {
2258 case FORMAT_TYPE_LONG_LONG:
2259 save_arg(long long);
2261 case FORMAT_TYPE_ULONG:
2262 case FORMAT_TYPE_LONG:
2263 save_arg(unsigned long);
2265 case FORMAT_TYPE_SIZE_T:
2268 case FORMAT_TYPE_PTRDIFF:
2269 save_arg(ptrdiff_t);
2271 case FORMAT_TYPE_UBYTE:
2272 case FORMAT_TYPE_BYTE:
2275 case FORMAT_TYPE_USHORT:
2276 case FORMAT_TYPE_SHORT:
2286 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2289 EXPORT_SYMBOL_GPL(vbin_printf);
2292 * bstr_printf - Format a string from binary arguments and place it in a buffer
2293 * @buf: The buffer to place the result into
2294 * @size: The size of the buffer, including the trailing null space
2295 * @fmt: The format string to use
2296 * @bin_buf: Binary arguments for the format string
2298 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2299 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2300 * a binary buffer that generated by vbin_printf.
2302 * The format follows C99 vsnprintf, but has some extensions:
2303 * see vsnprintf comment for details.
2305 * The return value is the number of characters which would
2306 * be generated for the given input, excluding the trailing
2307 * '\0', as per ISO C99. If you want to have the exact
2308 * number of characters written into @buf as return value
2309 * (not including the trailing '\0'), use vscnprintf(). If the
2310 * return is greater than or equal to @size, the resulting
2311 * string is truncated.
2313 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2315 struct printf_spec spec = {0};
2317 const char *args = (const char *)bin_buf;
2319 if (WARN_ON_ONCE(size > INT_MAX))
2325 #define get_arg(type) \
2327 typeof(type) value; \
2328 if (sizeof(type) == 8) { \
2329 args = PTR_ALIGN(args, sizeof(u32)); \
2330 *(u32 *)&value = *(u32 *)args; \
2331 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
2333 args = PTR_ALIGN(args, sizeof(type)); \
2334 value = *(typeof(type) *)args; \
2336 args += sizeof(type); \
2340 /* Make sure end is always >= buf */
2347 const char *old_fmt = fmt;
2348 int read = format_decode(fmt, &spec);
2352 switch (spec.type) {
2353 case FORMAT_TYPE_NONE: {
2356 if (copy > end - str)
2358 memcpy(str, old_fmt, copy);
2364 case FORMAT_TYPE_WIDTH:
2365 spec.field_width = get_arg(int);
2368 case FORMAT_TYPE_PRECISION:
2369 spec.precision = get_arg(int);
2372 case FORMAT_TYPE_CHAR: {
2375 if (!(spec.flags & LEFT)) {
2376 while (--spec.field_width > 0) {
2382 c = (unsigned char) get_arg(char);
2386 while (--spec.field_width > 0) {
2394 case FORMAT_TYPE_STR: {
2395 const char *str_arg = args;
2396 args += strlen(str_arg) + 1;
2397 str = string(str, end, (char *)str_arg, spec);
2401 case FORMAT_TYPE_PTR:
2402 str = pointer(fmt, str, end, get_arg(void *), spec);
2403 while (isalnum(*fmt))
2407 case FORMAT_TYPE_PERCENT_CHAR:
2413 case FORMAT_TYPE_INVALID:
2417 unsigned long long num;
2419 switch (spec.type) {
2421 case FORMAT_TYPE_LONG_LONG:
2422 num = get_arg(long long);
2424 case FORMAT_TYPE_ULONG:
2425 case FORMAT_TYPE_LONG:
2426 num = get_arg(unsigned long);
2428 case FORMAT_TYPE_SIZE_T:
2429 num = get_arg(size_t);
2431 case FORMAT_TYPE_PTRDIFF:
2432 num = get_arg(ptrdiff_t);
2434 case FORMAT_TYPE_UBYTE:
2435 num = get_arg(unsigned char);
2437 case FORMAT_TYPE_BYTE:
2438 num = get_arg(signed char);
2440 case FORMAT_TYPE_USHORT:
2441 num = get_arg(unsigned short);
2443 case FORMAT_TYPE_SHORT:
2444 num = get_arg(short);
2446 case FORMAT_TYPE_UINT:
2447 num = get_arg(unsigned int);
2453 str = number(str, end, num, spec);
2455 } /* switch(spec.type) */
2468 /* the trailing null byte doesn't count towards the total */
2471 EXPORT_SYMBOL_GPL(bstr_printf);
2474 * bprintf - Parse a format string and place args' binary value in a buffer
2475 * @bin_buf: The buffer to place args' binary value
2476 * @size: The size of the buffer(by words(32bits), not characters)
2477 * @fmt: The format string to use
2478 * @...: Arguments for the format string
2480 * The function returns the number of words(u32) written
2483 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2488 va_start(args, fmt);
2489 ret = vbin_printf(bin_buf, size, fmt, args);
2494 EXPORT_SYMBOL_GPL(bprintf);
2496 #endif /* CONFIG_BINARY_PRINTF */
2499 * vsscanf - Unformat a buffer into a list of arguments
2500 * @buf: input buffer
2501 * @fmt: format of buffer
2504 int vsscanf(const char *buf, const char *fmt, va_list args)
2506 const char *str = buf;
2514 unsigned long long u;
2520 /* skip any white space in format */
2521 /* white space in format matchs any amount of
2522 * white space, including none, in the input.
2524 if (isspace(*fmt)) {
2525 fmt = skip_spaces(++fmt);
2526 str = skip_spaces(str);
2529 /* anything that is not a conversion must match exactly */
2530 if (*fmt != '%' && *fmt) {
2531 if (*fmt++ != *str++)
2540 /* skip this conversion.
2541 * advance both strings to next white space
2546 while (!isspace(*fmt) && *fmt != '%' && *fmt)
2548 while (!isspace(*str) && *str)
2553 /* get field width */
2555 if (isdigit(*fmt)) {
2556 field_width = skip_atoi(&fmt);
2557 if (field_width <= 0)
2561 /* get conversion qualifier */
2563 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2564 _tolower(*fmt) == 'z') {
2566 if (unlikely(qualifier == *fmt)) {
2567 if (qualifier == 'h') {
2570 } else if (qualifier == 'l') {
2581 /* return number of characters read so far */
2582 *va_arg(args, int *) = str - buf;
2596 char *s = (char *)va_arg(args, char*);
2597 if (field_width == -1)
2601 } while (--field_width > 0 && *str);
2607 char *s = (char *)va_arg(args, char *);
2608 if (field_width == -1)
2609 field_width = SHRT_MAX;
2610 /* first, skip leading white space in buffer */
2611 str = skip_spaces(str);
2613 /* now copy until next white space */
2614 while (*str && !isspace(*str) && field_width--)
2634 /* looking for '%' in str */
2639 /* invalid format; stop here */
2643 /* have some sort of integer conversion.
2644 * first, skip white space in buffer.
2646 str = skip_spaces(str);
2649 if (is_sign && digit == '-')
2653 || (base == 16 && !isxdigit(digit))
2654 || (base == 10 && !isdigit(digit))
2655 || (base == 8 && (!isdigit(digit) || digit > '7'))
2656 || (base == 0 && !isdigit(digit)))
2660 val.s = qualifier != 'L' ?
2661 simple_strtol(str, &next, base) :
2662 simple_strtoll(str, &next, base);
2664 val.u = qualifier != 'L' ?
2665 simple_strtoul(str, &next, base) :
2666 simple_strtoull(str, &next, base);
2668 if (field_width > 0 && next - str > field_width) {
2670 _parse_integer_fixup_radix(str, &base);
2671 while (next - str > field_width) {
2673 val.s = div_s64(val.s, base);
2675 val.u = div_u64(val.u, base);
2680 switch (qualifier) {
2681 case 'H': /* that's 'hh' in format */
2683 *va_arg(args, signed char *) = val.s;
2685 *va_arg(args, unsigned char *) = val.u;
2689 *va_arg(args, short *) = val.s;
2691 *va_arg(args, unsigned short *) = val.u;
2695 *va_arg(args, long *) = val.s;
2697 *va_arg(args, unsigned long *) = val.u;
2701 *va_arg(args, long long *) = val.s;
2703 *va_arg(args, unsigned long long *) = val.u;
2707 *va_arg(args, size_t *) = val.u;
2711 *va_arg(args, int *) = val.s;
2713 *va_arg(args, unsigned int *) = val.u;
2725 EXPORT_SYMBOL(vsscanf);
2728 * sscanf - Unformat a buffer into a list of arguments
2729 * @buf: input buffer
2730 * @fmt: formatting of buffer
2731 * @...: resulting arguments
2733 int sscanf(const char *buf, const char *fmt, ...)
2738 va_start(args, fmt);
2739 i = vsscanf(buf, fmt, args);
2744 EXPORT_SYMBOL(sscanf);