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-provider.h>
21 #include <linux/module.h> /* for KSYM_SYMBOL_LEN */
22 #include <linux/types.h>
23 #include <linux/string.h>
24 #include <linux/ctype.h>
25 #include <linux/kernel.h>
26 #include <linux/kallsyms.h>
27 #include <linux/math64.h>
28 #include <linux/uaccess.h>
29 #include <linux/ioport.h>
30 #include <linux/dcache.h>
31 #include <linux/cred.h>
32 #include <net/addrconf.h>
34 #include <asm/page.h> /* for PAGE_SIZE */
35 #include <asm/sections.h> /* for dereference_function_descriptor() */
36 #include <asm/byteorder.h> /* cpu_to_le16 */
38 #include <linux/string_helpers.h>
42 * simple_strtoull - convert a string to an unsigned long long
43 * @cp: The start of the string
44 * @endp: A pointer to the end of the parsed string will be placed here
45 * @base: The number base to use
47 * This function is obsolete. Please use kstrtoull instead.
49 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
51 unsigned long long result;
54 cp = _parse_integer_fixup_radix(cp, &base);
55 rv = _parse_integer(cp, base, &result);
57 cp += (rv & ~KSTRTOX_OVERFLOW);
64 EXPORT_SYMBOL(simple_strtoull);
67 * simple_strtoul - convert a string to an unsigned long
68 * @cp: The start of the string
69 * @endp: A pointer to the end of the parsed string will be placed here
70 * @base: The number base to use
72 * This function is obsolete. Please use kstrtoul instead.
74 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
76 return simple_strtoull(cp, endp, base);
78 EXPORT_SYMBOL(simple_strtoul);
81 * simple_strtol - convert a string to a signed long
82 * @cp: The start of the string
83 * @endp: A pointer to the end of the parsed string will be placed here
84 * @base: The number base to use
86 * This function is obsolete. Please use kstrtol instead.
88 long simple_strtol(const char *cp, char **endp, unsigned int base)
91 return -simple_strtoul(cp + 1, endp, base);
93 return simple_strtoul(cp, endp, base);
95 EXPORT_SYMBOL(simple_strtol);
98 * simple_strtoll - convert a string to a signed long long
99 * @cp: The start of the string
100 * @endp: A pointer to the end of the parsed string will be placed here
101 * @base: The number base to use
103 * This function is obsolete. Please use kstrtoll instead.
105 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
108 return -simple_strtoull(cp + 1, endp, base);
110 return simple_strtoull(cp, endp, base);
112 EXPORT_SYMBOL(simple_strtoll);
114 static noinline_for_stack
115 int skip_atoi(const char **s)
120 i = i*10 + *((*s)++) - '0';
121 } while (isdigit(**s));
127 * Decimal conversion is by far the most typical, and is used for
128 * /proc and /sys data. This directly impacts e.g. top performance
129 * with many processes running. We optimize it for speed by emitting
130 * two characters at a time, using a 200 byte lookup table. This
131 * roughly halves the number of multiplications compared to computing
132 * the digits one at a time. Implementation strongly inspired by the
133 * previous version, which in turn used ideas described at
134 * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
135 * from the author, Douglas W. Jones).
137 * It turns out there is precisely one 26 bit fixed-point
138 * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
139 * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
140 * range happens to be somewhat larger (x <= 1073741898), but that's
141 * irrelevant for our purpose.
143 * For dividing a number in the range [10^4, 10^6-1] by 100, we still
144 * need a 32x32->64 bit multiply, so we simply use the same constant.
146 * For dividing a number in the range [100, 10^4-1] by 100, there are
147 * several options. The simplest is (x * 0x147b) >> 19, which is valid
148 * for all x <= 43698.
151 static const u16 decpair[100] = {
152 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
153 _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
154 _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
155 _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
156 _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
157 _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
158 _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
159 _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
160 _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
161 _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
162 _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
167 * This will print a single '0' even if r == 0, since we would
168 * immediately jump to out_r where two 0s would be written and one of
169 * them then discarded. This is needed by ip4_string below. All other
170 * callers pass a non-zero value of r.
172 static noinline_for_stack
173 char *put_dec_trunc8(char *buf, unsigned r)
181 /* 100 <= r < 10^8 */
182 q = (r * (u64)0x28f5c29) >> 32;
183 *((u16 *)buf) = decpair[r - 100*q];
190 /* 100 <= q < 10^6 */
191 r = (q * (u64)0x28f5c29) >> 32;
192 *((u16 *)buf) = decpair[q - 100*r];
199 /* 100 <= r < 10^4 */
200 q = (r * 0x147b) >> 19;
201 *((u16 *)buf) = decpair[r - 100*q];
208 *((u16 *)buf) = decpair[r];
215 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
216 static noinline_for_stack
217 char *put_dec_full8(char *buf, unsigned r)
222 q = (r * (u64)0x28f5c29) >> 32;
223 *((u16 *)buf) = decpair[r - 100*q];
227 r = (q * (u64)0x28f5c29) >> 32;
228 *((u16 *)buf) = decpair[q - 100*r];
232 q = (r * 0x147b) >> 19;
233 *((u16 *)buf) = decpair[r - 100*q];
237 *((u16 *)buf) = decpair[q];
242 static noinline_for_stack
243 char *put_dec(char *buf, unsigned long long n)
245 if (n >= 100*1000*1000)
246 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
247 /* 1 <= n <= 1.6e11 */
248 if (n >= 100*1000*1000)
249 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
251 return put_dec_trunc8(buf, n);
254 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
257 put_dec_full4(char *buf, unsigned r)
262 q = (r * 0x147b) >> 19;
263 *((u16 *)buf) = decpair[r - 100*q];
266 *((u16 *)buf) = decpair[q];
270 * Call put_dec_full4 on x % 10000, return x / 10000.
271 * The approximation x/10000 == (x * 0x346DC5D7) >> 43
272 * holds for all x < 1,128,869,999. The largest value this
273 * helper will ever be asked to convert is 1,125,520,955.
274 * (second call in the put_dec code, assuming n is all-ones).
276 static noinline_for_stack
277 unsigned put_dec_helper4(char *buf, unsigned x)
279 uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
281 put_dec_full4(buf, x - q * 10000);
285 /* Based on code by Douglas W. Jones found at
286 * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
287 * (with permission from the author).
288 * Performs no 64-bit division and hence should be fast on 32-bit machines.
291 char *put_dec(char *buf, unsigned long long n)
293 uint32_t d3, d2, d1, q, h;
295 if (n < 100*1000*1000)
296 return put_dec_trunc8(buf, n);
298 d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
301 d3 = (h >> 16); /* implicit "& 0xffff" */
303 /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
304 = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
305 q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
306 q = put_dec_helper4(buf, q);
308 q += 7671 * d3 + 9496 * d2 + 6 * d1;
309 q = put_dec_helper4(buf+4, q);
311 q += 4749 * d3 + 42 * d2;
312 q = put_dec_helper4(buf+8, q);
317 buf = put_dec_trunc8(buf, q);
318 else while (buf[-1] == '0')
327 * Convert passed number to decimal string.
328 * Returns the length of string. On buffer overflow, returns 0.
330 * If speed is not important, use snprintf(). It's easy to read the code.
332 int num_to_str(char *buf, int size, unsigned long long num)
334 /* put_dec requires 2-byte alignment of the buffer. */
335 char tmp[sizeof(num) * 3] __aligned(2);
338 /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
343 len = put_dec(tmp, num) - tmp;
348 for (idx = 0; idx < len; ++idx)
349 buf[idx] = tmp[len - idx - 1];
353 #define SIGN 1 /* unsigned/signed, must be 1 */
354 #define LEFT 2 /* left justified */
355 #define PLUS 4 /* show plus */
356 #define SPACE 8 /* space if plus */
357 #define ZEROPAD 16 /* pad with zero, must be 16 == '0' - ' ' */
358 #define SMALL 32 /* use lowercase in hex (must be 32 == 0x20) */
359 #define SPECIAL 64 /* prefix hex with "0x", octal with "0" */
362 FORMAT_TYPE_NONE, /* Just a string part */
364 FORMAT_TYPE_PRECISION,
368 FORMAT_TYPE_PERCENT_CHAR,
370 FORMAT_TYPE_LONG_LONG,
384 u8 type; /* format_type enum */
385 u8 flags; /* flags to number() */
386 u8 base; /* number base, 8, 10 or 16 only */
387 u8 qualifier; /* number qualifier, one of 'hHlLtzZ' */
388 s16 field_width; /* width of output field */
389 s16 precision; /* # of digits/chars */
392 static noinline_for_stack
393 char *number(char *buf, char *end, unsigned long long num,
394 struct printf_spec spec)
396 /* put_dec requires 2-byte alignment of the buffer. */
397 char tmp[3 * sizeof(num)] __aligned(2);
400 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
402 bool is_zero = num == 0LL;
404 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
405 * produces same digits or (maybe lowercased) letters */
406 locase = (spec.flags & SMALL);
407 if (spec.flags & LEFT)
408 spec.flags &= ~ZEROPAD;
410 if (spec.flags & SIGN) {
411 if ((signed long long)num < 0) {
413 num = -(signed long long)num;
415 } else if (spec.flags & PLUS) {
418 } else if (spec.flags & SPACE) {
425 spec.field_width -= 2;
430 /* generate full string in tmp[], in reverse order */
433 tmp[i++] = hex_asc_upper[num] | locase;
434 else if (spec.base != 10) { /* 8 or 16 */
435 int mask = spec.base - 1;
441 tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
444 } else { /* base 10 */
445 i = put_dec(tmp, num) - tmp;
448 /* printing 100 using %2d gives "100", not "00" */
449 if (i > spec.precision)
451 /* leading space padding */
452 spec.field_width -= spec.precision;
453 if (!(spec.flags & (ZEROPAD | LEFT))) {
454 while (--spec.field_width >= 0) {
466 /* "0x" / "0" prefix */
468 if (spec.base == 16 || !is_zero) {
473 if (spec.base == 16) {
475 *buf = ('X' | locase);
479 /* zero or space padding */
480 if (!(spec.flags & LEFT)) {
481 char c = ' ' + (spec.flags & ZEROPAD);
482 BUILD_BUG_ON(' ' + ZEROPAD != '0');
483 while (--spec.field_width >= 0) {
489 /* hmm even more zero padding? */
490 while (i <= --spec.precision) {
495 /* actual digits of result */
501 /* trailing space padding */
502 while (--spec.field_width >= 0) {
511 static noinline_for_stack
512 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
516 if ((unsigned long)s < PAGE_SIZE)
519 len = strnlen(s, spec.precision);
521 if (!(spec.flags & LEFT)) {
522 while (len < spec.field_width--) {
528 for (i = 0; i < len; ++i) {
533 while (len < spec.field_width--) {
542 static void widen(char *buf, char *end, unsigned len, unsigned spaces)
545 if (buf >= end) /* nowhere to put anything */
548 if (size <= spaces) {
549 memset(buf, ' ', size);
553 if (len > size - spaces)
555 memmove(buf + spaces, buf, len);
557 memset(buf, ' ', spaces);
560 static noinline_for_stack
561 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
564 const char *array[4], *s;
565 const struct dentry *p;
570 case '2': case '3': case '4':
571 depth = fmt[1] - '0';
578 for (i = 0; i < depth; i++, d = p) {
579 p = ACCESS_ONCE(d->d_parent);
580 array[i] = ACCESS_ONCE(d->d_name.name);
589 for (n = 0; n != spec.precision; n++, buf++) {
601 if (n < spec.field_width) {
602 /* we want to pad the sucker */
603 unsigned spaces = spec.field_width - n;
604 if (!(spec.flags & LEFT)) {
605 widen(buf - n, end, n, spaces);
617 static noinline_for_stack
618 char *symbol_string(char *buf, char *end, void *ptr,
619 struct printf_spec spec, const char *fmt)
622 #ifdef CONFIG_KALLSYMS
623 char sym[KSYM_SYMBOL_LEN];
627 ptr = __builtin_extract_return_addr(ptr);
628 value = (unsigned long)ptr;
630 #ifdef CONFIG_KALLSYMS
632 sprint_backtrace(sym, value);
633 else if (*fmt != 'f' && *fmt != 's')
634 sprint_symbol(sym, value);
636 sprint_symbol_no_offset(sym, value);
638 return string(buf, end, sym, spec);
640 spec.field_width = 2 * sizeof(void *);
641 spec.flags |= SPECIAL | SMALL | ZEROPAD;
644 return number(buf, end, value, spec);
648 static noinline_for_stack
649 char *resource_string(char *buf, char *end, struct resource *res,
650 struct printf_spec spec, const char *fmt)
652 #ifndef IO_RSRC_PRINTK_SIZE
653 #define IO_RSRC_PRINTK_SIZE 6
656 #ifndef MEM_RSRC_PRINTK_SIZE
657 #define MEM_RSRC_PRINTK_SIZE 10
659 static const struct printf_spec io_spec = {
661 .field_width = IO_RSRC_PRINTK_SIZE,
663 .flags = SPECIAL | SMALL | ZEROPAD,
665 static const struct printf_spec mem_spec = {
667 .field_width = MEM_RSRC_PRINTK_SIZE,
669 .flags = SPECIAL | SMALL | ZEROPAD,
671 static const struct printf_spec bus_spec = {
675 .flags = SMALL | ZEROPAD,
677 static const struct printf_spec dec_spec = {
682 static const struct printf_spec str_spec = {
687 static const struct printf_spec flag_spec = {
690 .flags = SPECIAL | SMALL,
693 /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
694 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
695 #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
696 #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
697 #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
698 #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
699 char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
700 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
702 char *p = sym, *pend = sym + sizeof(sym);
703 int decode = (fmt[0] == 'R') ? 1 : 0;
704 const struct printf_spec *specp;
707 if (res->flags & IORESOURCE_IO) {
708 p = string(p, pend, "io ", str_spec);
710 } else if (res->flags & IORESOURCE_MEM) {
711 p = string(p, pend, "mem ", str_spec);
713 } else if (res->flags & IORESOURCE_IRQ) {
714 p = string(p, pend, "irq ", str_spec);
716 } else if (res->flags & IORESOURCE_DMA) {
717 p = string(p, pend, "dma ", str_spec);
719 } else if (res->flags & IORESOURCE_BUS) {
720 p = string(p, pend, "bus ", str_spec);
723 p = string(p, pend, "??? ", str_spec);
727 if (decode && res->flags & IORESOURCE_UNSET) {
728 p = string(p, pend, "size ", str_spec);
729 p = number(p, pend, resource_size(res), *specp);
731 p = number(p, pend, res->start, *specp);
732 if (res->start != res->end) {
734 p = number(p, pend, res->end, *specp);
738 if (res->flags & IORESOURCE_MEM_64)
739 p = string(p, pend, " 64bit", str_spec);
740 if (res->flags & IORESOURCE_PREFETCH)
741 p = string(p, pend, " pref", str_spec);
742 if (res->flags & IORESOURCE_WINDOW)
743 p = string(p, pend, " window", str_spec);
744 if (res->flags & IORESOURCE_DISABLED)
745 p = string(p, pend, " disabled", str_spec);
747 p = string(p, pend, " flags ", str_spec);
748 p = number(p, pend, res->flags, flag_spec);
753 return string(buf, end, sym, spec);
756 static noinline_for_stack
757 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
760 int i, len = 1; /* if we pass '%ph[CDN]', field width remains
761 negative value, fallback to the default */
764 if (spec.field_width == 0)
765 /* nothing to print */
768 if (ZERO_OR_NULL_PTR(addr))
770 return string(buf, end, NULL, spec);
787 if (spec.field_width > 0)
788 len = min_t(int, spec.field_width, 64);
790 for (i = 0; i < len; ++i) {
792 *buf = hex_asc_hi(addr[i]);
795 *buf = hex_asc_lo(addr[i]);
798 if (separator && i != len - 1) {
808 static noinline_for_stack
809 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
810 struct printf_spec spec, const char *fmt)
812 const int CHUNKSZ = 32;
813 int nr_bits = max_t(int, spec.field_width, 0);
817 /* reused to print numbers */
818 spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
820 chunksz = nr_bits & (CHUNKSZ - 1);
824 i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
825 for (; i >= 0; i -= CHUNKSZ) {
829 chunkmask = ((1ULL << chunksz) - 1);
830 word = i / BITS_PER_LONG;
831 bit = i % BITS_PER_LONG;
832 val = (bitmap[word] >> bit) & chunkmask;
841 spec.field_width = DIV_ROUND_UP(chunksz, 4);
842 buf = number(buf, end, val, spec);
849 static noinline_for_stack
850 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
851 struct printf_spec spec, const char *fmt)
853 int nr_bits = max_t(int, spec.field_width, 0);
854 /* current bit is 'cur', most recently seen range is [rbot, rtop] */
858 /* reused to print numbers */
859 spec = (struct printf_spec){ .base = 10 };
861 rbot = cur = find_first_bit(bitmap, nr_bits);
862 while (cur < nr_bits) {
864 cur = find_next_bit(bitmap, nr_bits, cur + 1);
865 if (cur < nr_bits && cur <= rtop + 1)
875 buf = number(buf, end, rbot, spec);
881 buf = number(buf, end, rtop, spec);
889 static noinline_for_stack
890 char *mac_address_string(char *buf, char *end, u8 *addr,
891 struct printf_spec spec, const char *fmt)
893 char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
897 bool reversed = false;
913 for (i = 0; i < 6; i++) {
915 p = hex_byte_pack(p, addr[5 - i]);
917 p = hex_byte_pack(p, addr[i]);
919 if (fmt[0] == 'M' && i != 5)
924 return string(buf, end, mac_addr, spec);
927 static noinline_for_stack
928 char *ip4_string(char *p, const u8 *addr, const char *fmt)
931 bool leading_zeros = (fmt[0] == 'i');
956 for (i = 0; i < 4; i++) {
957 char temp[4] __aligned(2); /* hold each IP quad in reverse order */
958 int digits = put_dec_trunc8(temp, addr[index]) - temp;
965 /* reverse the digits in the quad */
977 static noinline_for_stack
978 char *ip6_compressed_string(char *p, const char *addr)
981 unsigned char zerolength[8];
986 bool needcolon = false;
990 memcpy(&in6, addr, sizeof(struct in6_addr));
992 useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
994 memset(zerolength, 0, sizeof(zerolength));
1001 /* find position of longest 0 run */
1002 for (i = 0; i < range; i++) {
1003 for (j = i; j < range; j++) {
1004 if (in6.s6_addr16[j] != 0)
1009 for (i = 0; i < range; i++) {
1010 if (zerolength[i] > longest) {
1011 longest = zerolength[i];
1015 if (longest == 1) /* don't compress a single 0 */
1019 for (i = 0; i < range; i++) {
1020 if (i == colonpos) {
1021 if (needcolon || i == 0)
1032 /* hex u16 without leading 0s */
1033 word = ntohs(in6.s6_addr16[i]);
1038 p = hex_byte_pack(p, hi);
1040 *p++ = hex_asc_lo(hi);
1041 p = hex_byte_pack(p, lo);
1044 p = hex_byte_pack(p, lo);
1046 *p++ = hex_asc_lo(lo);
1053 p = ip4_string(p, &in6.s6_addr[12], "I4");
1060 static noinline_for_stack
1061 char *ip6_string(char *p, const char *addr, const char *fmt)
1065 for (i = 0; i < 8; i++) {
1066 p = hex_byte_pack(p, *addr++);
1067 p = hex_byte_pack(p, *addr++);
1068 if (fmt[0] == 'I' && i != 7)
1076 static noinline_for_stack
1077 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1078 struct printf_spec spec, const char *fmt)
1080 char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1082 if (fmt[0] == 'I' && fmt[2] == 'c')
1083 ip6_compressed_string(ip6_addr, addr);
1085 ip6_string(ip6_addr, addr, fmt);
1087 return string(buf, end, ip6_addr, spec);
1090 static noinline_for_stack
1091 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1092 struct printf_spec spec, const char *fmt)
1094 char ip4_addr[sizeof("255.255.255.255")];
1096 ip4_string(ip4_addr, addr, fmt);
1098 return string(buf, end, ip4_addr, spec);
1101 static noinline_for_stack
1102 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1103 struct printf_spec spec, const char *fmt)
1105 bool have_p = false, have_s = false, have_f = false, have_c = false;
1106 char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1107 sizeof(":12345") + sizeof("/123456789") +
1108 sizeof("%1234567890")];
1109 char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1110 const u8 *addr = (const u8 *) &sa->sin6_addr;
1111 char fmt6[2] = { fmt[0], '6' };
1115 while (isalpha(*++fmt)) {
1132 if (have_p || have_s || have_f) {
1137 if (fmt6[0] == 'I' && have_c)
1138 p = ip6_compressed_string(ip6_addr + off, addr);
1140 p = ip6_string(ip6_addr + off, addr, fmt6);
1142 if (have_p || have_s || have_f)
1147 p = number(p, pend, ntohs(sa->sin6_port), spec);
1151 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1152 IPV6_FLOWINFO_MASK), spec);
1156 p = number(p, pend, sa->sin6_scope_id, spec);
1160 return string(buf, end, ip6_addr, spec);
1163 static noinline_for_stack
1164 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1165 struct printf_spec spec, const char *fmt)
1167 bool have_p = false;
1168 char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1169 char *pend = ip4_addr + sizeof(ip4_addr);
1170 const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1171 char fmt4[3] = { fmt[0], '4', 0 };
1174 while (isalpha(*++fmt)) {
1188 p = ip4_string(ip4_addr, addr, fmt4);
1191 p = number(p, pend, ntohs(sa->sin_port), spec);
1195 return string(buf, end, ip4_addr, spec);
1198 static noinline_for_stack
1199 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1204 unsigned int flags = 0;
1207 if (spec.field_width == 0)
1208 return buf; /* nothing to print */
1210 if (ZERO_OR_NULL_PTR(addr))
1211 return string(buf, end, NULL, spec); /* NULL pointer */
1215 switch (fmt[count++]) {
1217 flags |= ESCAPE_ANY;
1220 flags |= ESCAPE_SPECIAL;
1223 flags |= ESCAPE_HEX;
1226 flags |= ESCAPE_NULL;
1229 flags |= ESCAPE_OCTAL;
1235 flags |= ESCAPE_SPACE;
1244 flags = ESCAPE_ANY_NP;
1246 len = spec.field_width < 0 ? 1 : spec.field_width;
1249 * string_escape_mem() writes as many characters as it can to
1250 * the given buffer, and returns the total size of the output
1251 * had the buffer been big enough.
1253 buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1258 static noinline_for_stack
1259 char *uuid_string(char *buf, char *end, const u8 *addr,
1260 struct printf_spec spec, const char *fmt)
1262 char uuid[sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")];
1265 static const u8 be[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
1266 static const u8 le[16] = {3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15};
1267 const u8 *index = be;
1272 uc = true; /* fall-through */
1281 for (i = 0; i < 16; i++) {
1282 p = hex_byte_pack(p, addr[index[i]]);
1302 return string(buf, end, uuid, spec);
1306 char *netdev_feature_string(char *buf, char *end, const u8 *addr,
1307 struct printf_spec spec)
1309 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1310 if (spec.field_width == -1)
1311 spec.field_width = 2 + 2 * sizeof(netdev_features_t);
1314 return number(buf, end, *(const netdev_features_t *)addr, spec);
1317 static noinline_for_stack
1318 char *address_val(char *buf, char *end, const void *addr,
1319 struct printf_spec spec, const char *fmt)
1321 unsigned long long num;
1323 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1328 num = *(const dma_addr_t *)addr;
1329 spec.field_width = sizeof(dma_addr_t) * 2 + 2;
1333 num = *(const phys_addr_t *)addr;
1334 spec.field_width = sizeof(phys_addr_t) * 2 + 2;
1338 return number(buf, end, num, spec);
1341 static noinline_for_stack
1342 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1345 if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1346 return string(buf, end, NULL, spec);
1350 return number(buf, end, clk_get_rate(clk), spec);
1354 #ifdef CONFIG_COMMON_CLK
1355 return string(buf, end, __clk_get_name(clk), spec);
1358 spec.field_width = sizeof(unsigned long) * 2 + 2;
1359 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1360 return number(buf, end, (unsigned long)clk, spec);
1365 int kptr_restrict __read_mostly;
1368 * Show a '%p' thing. A kernel extension is that the '%p' is followed
1369 * by an extra set of alphanumeric characters that are extended format
1372 * Right now we handle:
1374 * - 'F' For symbolic function descriptor pointers with offset
1375 * - 'f' For simple symbolic function names without offset
1376 * - 'S' For symbolic direct pointers with offset
1377 * - 's' For symbolic direct pointers without offset
1378 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1379 * - 'B' For backtraced symbolic direct pointers with offset
1380 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1381 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1382 * - 'b[l]' For a bitmap, the number of bits is determined by the field
1383 * width which must be explicitly specified either as part of the
1384 * format string '%32b[l]' or through '%*b[l]', [l] selects
1385 * range-list format instead of hex format
1386 * - 'M' For a 6-byte MAC address, it prints the address in the
1387 * usual colon-separated hex notation
1388 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1389 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1390 * with a dash-separated hex notation
1391 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1392 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1393 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1394 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
1396 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1397 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1398 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1399 * IPv6 omits the colons (01020304...0f)
1400 * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1402 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1403 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1404 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1405 * - 'I[6S]c' for IPv6 addresses printed as specified by
1406 * http://tools.ietf.org/html/rfc5952
1407 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1408 * of the following flags (see string_escape_mem() for the
1411 * c - ESCAPE_SPECIAL
1417 * By default ESCAPE_ANY_NP is used.
1418 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1419 * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1420 * Options for %pU are:
1421 * b big endian lower case hex (default)
1422 * B big endian UPPER case hex
1423 * l little endian lower case hex
1424 * L little endian UPPER case hex
1425 * big endian output byte order is:
1426 * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1427 * little endian output byte order is:
1428 * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1429 * - 'V' For a struct va_format which contains a format string * and va_list *,
1430 * call vsnprintf(->format, *->va_list).
1431 * Implements a "recursive vsnprintf".
1432 * Do not use this feature without some mechanism to verify the
1433 * correctness of the format string and va_list arguments.
1434 * - 'K' For a kernel pointer that should be hidden from unprivileged users
1435 * - 'NF' For a netdev_features_t
1436 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1437 * a certain separator (' ' by default):
1441 * The maximum supported length is 64 bytes of the input. Consider
1442 * to use print_hex_dump() for the larger input.
1443 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1444 * (default assumed to be phys_addr_t, passed by reference)
1445 * - 'd[234]' For a dentry name (optionally 2-4 last components)
1446 * - 'D[234]' Same as 'd' but for a struct file
1447 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1448 * (legacy clock framework) of the clock
1449 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1450 * (legacy clock framework) of the clock
1451 * - 'Cr' For a clock, it prints the current rate of the clock
1453 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1454 * function pointers are really function descriptors, which contain a
1455 * pointer to the real address.
1457 static noinline_for_stack
1458 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1459 struct printf_spec spec)
1461 int default_width = 2 * sizeof(void *) + (spec.flags & SPECIAL ? 2 : 0);
1463 if (!ptr && *fmt != 'K') {
1465 * Print (null) with the same width as a pointer so it makes
1466 * tabular output look nice.
1468 if (spec.field_width == -1)
1469 spec.field_width = default_width;
1470 return string(buf, end, "(null)", spec);
1476 ptr = dereference_function_descriptor(ptr);
1481 return symbol_string(buf, end, ptr, spec, fmt);
1484 return resource_string(buf, end, ptr, spec, fmt);
1486 return hex_string(buf, end, ptr, spec, fmt);
1490 return bitmap_list_string(buf, end, ptr, spec, fmt);
1492 return bitmap_string(buf, end, ptr, spec, fmt);
1494 case 'M': /* Colon separated: 00:01:02:03:04:05 */
1495 case 'm': /* Contiguous: 000102030405 */
1497 /* [mM]R (Reverse order; Bluetooth) */
1498 return mac_address_string(buf, end, ptr, spec, fmt);
1499 case 'I': /* Formatted IP supported
1501 * 6: 0001:0203:...:0708
1502 * 6c: 1::708 or 1::1.2.3.4
1504 case 'i': /* Contiguous:
1505 * 4: 001.002.003.004
1510 return ip6_addr_string(buf, end, ptr, spec, fmt);
1512 return ip4_addr_string(buf, end, ptr, spec, fmt);
1515 struct sockaddr raw;
1516 struct sockaddr_in v4;
1517 struct sockaddr_in6 v6;
1520 switch (sa->raw.sa_family) {
1522 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1524 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1526 return string(buf, end, "(invalid address)", spec);
1531 return escaped_string(buf, end, ptr, spec, fmt);
1533 return uuid_string(buf, end, ptr, spec, fmt);
1538 va_copy(va, *((struct va_format *)ptr)->va);
1539 buf += vsnprintf(buf, end > buf ? end - buf : 0,
1540 ((struct va_format *)ptr)->fmt, va);
1546 * %pK cannot be used in IRQ context because its test
1547 * for CAP_SYSLOG would be meaningless.
1549 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
1551 if (spec.field_width == -1)
1552 spec.field_width = default_width;
1553 return string(buf, end, "pK-error", spec);
1556 switch (kptr_restrict) {
1558 /* Always print %pK values */
1562 * Only print the real pointer value if the current
1563 * process has CAP_SYSLOG and is running with the
1564 * same credentials it started with. This is because
1565 * access to files is checked at open() time, but %pK
1566 * checks permission at read() time. We don't want to
1567 * leak pointer values if a binary opens a file using
1568 * %pK and then elevates privileges before reading it.
1570 const struct cred *cred = current_cred();
1572 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
1573 !uid_eq(cred->euid, cred->uid) ||
1574 !gid_eq(cred->egid, cred->gid))
1580 /* Always print 0's for %pK */
1589 return netdev_feature_string(buf, end, ptr, spec);
1593 return address_val(buf, end, ptr, spec, fmt);
1595 return dentry_name(buf, end, ptr, spec, fmt);
1597 return clock(buf, end, ptr, spec, fmt);
1599 return dentry_name(buf, end,
1600 ((const struct file *)ptr)->f_path.dentry,
1603 spec.flags |= SMALL;
1604 if (spec.field_width == -1) {
1605 spec.field_width = default_width;
1606 spec.flags |= ZEROPAD;
1610 return number(buf, end, (unsigned long) ptr, spec);
1614 * Helper function to decode printf style format.
1615 * Each call decode a token from the format and return the
1616 * number of characters read (or likely the delta where it wants
1617 * to go on the next call).
1618 * The decoded token is returned through the parameters
1620 * 'h', 'l', or 'L' for integer fields
1621 * 'z' support added 23/7/1999 S.H.
1622 * 'z' changed to 'Z' --davidm 1/25/99
1623 * 't' added for ptrdiff_t
1625 * @fmt: the format string
1626 * @type of the token returned
1627 * @flags: various flags such as +, -, # tokens..
1628 * @field_width: overwritten width
1629 * @base: base of the number (octal, hex, ...)
1630 * @precision: precision of a number
1631 * @qualifier: qualifier of a number (long, size_t, ...)
1633 static noinline_for_stack
1634 int format_decode(const char *fmt, struct printf_spec *spec)
1636 const char *start = fmt;
1638 /* we finished early by reading the field width */
1639 if (spec->type == FORMAT_TYPE_WIDTH) {
1640 if (spec->field_width < 0) {
1641 spec->field_width = -spec->field_width;
1642 spec->flags |= LEFT;
1644 spec->type = FORMAT_TYPE_NONE;
1648 /* we finished early by reading the precision */
1649 if (spec->type == FORMAT_TYPE_PRECISION) {
1650 if (spec->precision < 0)
1651 spec->precision = 0;
1653 spec->type = FORMAT_TYPE_NONE;
1658 spec->type = FORMAT_TYPE_NONE;
1660 for (; *fmt ; ++fmt) {
1665 /* Return the current non-format string */
1666 if (fmt != start || !*fmt)
1672 while (1) { /* this also skips first '%' */
1678 case '-': spec->flags |= LEFT; break;
1679 case '+': spec->flags |= PLUS; break;
1680 case ' ': spec->flags |= SPACE; break;
1681 case '#': spec->flags |= SPECIAL; break;
1682 case '0': spec->flags |= ZEROPAD; break;
1683 default: found = false;
1690 /* get field width */
1691 spec->field_width = -1;
1694 spec->field_width = skip_atoi(&fmt);
1695 else if (*fmt == '*') {
1696 /* it's the next argument */
1697 spec->type = FORMAT_TYPE_WIDTH;
1698 return ++fmt - start;
1702 /* get the precision */
1703 spec->precision = -1;
1706 if (isdigit(*fmt)) {
1707 spec->precision = skip_atoi(&fmt);
1708 if (spec->precision < 0)
1709 spec->precision = 0;
1710 } else if (*fmt == '*') {
1711 /* it's the next argument */
1712 spec->type = FORMAT_TYPE_PRECISION;
1713 return ++fmt - start;
1718 /* get the conversion qualifier */
1719 spec->qualifier = -1;
1720 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1721 _tolower(*fmt) == 'z' || *fmt == 't') {
1722 spec->qualifier = *fmt++;
1723 if (unlikely(spec->qualifier == *fmt)) {
1724 if (spec->qualifier == 'l') {
1725 spec->qualifier = 'L';
1727 } else if (spec->qualifier == 'h') {
1728 spec->qualifier = 'H';
1738 spec->type = FORMAT_TYPE_CHAR;
1739 return ++fmt - start;
1742 spec->type = FORMAT_TYPE_STR;
1743 return ++fmt - start;
1746 spec->type = FORMAT_TYPE_PTR;
1747 return ++fmt - start;
1750 spec->type = FORMAT_TYPE_PERCENT_CHAR;
1751 return ++fmt - start;
1753 /* integer number formats - set up the flags and "break" */
1759 spec->flags |= SMALL;
1767 spec->flags |= SIGN;
1773 * Since %n poses a greater security risk than utility, treat
1774 * it as an invalid format specifier. Warn about its use so
1775 * that new instances don't get added.
1777 WARN_ONCE(1, "Please remove ignored %%n in '%s'\n", fmt);
1781 spec->type = FORMAT_TYPE_INVALID;
1785 if (spec->qualifier == 'L')
1786 spec->type = FORMAT_TYPE_LONG_LONG;
1787 else if (spec->qualifier == 'l') {
1788 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
1789 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
1790 } else if (_tolower(spec->qualifier) == 'z') {
1791 spec->type = FORMAT_TYPE_SIZE_T;
1792 } else if (spec->qualifier == 't') {
1793 spec->type = FORMAT_TYPE_PTRDIFF;
1794 } else if (spec->qualifier == 'H') {
1795 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
1796 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
1797 } else if (spec->qualifier == 'h') {
1798 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
1799 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
1801 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
1802 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
1805 return ++fmt - start;
1809 * vsnprintf - Format a string and place it in a buffer
1810 * @buf: The buffer to place the result into
1811 * @size: The size of the buffer, including the trailing null space
1812 * @fmt: The format string to use
1813 * @args: Arguments for the format string
1815 * This function follows C99 vsnprintf, but has some extensions:
1816 * %pS output the name of a text symbol with offset
1817 * %ps output the name of a text symbol without offset
1818 * %pF output the name of a function pointer with its offset
1819 * %pf output the name of a function pointer without its offset
1820 * %pB output the name of a backtrace symbol with its offset
1821 * %pR output the address range in a struct resource with decoded flags
1822 * %pr output the address range in a struct resource with raw flags
1823 * %pb output the bitmap with field width as the number of bits
1824 * %pbl output the bitmap as range list with field width as the number of bits
1825 * %pM output a 6-byte MAC address with colons
1826 * %pMR output a 6-byte MAC address with colons in reversed order
1827 * %pMF output a 6-byte MAC address with dashes
1828 * %pm output a 6-byte MAC address without colons
1829 * %pmR output a 6-byte MAC address without colons in reversed order
1830 * %pI4 print an IPv4 address without leading zeros
1831 * %pi4 print an IPv4 address with leading zeros
1832 * %pI6 print an IPv6 address with colons
1833 * %pi6 print an IPv6 address without colons
1834 * %pI6c print an IPv6 address as specified by RFC 5952
1835 * %pIS depending on sa_family of 'struct sockaddr *' print IPv4/IPv6 address
1836 * %piS depending on sa_family of 'struct sockaddr *' print IPv4/IPv6 address
1837 * %pU[bBlL] print a UUID/GUID in big or little endian using lower or upper
1839 * %*pE[achnops] print an escaped buffer
1840 * %*ph[CDN] a variable-length hex string with a separator (supports up to 64
1841 * bytes of the input)
1842 * %pC output the name (Common Clock Framework) or address (legacy clock
1843 * framework) of a clock
1844 * %pCn output the name (Common Clock Framework) or address (legacy clock
1845 * framework) of a clock
1846 * %pCr output the current rate of a clock
1849 * ** Please update Documentation/printk-formats.txt when making changes **
1851 * The return value is the number of characters which would
1852 * be generated for the given input, excluding the trailing
1853 * '\0', as per ISO C99. If you want to have the exact
1854 * number of characters written into @buf as return value
1855 * (not including the trailing '\0'), use vscnprintf(). If the
1856 * return is greater than or equal to @size, the resulting
1857 * string is truncated.
1859 * If you're not already dealing with a va_list consider using snprintf().
1861 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1863 unsigned long long num;
1865 struct printf_spec spec = {0};
1867 /* Reject out-of-range values early. Large positive sizes are
1868 used for unknown buffer sizes. */
1869 if (WARN_ON_ONCE(size > INT_MAX))
1875 /* Make sure end is always >= buf */
1882 const char *old_fmt = fmt;
1883 int read = format_decode(fmt, &spec);
1887 switch (spec.type) {
1888 case FORMAT_TYPE_NONE: {
1891 if (copy > end - str)
1893 memcpy(str, old_fmt, copy);
1899 case FORMAT_TYPE_WIDTH:
1900 spec.field_width = va_arg(args, int);
1903 case FORMAT_TYPE_PRECISION:
1904 spec.precision = va_arg(args, int);
1907 case FORMAT_TYPE_CHAR: {
1910 if (!(spec.flags & LEFT)) {
1911 while (--spec.field_width > 0) {
1918 c = (unsigned char) va_arg(args, int);
1922 while (--spec.field_width > 0) {
1930 case FORMAT_TYPE_STR:
1931 str = string(str, end, va_arg(args, char *), spec);
1934 case FORMAT_TYPE_PTR:
1935 str = pointer(fmt, str, end, va_arg(args, void *),
1937 while (isalnum(*fmt))
1941 case FORMAT_TYPE_PERCENT_CHAR:
1947 case FORMAT_TYPE_INVALID:
1954 switch (spec.type) {
1955 case FORMAT_TYPE_LONG_LONG:
1956 num = va_arg(args, long long);
1958 case FORMAT_TYPE_ULONG:
1959 num = va_arg(args, unsigned long);
1961 case FORMAT_TYPE_LONG:
1962 num = va_arg(args, long);
1964 case FORMAT_TYPE_SIZE_T:
1965 if (spec.flags & SIGN)
1966 num = va_arg(args, ssize_t);
1968 num = va_arg(args, size_t);
1970 case FORMAT_TYPE_PTRDIFF:
1971 num = va_arg(args, ptrdiff_t);
1973 case FORMAT_TYPE_UBYTE:
1974 num = (unsigned char) va_arg(args, int);
1976 case FORMAT_TYPE_BYTE:
1977 num = (signed char) va_arg(args, int);
1979 case FORMAT_TYPE_USHORT:
1980 num = (unsigned short) va_arg(args, int);
1982 case FORMAT_TYPE_SHORT:
1983 num = (short) va_arg(args, int);
1985 case FORMAT_TYPE_INT:
1986 num = (int) va_arg(args, int);
1989 num = va_arg(args, unsigned int);
1992 str = number(str, end, num, spec);
2003 /* the trailing null byte doesn't count towards the total */
2007 EXPORT_SYMBOL(vsnprintf);
2010 * vscnprintf - Format a string and place it in a buffer
2011 * @buf: The buffer to place the result into
2012 * @size: The size of the buffer, including the trailing null space
2013 * @fmt: The format string to use
2014 * @args: Arguments for the format string
2016 * The return value is the number of characters which have been written into
2017 * the @buf not including the trailing '\0'. If @size is == 0 the function
2020 * If you're not already dealing with a va_list consider using scnprintf().
2022 * See the vsnprintf() documentation for format string extensions over C99.
2024 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2028 i = vsnprintf(buf, size, fmt, args);
2030 if (likely(i < size))
2036 EXPORT_SYMBOL(vscnprintf);
2039 * snprintf - Format a string and place it in a buffer
2040 * @buf: The buffer to place the result into
2041 * @size: The size of the buffer, including the trailing null space
2042 * @fmt: The format string to use
2043 * @...: Arguments for the format string
2045 * The return value is the number of characters which would be
2046 * generated for the given input, excluding the trailing null,
2047 * as per ISO C99. If the return is greater than or equal to
2048 * @size, the resulting string is truncated.
2050 * See the vsnprintf() documentation for format string extensions over C99.
2052 int snprintf(char *buf, size_t size, const char *fmt, ...)
2057 va_start(args, fmt);
2058 i = vsnprintf(buf, size, fmt, args);
2063 EXPORT_SYMBOL(snprintf);
2066 * scnprintf - 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 written into @buf not including
2073 * the trailing '\0'. If @size is == 0 the function returns 0.
2076 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2081 va_start(args, fmt);
2082 i = vscnprintf(buf, size, fmt, args);
2087 EXPORT_SYMBOL(scnprintf);
2090 * vsprintf - Format a string and place it in a buffer
2091 * @buf: The buffer to place the result into
2092 * @fmt: The format string to use
2093 * @args: Arguments for the format string
2095 * The function returns the number of characters written
2096 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2099 * If you're not already dealing with a va_list consider using sprintf().
2101 * See the vsnprintf() documentation for format string extensions over C99.
2103 int vsprintf(char *buf, const char *fmt, va_list args)
2105 return vsnprintf(buf, INT_MAX, fmt, args);
2107 EXPORT_SYMBOL(vsprintf);
2110 * sprintf - Format a string and place it in a buffer
2111 * @buf: The buffer to place the result into
2112 * @fmt: The format string to use
2113 * @...: Arguments for the format string
2115 * The function returns the number of characters written
2116 * into @buf. Use snprintf() or scnprintf() in order to avoid
2119 * See the vsnprintf() documentation for format string extensions over C99.
2121 int sprintf(char *buf, const char *fmt, ...)
2126 va_start(args, fmt);
2127 i = vsnprintf(buf, INT_MAX, fmt, args);
2132 EXPORT_SYMBOL(sprintf);
2134 #ifdef CONFIG_BINARY_PRINTF
2137 * vbin_printf() - VA arguments to binary data
2138 * bstr_printf() - Binary data to text string
2142 * vbin_printf - Parse a format string and place args' binary value in a buffer
2143 * @bin_buf: The buffer to place args' binary value
2144 * @size: The size of the buffer(by words(32bits), not characters)
2145 * @fmt: The format string to use
2146 * @args: Arguments for the format string
2148 * The format follows C99 vsnprintf, except %n is ignored, and its argument
2151 * The return value is the number of words(32bits) which would be generated for
2155 * If the return value is greater than @size, the resulting bin_buf is NOT
2156 * valid for bstr_printf().
2158 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2160 struct printf_spec spec = {0};
2163 str = (char *)bin_buf;
2164 end = (char *)(bin_buf + size);
2166 #define save_arg(type) \
2168 if (sizeof(type) == 8) { \
2169 unsigned long long value; \
2170 str = PTR_ALIGN(str, sizeof(u32)); \
2171 value = va_arg(args, unsigned long long); \
2172 if (str + sizeof(type) <= end) { \
2173 *(u32 *)str = *(u32 *)&value; \
2174 *(u32 *)(str + 4) = *((u32 *)&value + 1); \
2177 unsigned long value; \
2178 str = PTR_ALIGN(str, sizeof(type)); \
2179 value = va_arg(args, int); \
2180 if (str + sizeof(type) <= end) \
2181 *(typeof(type) *)str = (type)value; \
2183 str += sizeof(type); \
2187 int read = format_decode(fmt, &spec);
2191 switch (spec.type) {
2192 case FORMAT_TYPE_NONE:
2193 case FORMAT_TYPE_INVALID:
2194 case FORMAT_TYPE_PERCENT_CHAR:
2197 case FORMAT_TYPE_WIDTH:
2198 case FORMAT_TYPE_PRECISION:
2202 case FORMAT_TYPE_CHAR:
2206 case FORMAT_TYPE_STR: {
2207 const char *save_str = va_arg(args, char *);
2210 if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2211 || (unsigned long)save_str < PAGE_SIZE)
2212 save_str = "(null)";
2213 len = strlen(save_str) + 1;
2214 if (str + len < end)
2215 memcpy(str, save_str, len);
2220 case FORMAT_TYPE_PTR:
2222 /* skip all alphanumeric pointer suffixes */
2223 while (isalnum(*fmt))
2228 switch (spec.type) {
2230 case FORMAT_TYPE_LONG_LONG:
2231 save_arg(long long);
2233 case FORMAT_TYPE_ULONG:
2234 case FORMAT_TYPE_LONG:
2235 save_arg(unsigned long);
2237 case FORMAT_TYPE_SIZE_T:
2240 case FORMAT_TYPE_PTRDIFF:
2241 save_arg(ptrdiff_t);
2243 case FORMAT_TYPE_UBYTE:
2244 case FORMAT_TYPE_BYTE:
2247 case FORMAT_TYPE_USHORT:
2248 case FORMAT_TYPE_SHORT:
2257 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2260 EXPORT_SYMBOL_GPL(vbin_printf);
2263 * bstr_printf - Format a string from binary arguments and place it in a buffer
2264 * @buf: The buffer to place the result into
2265 * @size: The size of the buffer, including the trailing null space
2266 * @fmt: The format string to use
2267 * @bin_buf: Binary arguments for the format string
2269 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2270 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2271 * a binary buffer that generated by vbin_printf.
2273 * The format follows C99 vsnprintf, but has some extensions:
2274 * see vsnprintf comment for details.
2276 * The return value is the number of characters which would
2277 * be generated for the given input, excluding the trailing
2278 * '\0', as per ISO C99. If you want to have the exact
2279 * number of characters written into @buf as return value
2280 * (not including the trailing '\0'), use vscnprintf(). If the
2281 * return is greater than or equal to @size, the resulting
2282 * string is truncated.
2284 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2286 struct printf_spec spec = {0};
2288 const char *args = (const char *)bin_buf;
2290 if (WARN_ON_ONCE((int) size < 0))
2296 #define get_arg(type) \
2298 typeof(type) value; \
2299 if (sizeof(type) == 8) { \
2300 args = PTR_ALIGN(args, sizeof(u32)); \
2301 *(u32 *)&value = *(u32 *)args; \
2302 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
2304 args = PTR_ALIGN(args, sizeof(type)); \
2305 value = *(typeof(type) *)args; \
2307 args += sizeof(type); \
2311 /* Make sure end is always >= buf */
2318 const char *old_fmt = fmt;
2319 int read = format_decode(fmt, &spec);
2323 switch (spec.type) {
2324 case FORMAT_TYPE_NONE: {
2327 if (copy > end - str)
2329 memcpy(str, old_fmt, copy);
2335 case FORMAT_TYPE_WIDTH:
2336 spec.field_width = get_arg(int);
2339 case FORMAT_TYPE_PRECISION:
2340 spec.precision = get_arg(int);
2343 case FORMAT_TYPE_CHAR: {
2346 if (!(spec.flags & LEFT)) {
2347 while (--spec.field_width > 0) {
2353 c = (unsigned char) get_arg(char);
2357 while (--spec.field_width > 0) {
2365 case FORMAT_TYPE_STR: {
2366 const char *str_arg = args;
2367 args += strlen(str_arg) + 1;
2368 str = string(str, end, (char *)str_arg, spec);
2372 case FORMAT_TYPE_PTR:
2373 str = pointer(fmt, str, end, get_arg(void *), spec);
2374 while (isalnum(*fmt))
2378 case FORMAT_TYPE_PERCENT_CHAR:
2379 case FORMAT_TYPE_INVALID:
2386 unsigned long long num;
2388 switch (spec.type) {
2390 case FORMAT_TYPE_LONG_LONG:
2391 num = get_arg(long long);
2393 case FORMAT_TYPE_ULONG:
2394 case FORMAT_TYPE_LONG:
2395 num = get_arg(unsigned long);
2397 case FORMAT_TYPE_SIZE_T:
2398 num = get_arg(size_t);
2400 case FORMAT_TYPE_PTRDIFF:
2401 num = get_arg(ptrdiff_t);
2403 case FORMAT_TYPE_UBYTE:
2404 num = get_arg(unsigned char);
2406 case FORMAT_TYPE_BYTE:
2407 num = get_arg(signed char);
2409 case FORMAT_TYPE_USHORT:
2410 num = get_arg(unsigned short);
2412 case FORMAT_TYPE_SHORT:
2413 num = get_arg(short);
2415 case FORMAT_TYPE_UINT:
2416 num = get_arg(unsigned int);
2422 str = number(str, end, num, spec);
2424 } /* switch(spec.type) */
2436 /* the trailing null byte doesn't count towards the total */
2439 EXPORT_SYMBOL_GPL(bstr_printf);
2442 * bprintf - Parse a format string and place args' binary value in a buffer
2443 * @bin_buf: The buffer to place args' binary value
2444 * @size: The size of the buffer(by words(32bits), not characters)
2445 * @fmt: The format string to use
2446 * @...: Arguments for the format string
2448 * The function returns the number of words(u32) written
2451 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2456 va_start(args, fmt);
2457 ret = vbin_printf(bin_buf, size, fmt, args);
2462 EXPORT_SYMBOL_GPL(bprintf);
2464 #endif /* CONFIG_BINARY_PRINTF */
2467 * vsscanf - Unformat a buffer into a list of arguments
2468 * @buf: input buffer
2469 * @fmt: format of buffer
2472 int vsscanf(const char *buf, const char *fmt, va_list args)
2474 const char *str = buf;
2482 unsigned long long u;
2488 /* skip any white space in format */
2489 /* white space in format matchs any amount of
2490 * white space, including none, in the input.
2492 if (isspace(*fmt)) {
2493 fmt = skip_spaces(++fmt);
2494 str = skip_spaces(str);
2497 /* anything that is not a conversion must match exactly */
2498 if (*fmt != '%' && *fmt) {
2499 if (*fmt++ != *str++)
2508 /* skip this conversion.
2509 * advance both strings to next white space
2514 while (!isspace(*fmt) && *fmt != '%' && *fmt)
2516 while (!isspace(*str) && *str)
2521 /* get field width */
2523 if (isdigit(*fmt)) {
2524 field_width = skip_atoi(&fmt);
2525 if (field_width <= 0)
2529 /* get conversion qualifier */
2531 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2532 _tolower(*fmt) == 'z') {
2534 if (unlikely(qualifier == *fmt)) {
2535 if (qualifier == 'h') {
2538 } else if (qualifier == 'l') {
2549 /* return number of characters read so far */
2550 *va_arg(args, int *) = str - buf;
2564 char *s = (char *)va_arg(args, char*);
2565 if (field_width == -1)
2569 } while (--field_width > 0 && *str);
2575 char *s = (char *)va_arg(args, char *);
2576 if (field_width == -1)
2577 field_width = SHRT_MAX;
2578 /* first, skip leading white space in buffer */
2579 str = skip_spaces(str);
2581 /* now copy until next white space */
2582 while (*str && !isspace(*str) && field_width--)
2602 /* looking for '%' in str */
2607 /* invalid format; stop here */
2611 /* have some sort of integer conversion.
2612 * first, skip white space in buffer.
2614 str = skip_spaces(str);
2617 if (is_sign && digit == '-')
2621 || (base == 16 && !isxdigit(digit))
2622 || (base == 10 && !isdigit(digit))
2623 || (base == 8 && (!isdigit(digit) || digit > '7'))
2624 || (base == 0 && !isdigit(digit)))
2628 val.s = qualifier != 'L' ?
2629 simple_strtol(str, &next, base) :
2630 simple_strtoll(str, &next, base);
2632 val.u = qualifier != 'L' ?
2633 simple_strtoul(str, &next, base) :
2634 simple_strtoull(str, &next, base);
2636 if (field_width > 0 && next - str > field_width) {
2638 _parse_integer_fixup_radix(str, &base);
2639 while (next - str > field_width) {
2641 val.s = div_s64(val.s, base);
2643 val.u = div_u64(val.u, base);
2648 switch (qualifier) {
2649 case 'H': /* that's 'hh' in format */
2651 *va_arg(args, signed char *) = val.s;
2653 *va_arg(args, unsigned char *) = val.u;
2657 *va_arg(args, short *) = val.s;
2659 *va_arg(args, unsigned short *) = val.u;
2663 *va_arg(args, long *) = val.s;
2665 *va_arg(args, unsigned long *) = val.u;
2669 *va_arg(args, long long *) = val.s;
2671 *va_arg(args, unsigned long long *) = val.u;
2675 *va_arg(args, size_t *) = val.u;
2679 *va_arg(args, int *) = val.s;
2681 *va_arg(args, unsigned int *) = val.u;
2693 EXPORT_SYMBOL(vsscanf);
2696 * sscanf - Unformat a buffer into a list of arguments
2697 * @buf: input buffer
2698 * @fmt: formatting of buffer
2699 * @...: resulting arguments
2701 int sscanf(const char *buf, const char *fmt, ...)
2706 va_start(args, fmt);
2707 i = vsscanf(buf, fmt, args);
2712 EXPORT_SYMBOL(sscanf);