pandora: defconfig: update
[pandora-kernel.git] / lib / vsprintf.c
1 /*
2  *  linux/lib/vsprintf.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
8 /*
9  * Wirzenius wrote this portably, Torvalds fucked it up :-)
10  */
11
12 /*
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
17  */
18
19 #include <stdarg.h>
20 #include <linux/module.h>
21 #include <linux/types.h>
22 #include <linux/string.h>
23 #include <linux/ctype.h>
24 #include <linux/kernel.h>
25 #include <linux/kallsyms.h>
26 #include <linux/uaccess.h>
27 #include <linux/ioport.h>
28 #include <linux/cred.h>
29 #include <net/addrconf.h>
30
31 #include <asm/page.h>           /* for PAGE_SIZE */
32 #include <asm/div64.h>
33 #include <asm/sections.h>       /* for dereference_function_descriptor() */
34
35 #include "kstrtox.h"
36
37 /**
38  * simple_strtoull - convert a string to an unsigned long long
39  * @cp: The start of the string
40  * @endp: A pointer to the end of the parsed string will be placed here
41  * @base: The number base to use
42  */
43 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
44 {
45         unsigned long long result;
46         unsigned int rv;
47
48         cp = _parse_integer_fixup_radix(cp, &base);
49         rv = _parse_integer(cp, base, &result);
50         /* FIXME */
51         cp += (rv & ~KSTRTOX_OVERFLOW);
52
53         if (endp)
54                 *endp = (char *)cp;
55
56         return result;
57 }
58 EXPORT_SYMBOL(simple_strtoull);
59
60 /**
61  * simple_strtoul - convert a string to an unsigned long
62  * @cp: The start of the string
63  * @endp: A pointer to the end of the parsed string will be placed here
64  * @base: The number base to use
65  */
66 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
67 {
68         return simple_strtoull(cp, endp, base);
69 }
70 EXPORT_SYMBOL(simple_strtoul);
71
72 /**
73  * simple_strtol - convert a string to a signed long
74  * @cp: The start of the string
75  * @endp: A pointer to the end of the parsed string will be placed here
76  * @base: The number base to use
77  */
78 long simple_strtol(const char *cp, char **endp, unsigned int base)
79 {
80         if (*cp == '-')
81                 return -simple_strtoul(cp + 1, endp, base);
82
83         return simple_strtoul(cp, endp, base);
84 }
85 EXPORT_SYMBOL(simple_strtol);
86
87 /**
88  * simple_strtoll - convert a string to a signed long long
89  * @cp: The start of the string
90  * @endp: A pointer to the end of the parsed string will be placed here
91  * @base: The number base to use
92  */
93 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
94 {
95         if (*cp == '-')
96                 return -simple_strtoull(cp + 1, endp, base);
97
98         return simple_strtoull(cp, endp, base);
99 }
100 EXPORT_SYMBOL(simple_strtoll);
101
102 static noinline_for_stack
103 int skip_atoi(const char **s)
104 {
105         int i = 0;
106
107         while (isdigit(**s))
108                 i = i*10 + *((*s)++) - '0';
109
110         return i;
111 }
112
113 /* Decimal conversion is by far the most typical, and is used
114  * for /proc and /sys data. This directly impacts e.g. top performance
115  * with many processes running. We optimize it for speed
116  * using code from
117  * http://www.cs.uiowa.edu/~jones/bcd/decimal.html
118  * (with permission from the author, Douglas W. Jones). */
119
120 /* Formats correctly any integer in [0,99999].
121  * Outputs from one to five digits depending on input.
122  * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
123 static noinline_for_stack
124 char *put_dec_trunc(char *buf, unsigned q)
125 {
126         unsigned d3, d2, d1, d0;
127         d1 = (q>>4) & 0xf;
128         d2 = (q>>8) & 0xf;
129         d3 = (q>>12);
130
131         d0 = 6*(d3 + d2 + d1) + (q & 0xf);
132         q = (d0 * 0xcd) >> 11;
133         d0 = d0 - 10*q;
134         *buf++ = d0 + '0'; /* least significant digit */
135         d1 = q + 9*d3 + 5*d2 + d1;
136         if (d1 != 0) {
137                 q = (d1 * 0xcd) >> 11;
138                 d1 = d1 - 10*q;
139                 *buf++ = d1 + '0'; /* next digit */
140
141                 d2 = q + 2*d2;
142                 if ((d2 != 0) || (d3 != 0)) {
143                         q = (d2 * 0xd) >> 7;
144                         d2 = d2 - 10*q;
145                         *buf++ = d2 + '0'; /* next digit */
146
147                         d3 = q + 4*d3;
148                         if (d3 != 0) {
149                                 q = (d3 * 0xcd) >> 11;
150                                 d3 = d3 - 10*q;
151                                 *buf++ = d3 + '0';  /* next digit */
152                                 if (q != 0)
153                                         *buf++ = q + '0'; /* most sign. digit */
154                         }
155                 }
156         }
157
158         return buf;
159 }
160 /* Same with if's removed. Always emits five digits */
161 static noinline_for_stack
162 char *put_dec_full(char *buf, unsigned q)
163 {
164         /* BTW, if q is in [0,9999], 8-bit ints will be enough, */
165         /* but anyway, gcc produces better code with full-sized ints */
166         unsigned d3, d2, d1, d0;
167         d1 = (q>>4) & 0xf;
168         d2 = (q>>8) & 0xf;
169         d3 = (q>>12);
170
171         /*
172          * Possible ways to approx. divide by 10
173          * gcc -O2 replaces multiply with shifts and adds
174          * (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386)
175          * (x * 0x67) >> 10:  1100111
176          * (x * 0x34) >> 9:    110100 - same
177          * (x * 0x1a) >> 8:     11010 - same
178          * (x * 0x0d) >> 7:      1101 - same, shortest code (on i386)
179          */
180         d0 = 6*(d3 + d2 + d1) + (q & 0xf);
181         q = (d0 * 0xcd) >> 11;
182         d0 = d0 - 10*q;
183         *buf++ = d0 + '0';
184         d1 = q + 9*d3 + 5*d2 + d1;
185                 q = (d1 * 0xcd) >> 11;
186                 d1 = d1 - 10*q;
187                 *buf++ = d1 + '0';
188
189                 d2 = q + 2*d2;
190                         q = (d2 * 0xd) >> 7;
191                         d2 = d2 - 10*q;
192                         *buf++ = d2 + '0';
193
194                         d3 = q + 4*d3;
195                                 q = (d3 * 0xcd) >> 11; /* - shorter code */
196                                 /* q = (d3 * 0x67) >> 10; - would also work */
197                                 d3 = d3 - 10*q;
198                                 *buf++ = d3 + '0';
199                                         *buf++ = q + '0';
200
201         return buf;
202 }
203 /* No inlining helps gcc to use registers better */
204 static noinline_for_stack
205 char *put_dec(char *buf, unsigned long long num)
206 {
207         while (1) {
208                 unsigned rem;
209                 if (num < 100000)
210                         return put_dec_trunc(buf, num);
211                 rem = do_div(num, 100000);
212                 buf = put_dec_full(buf, rem);
213         }
214 }
215
216 #define ZEROPAD 1               /* pad with zero */
217 #define SIGN    2               /* unsigned/signed long */
218 #define PLUS    4               /* show plus */
219 #define SPACE   8               /* space if plus */
220 #define LEFT    16              /* left justified */
221 #define SMALL   32              /* use lowercase in hex (must be 32 == 0x20) */
222 #define SPECIAL 64              /* prefix hex with "0x", octal with "0" */
223
224 enum format_type {
225         FORMAT_TYPE_NONE, /* Just a string part */
226         FORMAT_TYPE_WIDTH,
227         FORMAT_TYPE_PRECISION,
228         FORMAT_TYPE_CHAR,
229         FORMAT_TYPE_STR,
230         FORMAT_TYPE_PTR,
231         FORMAT_TYPE_PERCENT_CHAR,
232         FORMAT_TYPE_INVALID,
233         FORMAT_TYPE_LONG_LONG,
234         FORMAT_TYPE_ULONG,
235         FORMAT_TYPE_LONG,
236         FORMAT_TYPE_UBYTE,
237         FORMAT_TYPE_BYTE,
238         FORMAT_TYPE_USHORT,
239         FORMAT_TYPE_SHORT,
240         FORMAT_TYPE_UINT,
241         FORMAT_TYPE_INT,
242         FORMAT_TYPE_NRCHARS,
243         FORMAT_TYPE_SIZE_T,
244         FORMAT_TYPE_PTRDIFF
245 };
246
247 struct printf_spec {
248         u8      type;           /* format_type enum */
249         u8      flags;          /* flags to number() */
250         u8      base;           /* number base, 8, 10 or 16 only */
251         u8      qualifier;      /* number qualifier, one of 'hHlLtzZ' */
252         s16     field_width;    /* width of output field */
253         s16     precision;      /* # of digits/chars */
254 };
255
256 static noinline_for_stack
257 char *number(char *buf, char *end, unsigned long long num,
258              struct printf_spec spec)
259 {
260         /* we are called with base 8, 10 or 16, only, thus don't need "G..."  */
261         static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */
262
263         char tmp[66];
264         char sign;
265         char locase;
266         int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
267         int i;
268
269         /* locase = 0 or 0x20. ORing digits or letters with 'locase'
270          * produces same digits or (maybe lowercased) letters */
271         locase = (spec.flags & SMALL);
272         if (spec.flags & LEFT)
273                 spec.flags &= ~ZEROPAD;
274         sign = 0;
275         if (spec.flags & SIGN) {
276                 if ((signed long long)num < 0) {
277                         sign = '-';
278                         num = -(signed long long)num;
279                         spec.field_width--;
280                 } else if (spec.flags & PLUS) {
281                         sign = '+';
282                         spec.field_width--;
283                 } else if (spec.flags & SPACE) {
284                         sign = ' ';
285                         spec.field_width--;
286                 }
287         }
288         if (need_pfx) {
289                 spec.field_width--;
290                 if (spec.base == 16)
291                         spec.field_width--;
292         }
293
294         /* generate full string in tmp[], in reverse order */
295         i = 0;
296         if (num == 0)
297                 tmp[i++] = '0';
298         /* Generic code, for any base:
299         else do {
300                 tmp[i++] = (digits[do_div(num,base)] | locase);
301         } while (num != 0);
302         */
303         else if (spec.base != 10) { /* 8 or 16 */
304                 int mask = spec.base - 1;
305                 int shift = 3;
306
307                 if (spec.base == 16)
308                         shift = 4;
309                 do {
310                         tmp[i++] = (digits[((unsigned char)num) & mask] | locase);
311                         num >>= shift;
312                 } while (num);
313         } else { /* base 10 */
314                 i = put_dec(tmp, num) - tmp;
315         }
316
317         /* printing 100 using %2d gives "100", not "00" */
318         if (i > spec.precision)
319                 spec.precision = i;
320         /* leading space padding */
321         spec.field_width -= spec.precision;
322         if (!(spec.flags & (ZEROPAD+LEFT))) {
323                 while (--spec.field_width >= 0) {
324                         if (buf < end)
325                                 *buf = ' ';
326                         ++buf;
327                 }
328         }
329         /* sign */
330         if (sign) {
331                 if (buf < end)
332                         *buf = sign;
333                 ++buf;
334         }
335         /* "0x" / "0" prefix */
336         if (need_pfx) {
337                 if (buf < end)
338                         *buf = '0';
339                 ++buf;
340                 if (spec.base == 16) {
341                         if (buf < end)
342                                 *buf = ('X' | locase);
343                         ++buf;
344                 }
345         }
346         /* zero or space padding */
347         if (!(spec.flags & LEFT)) {
348                 char c = (spec.flags & ZEROPAD) ? '0' : ' ';
349                 while (--spec.field_width >= 0) {
350                         if (buf < end)
351                                 *buf = c;
352                         ++buf;
353                 }
354         }
355         /* hmm even more zero padding? */
356         while (i <= --spec.precision) {
357                 if (buf < end)
358                         *buf = '0';
359                 ++buf;
360         }
361         /* actual digits of result */
362         while (--i >= 0) {
363                 if (buf < end)
364                         *buf = tmp[i];
365                 ++buf;
366         }
367         /* trailing space padding */
368         while (--spec.field_width >= 0) {
369                 if (buf < end)
370                         *buf = ' ';
371                 ++buf;
372         }
373
374         return buf;
375 }
376
377 static noinline_for_stack
378 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
379 {
380         int len, i;
381
382         if ((unsigned long)s < PAGE_SIZE)
383                 s = "(null)";
384
385         len = strnlen(s, spec.precision);
386
387         if (!(spec.flags & LEFT)) {
388                 while (len < spec.field_width--) {
389                         if (buf < end)
390                                 *buf = ' ';
391                         ++buf;
392                 }
393         }
394         for (i = 0; i < len; ++i) {
395                 if (buf < end)
396                         *buf = *s;
397                 ++buf; ++s;
398         }
399         while (len < spec.field_width--) {
400                 if (buf < end)
401                         *buf = ' ';
402                 ++buf;
403         }
404
405         return buf;
406 }
407
408 static noinline_for_stack
409 char *symbol_string(char *buf, char *end, void *ptr,
410                     struct printf_spec spec, char ext)
411 {
412         unsigned long value = (unsigned long) ptr;
413 #ifdef CONFIG_KALLSYMS
414         char sym[KSYM_SYMBOL_LEN];
415         if (ext == 'B')
416                 sprint_backtrace(sym, value);
417         else if (ext != 'f' && ext != 's')
418                 sprint_symbol(sym, value);
419         else
420                 kallsyms_lookup(value, NULL, NULL, NULL, sym);
421
422         return string(buf, end, sym, spec);
423 #else
424         spec.field_width = 2 * sizeof(void *);
425         spec.flags |= SPECIAL | SMALL | ZEROPAD;
426         spec.base = 16;
427
428         return number(buf, end, value, spec);
429 #endif
430 }
431
432 static noinline_for_stack
433 char *resource_string(char *buf, char *end, struct resource *res,
434                       struct printf_spec spec, const char *fmt)
435 {
436 #ifndef IO_RSRC_PRINTK_SIZE
437 #define IO_RSRC_PRINTK_SIZE     6
438 #endif
439
440 #ifndef MEM_RSRC_PRINTK_SIZE
441 #define MEM_RSRC_PRINTK_SIZE    10
442 #endif
443         static const struct printf_spec io_spec = {
444                 .base = 16,
445                 .field_width = IO_RSRC_PRINTK_SIZE,
446                 .precision = -1,
447                 .flags = SPECIAL | SMALL | ZEROPAD,
448         };
449         static const struct printf_spec mem_spec = {
450                 .base = 16,
451                 .field_width = MEM_RSRC_PRINTK_SIZE,
452                 .precision = -1,
453                 .flags = SPECIAL | SMALL | ZEROPAD,
454         };
455         static const struct printf_spec bus_spec = {
456                 .base = 16,
457                 .field_width = 2,
458                 .precision = -1,
459                 .flags = SMALL | ZEROPAD,
460         };
461         static const struct printf_spec dec_spec = {
462                 .base = 10,
463                 .precision = -1,
464                 .flags = 0,
465         };
466         static const struct printf_spec str_spec = {
467                 .field_width = -1,
468                 .precision = 10,
469                 .flags = LEFT,
470         };
471         static const struct printf_spec flag_spec = {
472                 .base = 16,
473                 .precision = -1,
474                 .flags = SPECIAL | SMALL,
475         };
476
477         /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
478          * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
479 #define RSRC_BUF_SIZE           ((2 * sizeof(resource_size_t)) + 4)
480 #define FLAG_BUF_SIZE           (2 * sizeof(res->flags))
481 #define DECODED_BUF_SIZE        sizeof("[mem - 64bit pref window disabled]")
482 #define RAW_BUF_SIZE            sizeof("[mem - flags 0x]")
483         char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
484                      2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
485
486         char *p = sym, *pend = sym + sizeof(sym);
487         int decode = (fmt[0] == 'R') ? 1 : 0;
488         const struct printf_spec *specp;
489
490         *p++ = '[';
491         if (res->flags & IORESOURCE_IO) {
492                 p = string(p, pend, "io  ", str_spec);
493                 specp = &io_spec;
494         } else if (res->flags & IORESOURCE_MEM) {
495                 p = string(p, pend, "mem ", str_spec);
496                 specp = &mem_spec;
497         } else if (res->flags & IORESOURCE_IRQ) {
498                 p = string(p, pend, "irq ", str_spec);
499                 specp = &dec_spec;
500         } else if (res->flags & IORESOURCE_DMA) {
501                 p = string(p, pend, "dma ", str_spec);
502                 specp = &dec_spec;
503         } else if (res->flags & IORESOURCE_BUS) {
504                 p = string(p, pend, "bus ", str_spec);
505                 specp = &bus_spec;
506         } else {
507                 p = string(p, pend, "??? ", str_spec);
508                 specp = &mem_spec;
509                 decode = 0;
510         }
511         p = number(p, pend, res->start, *specp);
512         if (res->start != res->end) {
513                 *p++ = '-';
514                 p = number(p, pend, res->end, *specp);
515         }
516         if (decode) {
517                 if (res->flags & IORESOURCE_MEM_64)
518                         p = string(p, pend, " 64bit", str_spec);
519                 if (res->flags & IORESOURCE_PREFETCH)
520                         p = string(p, pend, " pref", str_spec);
521                 if (res->flags & IORESOURCE_WINDOW)
522                         p = string(p, pend, " window", str_spec);
523                 if (res->flags & IORESOURCE_DISABLED)
524                         p = string(p, pend, " disabled", str_spec);
525         } else {
526                 p = string(p, pend, " flags ", str_spec);
527                 p = number(p, pend, res->flags, flag_spec);
528         }
529         *p++ = ']';
530         *p = '\0';
531
532         return string(buf, end, sym, spec);
533 }
534
535 static noinline_for_stack
536 char *mac_address_string(char *buf, char *end, u8 *addr,
537                          struct printf_spec spec, const char *fmt)
538 {
539         char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
540         char *p = mac_addr;
541         int i;
542         char separator;
543
544         if (fmt[1] == 'F') {            /* FDDI canonical format */
545                 separator = '-';
546         } else {
547                 separator = ':';
548         }
549
550         for (i = 0; i < 6; i++) {
551                 p = hex_byte_pack(p, addr[i]);
552                 if (fmt[0] == 'M' && i != 5)
553                         *p++ = separator;
554         }
555         *p = '\0';
556
557         return string(buf, end, mac_addr, spec);
558 }
559
560 static noinline_for_stack
561 char *ip4_string(char *p, const u8 *addr, const char *fmt)
562 {
563         int i;
564         bool leading_zeros = (fmt[0] == 'i');
565         int index;
566         int step;
567
568         switch (fmt[2]) {
569         case 'h':
570 #ifdef __BIG_ENDIAN
571                 index = 0;
572                 step = 1;
573 #else
574                 index = 3;
575                 step = -1;
576 #endif
577                 break;
578         case 'l':
579                 index = 3;
580                 step = -1;
581                 break;
582         case 'n':
583         case 'b':
584         default:
585                 index = 0;
586                 step = 1;
587                 break;
588         }
589         for (i = 0; i < 4; i++) {
590                 char temp[3];   /* hold each IP quad in reverse order */
591                 int digits = put_dec_trunc(temp, addr[index]) - temp;
592                 if (leading_zeros) {
593                         if (digits < 3)
594                                 *p++ = '0';
595                         if (digits < 2)
596                                 *p++ = '0';
597                 }
598                 /* reverse the digits in the quad */
599                 while (digits--)
600                         *p++ = temp[digits];
601                 if (i < 3)
602                         *p++ = '.';
603                 index += step;
604         }
605         *p = '\0';
606
607         return p;
608 }
609
610 static noinline_for_stack
611 char *ip6_compressed_string(char *p, const char *addr)
612 {
613         int i, j, range;
614         unsigned char zerolength[8];
615         int longest = 1;
616         int colonpos = -1;
617         u16 word;
618         u8 hi, lo;
619         bool needcolon = false;
620         bool useIPv4;
621         struct in6_addr in6;
622
623         memcpy(&in6, addr, sizeof(struct in6_addr));
624
625         useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
626
627         memset(zerolength, 0, sizeof(zerolength));
628
629         if (useIPv4)
630                 range = 6;
631         else
632                 range = 8;
633
634         /* find position of longest 0 run */
635         for (i = 0; i < range; i++) {
636                 for (j = i; j < range; j++) {
637                         if (in6.s6_addr16[j] != 0)
638                                 break;
639                         zerolength[i]++;
640                 }
641         }
642         for (i = 0; i < range; i++) {
643                 if (zerolength[i] > longest) {
644                         longest = zerolength[i];
645                         colonpos = i;
646                 }
647         }
648         if (longest == 1)               /* don't compress a single 0 */
649                 colonpos = -1;
650
651         /* emit address */
652         for (i = 0; i < range; i++) {
653                 if (i == colonpos) {
654                         if (needcolon || i == 0)
655                                 *p++ = ':';
656                         *p++ = ':';
657                         needcolon = false;
658                         i += longest - 1;
659                         continue;
660                 }
661                 if (needcolon) {
662                         *p++ = ':';
663                         needcolon = false;
664                 }
665                 /* hex u16 without leading 0s */
666                 word = ntohs(in6.s6_addr16[i]);
667                 hi = word >> 8;
668                 lo = word & 0xff;
669                 if (hi) {
670                         if (hi > 0x0f)
671                                 p = hex_byte_pack(p, hi);
672                         else
673                                 *p++ = hex_asc_lo(hi);
674                         p = hex_byte_pack(p, lo);
675                 }
676                 else if (lo > 0x0f)
677                         p = hex_byte_pack(p, lo);
678                 else
679                         *p++ = hex_asc_lo(lo);
680                 needcolon = true;
681         }
682
683         if (useIPv4) {
684                 if (needcolon)
685                         *p++ = ':';
686                 p = ip4_string(p, &in6.s6_addr[12], "I4");
687         }
688         *p = '\0';
689
690         return p;
691 }
692
693 static noinline_for_stack
694 char *ip6_string(char *p, const char *addr, const char *fmt)
695 {
696         int i;
697
698         for (i = 0; i < 8; i++) {
699                 p = hex_byte_pack(p, *addr++);
700                 p = hex_byte_pack(p, *addr++);
701                 if (fmt[0] == 'I' && i != 7)
702                         *p++ = ':';
703         }
704         *p = '\0';
705
706         return p;
707 }
708
709 static noinline_for_stack
710 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
711                       struct printf_spec spec, const char *fmt)
712 {
713         char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
714
715         if (fmt[0] == 'I' && fmt[2] == 'c')
716                 ip6_compressed_string(ip6_addr, addr);
717         else
718                 ip6_string(ip6_addr, addr, fmt);
719
720         return string(buf, end, ip6_addr, spec);
721 }
722
723 static noinline_for_stack
724 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
725                       struct printf_spec spec, const char *fmt)
726 {
727         char ip4_addr[sizeof("255.255.255.255")];
728
729         ip4_string(ip4_addr, addr, fmt);
730
731         return string(buf, end, ip4_addr, spec);
732 }
733
734 static noinline_for_stack
735 char *uuid_string(char *buf, char *end, const u8 *addr,
736                   struct printf_spec spec, const char *fmt)
737 {
738         char uuid[sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")];
739         char *p = uuid;
740         int i;
741         static const u8 be[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
742         static const u8 le[16] = {3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15};
743         const u8 *index = be;
744         bool uc = false;
745
746         switch (*(++fmt)) {
747         case 'L':
748                 uc = true;              /* fall-through */
749         case 'l':
750                 index = le;
751                 break;
752         case 'B':
753                 uc = true;
754                 break;
755         }
756
757         for (i = 0; i < 16; i++) {
758                 p = hex_byte_pack(p, addr[index[i]]);
759                 switch (i) {
760                 case 3:
761                 case 5:
762                 case 7:
763                 case 9:
764                         *p++ = '-';
765                         break;
766                 }
767         }
768
769         *p = 0;
770
771         if (uc) {
772                 p = uuid;
773                 do {
774                         *p = toupper(*p);
775                 } while (*(++p));
776         }
777
778         return string(buf, end, uuid, spec);
779 }
780
781 int kptr_restrict __read_mostly;
782
783 /*
784  * Show a '%p' thing.  A kernel extension is that the '%p' is followed
785  * by an extra set of alphanumeric characters that are extended format
786  * specifiers.
787  *
788  * Right now we handle:
789  *
790  * - 'F' For symbolic function descriptor pointers with offset
791  * - 'f' For simple symbolic function names without offset
792  * - 'S' For symbolic direct pointers with offset
793  * - 's' For symbolic direct pointers without offset
794  * - 'B' For backtraced symbolic direct pointers with offset
795  * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
796  * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
797  * - 'M' For a 6-byte MAC address, it prints the address in the
798  *       usual colon-separated hex notation
799  * - 'm' For a 6-byte MAC address, it prints the hex address without colons
800  * - 'MF' For a 6-byte MAC FDDI address, it prints the address
801  *       with a dash-separated hex notation
802  * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
803  *       IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
804  *       IPv6 uses colon separated network-order 16 bit hex with leading 0's
805  * - 'i' [46] for 'raw' IPv4/IPv6 addresses
806  *       IPv6 omits the colons (01020304...0f)
807  *       IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
808  * - '[Ii]4[hnbl]' IPv4 addresses in host, network, big or little endian order
809  * - 'I6c' for IPv6 addresses printed as specified by
810  *       http://tools.ietf.org/html/rfc5952
811  * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
812  *       "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
813  *       Options for %pU are:
814  *         b big endian lower case hex (default)
815  *         B big endian UPPER case hex
816  *         l little endian lower case hex
817  *         L little endian UPPER case hex
818  *           big endian output byte order is:
819  *             [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
820  *           little endian output byte order is:
821  *             [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
822  * - 'V' For a struct va_format which contains a format string * and va_list *,
823  *       call vsnprintf(->format, *->va_list).
824  *       Implements a "recursive vsnprintf".
825  *       Do not use this feature without some mechanism to verify the
826  *       correctness of the format string and va_list arguments.
827  * - 'K' For a kernel pointer that should be hidden from unprivileged users
828  *
829  * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
830  * function pointers are really function descriptors, which contain a
831  * pointer to the real address.
832  */
833 static noinline_for_stack
834 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
835               struct printf_spec spec)
836 {
837         if (!ptr && *fmt != 'K') {
838                 /*
839                  * Print (null) with the same width as a pointer so it makes
840                  * tabular output look nice.
841                  */
842                 if (spec.field_width == -1)
843                         spec.field_width = 2 * sizeof(void *);
844                 return string(buf, end, "(null)", spec);
845         }
846
847         switch (*fmt) {
848         case 'F':
849         case 'f':
850                 ptr = dereference_function_descriptor(ptr);
851                 /* Fallthrough */
852         case 'S':
853         case 's':
854         case 'B':
855                 return symbol_string(buf, end, ptr, spec, *fmt);
856         case 'R':
857         case 'r':
858                 return resource_string(buf, end, ptr, spec, fmt);
859         case 'M':                       /* Colon separated: 00:01:02:03:04:05 */
860         case 'm':                       /* Contiguous: 000102030405 */
861                                         /* [mM]F (FDDI, bit reversed) */
862                 return mac_address_string(buf, end, ptr, spec, fmt);
863         case 'I':                       /* Formatted IP supported
864                                          * 4:   1.2.3.4
865                                          * 6:   0001:0203:...:0708
866                                          * 6c:  1::708 or 1::1.2.3.4
867                                          */
868         case 'i':                       /* Contiguous:
869                                          * 4:   001.002.003.004
870                                          * 6:   000102...0f
871                                          */
872                 switch (fmt[1]) {
873                 case '6':
874                         return ip6_addr_string(buf, end, ptr, spec, fmt);
875                 case '4':
876                         return ip4_addr_string(buf, end, ptr, spec, fmt);
877                 }
878                 break;
879         case 'U':
880                 return uuid_string(buf, end, ptr, spec, fmt);
881         case 'V':
882                 return buf + vsnprintf(buf, end > buf ? end - buf : 0,
883                                        ((struct va_format *)ptr)->fmt,
884                                        *(((struct va_format *)ptr)->va));
885         case 'K':
886                 /*
887                  * %pK cannot be used in IRQ context because its test
888                  * for CAP_SYSLOG would be meaningless.
889                  */
890                 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
891                                       in_nmi())) {
892                         if (spec.field_width == -1)
893                                 spec.field_width = 2 * sizeof(void *);
894                         return string(buf, end, "pK-error", spec);
895                 }
896
897                 switch (kptr_restrict) {
898                 case 0:
899                         /* Always print %pK values */
900                         break;
901                 case 1: {
902                         /*
903                          * Only print the real pointer value if the current
904                          * process has CAP_SYSLOG and is running with the
905                          * same credentials it started with. This is because
906                          * access to files is checked at open() time, but %pK
907                          * checks permission at read() time. We don't want to
908                          * leak pointer values if a binary opens a file using
909                          * %pK and then elevates privileges before reading it.
910                          */
911                         const struct cred *cred = current_cred();
912
913                         if (!has_capability_noaudit(current, CAP_SYSLOG) ||
914                             cred->euid != cred->uid ||
915                             cred->egid != cred->gid)
916                                 ptr = NULL;
917                         break;
918                 }
919                 case 2:
920                 default:
921                         /* Always print 0's for %pK */
922                         ptr = NULL;
923                         break;
924                 }
925                 break;
926         }
927         spec.flags |= SMALL;
928         if (spec.field_width == -1) {
929                 spec.field_width = 2 * sizeof(void *);
930                 spec.flags |= ZEROPAD;
931         }
932         spec.base = 16;
933
934         return number(buf, end, (unsigned long) ptr, spec);
935 }
936
937 /*
938  * Helper function to decode printf style format.
939  * Each call decode a token from the format and return the
940  * number of characters read (or likely the delta where it wants
941  * to go on the next call).
942  * The decoded token is returned through the parameters
943  *
944  * 'h', 'l', or 'L' for integer fields
945  * 'z' support added 23/7/1999 S.H.
946  * 'z' changed to 'Z' --davidm 1/25/99
947  * 't' added for ptrdiff_t
948  *
949  * @fmt: the format string
950  * @type of the token returned
951  * @flags: various flags such as +, -, # tokens..
952  * @field_width: overwritten width
953  * @base: base of the number (octal, hex, ...)
954  * @precision: precision of a number
955  * @qualifier: qualifier of a number (long, size_t, ...)
956  */
957 static noinline_for_stack
958 int format_decode(const char *fmt, struct printf_spec *spec)
959 {
960         const char *start = fmt;
961
962         /* we finished early by reading the field width */
963         if (spec->type == FORMAT_TYPE_WIDTH) {
964                 if (spec->field_width < 0) {
965                         spec->field_width = -spec->field_width;
966                         spec->flags |= LEFT;
967                 }
968                 spec->type = FORMAT_TYPE_NONE;
969                 goto precision;
970         }
971
972         /* we finished early by reading the precision */
973         if (spec->type == FORMAT_TYPE_PRECISION) {
974                 if (spec->precision < 0)
975                         spec->precision = 0;
976
977                 spec->type = FORMAT_TYPE_NONE;
978                 goto qualifier;
979         }
980
981         /* By default */
982         spec->type = FORMAT_TYPE_NONE;
983
984         for (; *fmt ; ++fmt) {
985                 if (*fmt == '%')
986                         break;
987         }
988
989         /* Return the current non-format string */
990         if (fmt != start || !*fmt)
991                 return fmt - start;
992
993         /* Process flags */
994         spec->flags = 0;
995
996         while (1) { /* this also skips first '%' */
997                 bool found = true;
998
999                 ++fmt;
1000
1001                 switch (*fmt) {
1002                 case '-': spec->flags |= LEFT;    break;
1003                 case '+': spec->flags |= PLUS;    break;
1004                 case ' ': spec->flags |= SPACE;   break;
1005                 case '#': spec->flags |= SPECIAL; break;
1006                 case '0': spec->flags |= ZEROPAD; break;
1007                 default:  found = false;
1008                 }
1009
1010                 if (!found)
1011                         break;
1012         }
1013
1014         /* get field width */
1015         spec->field_width = -1;
1016
1017         if (isdigit(*fmt))
1018                 spec->field_width = skip_atoi(&fmt);
1019         else if (*fmt == '*') {
1020                 /* it's the next argument */
1021                 spec->type = FORMAT_TYPE_WIDTH;
1022                 return ++fmt - start;
1023         }
1024
1025 precision:
1026         /* get the precision */
1027         spec->precision = -1;
1028         if (*fmt == '.') {
1029                 ++fmt;
1030                 if (isdigit(*fmt)) {
1031                         spec->precision = skip_atoi(&fmt);
1032                         if (spec->precision < 0)
1033                                 spec->precision = 0;
1034                 } else if (*fmt == '*') {
1035                         /* it's the next argument */
1036                         spec->type = FORMAT_TYPE_PRECISION;
1037                         return ++fmt - start;
1038                 }
1039         }
1040
1041 qualifier:
1042         /* get the conversion qualifier */
1043         spec->qualifier = -1;
1044         if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1045             _tolower(*fmt) == 'z' || *fmt == 't') {
1046                 spec->qualifier = *fmt++;
1047                 if (unlikely(spec->qualifier == *fmt)) {
1048                         if (spec->qualifier == 'l') {
1049                                 spec->qualifier = 'L';
1050                                 ++fmt;
1051                         } else if (spec->qualifier == 'h') {
1052                                 spec->qualifier = 'H';
1053                                 ++fmt;
1054                         }
1055                 }
1056         }
1057
1058         /* default base */
1059         spec->base = 10;
1060         switch (*fmt) {
1061         case 'c':
1062                 spec->type = FORMAT_TYPE_CHAR;
1063                 return ++fmt - start;
1064
1065         case 's':
1066                 spec->type = FORMAT_TYPE_STR;
1067                 return ++fmt - start;
1068
1069         case 'p':
1070                 spec->type = FORMAT_TYPE_PTR;
1071                 return fmt - start;
1072                 /* skip alnum */
1073
1074         case 'n':
1075                 spec->type = FORMAT_TYPE_NRCHARS;
1076                 return ++fmt - start;
1077
1078         case '%':
1079                 spec->type = FORMAT_TYPE_PERCENT_CHAR;
1080                 return ++fmt - start;
1081
1082         /* integer number formats - set up the flags and "break" */
1083         case 'o':
1084                 spec->base = 8;
1085                 break;
1086
1087         case 'x':
1088                 spec->flags |= SMALL;
1089
1090         case 'X':
1091                 spec->base = 16;
1092                 break;
1093
1094         case 'd':
1095         case 'i':
1096                 spec->flags |= SIGN;
1097         case 'u':
1098                 break;
1099
1100         default:
1101                 spec->type = FORMAT_TYPE_INVALID;
1102                 return fmt - start;
1103         }
1104
1105         if (spec->qualifier == 'L')
1106                 spec->type = FORMAT_TYPE_LONG_LONG;
1107         else if (spec->qualifier == 'l') {
1108                 if (spec->flags & SIGN)
1109                         spec->type = FORMAT_TYPE_LONG;
1110                 else
1111                         spec->type = FORMAT_TYPE_ULONG;
1112         } else if (_tolower(spec->qualifier) == 'z') {
1113                 spec->type = FORMAT_TYPE_SIZE_T;
1114         } else if (spec->qualifier == 't') {
1115                 spec->type = FORMAT_TYPE_PTRDIFF;
1116         } else if (spec->qualifier == 'H') {
1117                 if (spec->flags & SIGN)
1118                         spec->type = FORMAT_TYPE_BYTE;
1119                 else
1120                         spec->type = FORMAT_TYPE_UBYTE;
1121         } else if (spec->qualifier == 'h') {
1122                 if (spec->flags & SIGN)
1123                         spec->type = FORMAT_TYPE_SHORT;
1124                 else
1125                         spec->type = FORMAT_TYPE_USHORT;
1126         } else {
1127                 if (spec->flags & SIGN)
1128                         spec->type = FORMAT_TYPE_INT;
1129                 else
1130                         spec->type = FORMAT_TYPE_UINT;
1131         }
1132
1133         return ++fmt - start;
1134 }
1135
1136 /**
1137  * vsnprintf - Format a string and place it in a buffer
1138  * @buf: The buffer to place the result into
1139  * @size: The size of the buffer, including the trailing null space
1140  * @fmt: The format string to use
1141  * @args: Arguments for the format string
1142  *
1143  * This function follows C99 vsnprintf, but has some extensions:
1144  * %pS output the name of a text symbol with offset
1145  * %ps output the name of a text symbol without offset
1146  * %pF output the name of a function pointer with its offset
1147  * %pf output the name of a function pointer without its offset
1148  * %pB output the name of a backtrace symbol with its offset
1149  * %pR output the address range in a struct resource with decoded flags
1150  * %pr output the address range in a struct resource with raw flags
1151  * %pM output a 6-byte MAC address with colons
1152  * %pm output a 6-byte MAC address without colons
1153  * %pI4 print an IPv4 address without leading zeros
1154  * %pi4 print an IPv4 address with leading zeros
1155  * %pI6 print an IPv6 address with colons
1156  * %pi6 print an IPv6 address without colons
1157  * %pI6c print an IPv6 address as specified by RFC 5952
1158  * %pU[bBlL] print a UUID/GUID in big or little endian using lower or upper
1159  *   case.
1160  * %n is ignored
1161  *
1162  * The return value is the number of characters which would
1163  * be generated for the given input, excluding the trailing
1164  * '\0', as per ISO C99. If you want to have the exact
1165  * number of characters written into @buf as return value
1166  * (not including the trailing '\0'), use vscnprintf(). If the
1167  * return is greater than or equal to @size, the resulting
1168  * string is truncated.
1169  *
1170  * If you're not already dealing with a va_list consider using snprintf().
1171  */
1172 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1173 {
1174         unsigned long long num;
1175         char *str, *end;
1176         struct printf_spec spec = {0};
1177
1178         /* Reject out-of-range values early.  Large positive sizes are
1179            used for unknown buffer sizes. */
1180         if (WARN_ON_ONCE(size > INT_MAX))
1181                 return 0;
1182
1183         str = buf;
1184         end = buf + size;
1185
1186         /* Make sure end is always >= buf */
1187         if (end < buf) {
1188                 end = ((void *)-1);
1189                 size = end - buf;
1190         }
1191
1192         while (*fmt) {
1193                 const char *old_fmt = fmt;
1194                 int read = format_decode(fmt, &spec);
1195
1196                 fmt += read;
1197
1198                 switch (spec.type) {
1199                 case FORMAT_TYPE_NONE: {
1200                         int copy = read;
1201                         if (str < end) {
1202                                 if (copy > end - str)
1203                                         copy = end - str;
1204                                 memcpy(str, old_fmt, copy);
1205                         }
1206                         str += read;
1207                         break;
1208                 }
1209
1210                 case FORMAT_TYPE_WIDTH:
1211                         spec.field_width = va_arg(args, int);
1212                         break;
1213
1214                 case FORMAT_TYPE_PRECISION:
1215                         spec.precision = va_arg(args, int);
1216                         break;
1217
1218                 case FORMAT_TYPE_CHAR: {
1219                         char c;
1220
1221                         if (!(spec.flags & LEFT)) {
1222                                 while (--spec.field_width > 0) {
1223                                         if (str < end)
1224                                                 *str = ' ';
1225                                         ++str;
1226
1227                                 }
1228                         }
1229                         c = (unsigned char) va_arg(args, int);
1230                         if (str < end)
1231                                 *str = c;
1232                         ++str;
1233                         while (--spec.field_width > 0) {
1234                                 if (str < end)
1235                                         *str = ' ';
1236                                 ++str;
1237                         }
1238                         break;
1239                 }
1240
1241                 case FORMAT_TYPE_STR:
1242                         str = string(str, end, va_arg(args, char *), spec);
1243                         break;
1244
1245                 case FORMAT_TYPE_PTR:
1246                         str = pointer(fmt+1, str, end, va_arg(args, void *),
1247                                       spec);
1248                         while (isalnum(*fmt))
1249                                 fmt++;
1250                         break;
1251
1252                 case FORMAT_TYPE_PERCENT_CHAR:
1253                         if (str < end)
1254                                 *str = '%';
1255                         ++str;
1256                         break;
1257
1258                 case FORMAT_TYPE_INVALID:
1259                         if (str < end)
1260                                 *str = '%';
1261                         ++str;
1262                         break;
1263
1264                 case FORMAT_TYPE_NRCHARS: {
1265                         u8 qualifier = spec.qualifier;
1266
1267                         if (qualifier == 'l') {
1268                                 long *ip = va_arg(args, long *);
1269                                 *ip = (str - buf);
1270                         } else if (_tolower(qualifier) == 'z') {
1271                                 size_t *ip = va_arg(args, size_t *);
1272                                 *ip = (str - buf);
1273                         } else {
1274                                 int *ip = va_arg(args, int *);
1275                                 *ip = (str - buf);
1276                         }
1277                         break;
1278                 }
1279
1280                 default:
1281                         switch (spec.type) {
1282                         case FORMAT_TYPE_LONG_LONG:
1283                                 num = va_arg(args, long long);
1284                                 break;
1285                         case FORMAT_TYPE_ULONG:
1286                                 num = va_arg(args, unsigned long);
1287                                 break;
1288                         case FORMAT_TYPE_LONG:
1289                                 num = va_arg(args, long);
1290                                 break;
1291                         case FORMAT_TYPE_SIZE_T:
1292                                 num = va_arg(args, size_t);
1293                                 break;
1294                         case FORMAT_TYPE_PTRDIFF:
1295                                 num = va_arg(args, ptrdiff_t);
1296                                 break;
1297                         case FORMAT_TYPE_UBYTE:
1298                                 num = (unsigned char) va_arg(args, int);
1299                                 break;
1300                         case FORMAT_TYPE_BYTE:
1301                                 num = (signed char) va_arg(args, int);
1302                                 break;
1303                         case FORMAT_TYPE_USHORT:
1304                                 num = (unsigned short) va_arg(args, int);
1305                                 break;
1306                         case FORMAT_TYPE_SHORT:
1307                                 num = (short) va_arg(args, int);
1308                                 break;
1309                         case FORMAT_TYPE_INT:
1310                                 num = (int) va_arg(args, int);
1311                                 break;
1312                         default:
1313                                 num = va_arg(args, unsigned int);
1314                         }
1315
1316                         str = number(str, end, num, spec);
1317                 }
1318         }
1319
1320         if (size > 0) {
1321                 if (str < end)
1322                         *str = '\0';
1323                 else
1324                         end[-1] = '\0';
1325         }
1326
1327         /* the trailing null byte doesn't count towards the total */
1328         return str-buf;
1329
1330 }
1331 EXPORT_SYMBOL(vsnprintf);
1332
1333 /**
1334  * vscnprintf - Format a string and place it in a buffer
1335  * @buf: The buffer to place the result into
1336  * @size: The size of the buffer, including the trailing null space
1337  * @fmt: The format string to use
1338  * @args: Arguments for the format string
1339  *
1340  * The return value is the number of characters which have been written into
1341  * the @buf not including the trailing '\0'. If @size is == 0 the function
1342  * returns 0.
1343  *
1344  * If you're not already dealing with a va_list consider using scnprintf().
1345  *
1346  * See the vsnprintf() documentation for format string extensions over C99.
1347  */
1348 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
1349 {
1350         int i;
1351
1352         i = vsnprintf(buf, size, fmt, args);
1353
1354         if (likely(i < size))
1355                 return i;
1356         if (size != 0)
1357                 return size - 1;
1358         return 0;
1359 }
1360 EXPORT_SYMBOL(vscnprintf);
1361
1362 /**
1363  * snprintf - Format a string and place it in a buffer
1364  * @buf: The buffer to place the result into
1365  * @size: The size of the buffer, including the trailing null space
1366  * @fmt: The format string to use
1367  * @...: Arguments for the format string
1368  *
1369  * The return value is the number of characters which would be
1370  * generated for the given input, excluding the trailing null,
1371  * as per ISO C99.  If the return is greater than or equal to
1372  * @size, the resulting string is truncated.
1373  *
1374  * See the vsnprintf() documentation for format string extensions over C99.
1375  */
1376 int snprintf(char *buf, size_t size, const char *fmt, ...)
1377 {
1378         va_list args;
1379         int i;
1380
1381         va_start(args, fmt);
1382         i = vsnprintf(buf, size, fmt, args);
1383         va_end(args);
1384
1385         return i;
1386 }
1387 EXPORT_SYMBOL(snprintf);
1388
1389 /**
1390  * scnprintf - Format a string and place it in a buffer
1391  * @buf: The buffer to place the result into
1392  * @size: The size of the buffer, including the trailing null space
1393  * @fmt: The format string to use
1394  * @...: Arguments for the format string
1395  *
1396  * The return value is the number of characters written into @buf not including
1397  * the trailing '\0'. If @size is == 0 the function returns 0.
1398  */
1399
1400 int scnprintf(char *buf, size_t size, const char *fmt, ...)
1401 {
1402         va_list args;
1403         int i;
1404
1405         va_start(args, fmt);
1406         i = vscnprintf(buf, size, fmt, args);
1407         va_end(args);
1408
1409         return i;
1410 }
1411 EXPORT_SYMBOL(scnprintf);
1412
1413 /**
1414  * vsprintf - Format a string and place it in a buffer
1415  * @buf: The buffer to place the result into
1416  * @fmt: The format string to use
1417  * @args: Arguments for the format string
1418  *
1419  * The function returns the number of characters written
1420  * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
1421  * buffer overflows.
1422  *
1423  * If you're not already dealing with a va_list consider using sprintf().
1424  *
1425  * See the vsnprintf() documentation for format string extensions over C99.
1426  */
1427 int vsprintf(char *buf, const char *fmt, va_list args)
1428 {
1429         return vsnprintf(buf, INT_MAX, fmt, args);
1430 }
1431 EXPORT_SYMBOL(vsprintf);
1432
1433 /**
1434  * sprintf - Format a string and place it in a buffer
1435  * @buf: The buffer to place the result into
1436  * @fmt: The format string to use
1437  * @...: Arguments for the format string
1438  *
1439  * The function returns the number of characters written
1440  * into @buf. Use snprintf() or scnprintf() in order to avoid
1441  * buffer overflows.
1442  *
1443  * See the vsnprintf() documentation for format string extensions over C99.
1444  */
1445 int sprintf(char *buf, const char *fmt, ...)
1446 {
1447         va_list args;
1448         int i;
1449
1450         va_start(args, fmt);
1451         i = vsnprintf(buf, INT_MAX, fmt, args);
1452         va_end(args);
1453
1454         return i;
1455 }
1456 EXPORT_SYMBOL(sprintf);
1457
1458 #ifdef CONFIG_BINARY_PRINTF
1459 /*
1460  * bprintf service:
1461  * vbin_printf() - VA arguments to binary data
1462  * bstr_printf() - Binary data to text string
1463  */
1464
1465 /**
1466  * vbin_printf - Parse a format string and place args' binary value in a buffer
1467  * @bin_buf: The buffer to place args' binary value
1468  * @size: The size of the buffer(by words(32bits), not characters)
1469  * @fmt: The format string to use
1470  * @args: Arguments for the format string
1471  *
1472  * The format follows C99 vsnprintf, except %n is ignored, and its argument
1473  * is skiped.
1474  *
1475  * The return value is the number of words(32bits) which would be generated for
1476  * the given input.
1477  *
1478  * NOTE:
1479  * If the return value is greater than @size, the resulting bin_buf is NOT
1480  * valid for bstr_printf().
1481  */
1482 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
1483 {
1484         struct printf_spec spec = {0};
1485         char *str, *end;
1486
1487         str = (char *)bin_buf;
1488         end = (char *)(bin_buf + size);
1489
1490 #define save_arg(type)                                                  \
1491 do {                                                                    \
1492         if (sizeof(type) == 8) {                                        \
1493                 unsigned long long value;                               \
1494                 str = PTR_ALIGN(str, sizeof(u32));                      \
1495                 value = va_arg(args, unsigned long long);               \
1496                 if (str + sizeof(type) <= end) {                        \
1497                         *(u32 *)str = *(u32 *)&value;                   \
1498                         *(u32 *)(str + 4) = *((u32 *)&value + 1);       \
1499                 }                                                       \
1500         } else {                                                        \
1501                 unsigned long value;                                    \
1502                 str = PTR_ALIGN(str, sizeof(type));                     \
1503                 value = va_arg(args, int);                              \
1504                 if (str + sizeof(type) <= end)                          \
1505                         *(typeof(type) *)str = (type)value;             \
1506         }                                                               \
1507         str += sizeof(type);                                            \
1508 } while (0)
1509
1510         while (*fmt) {
1511                 int read = format_decode(fmt, &spec);
1512
1513                 fmt += read;
1514
1515                 switch (spec.type) {
1516                 case FORMAT_TYPE_NONE:
1517                 case FORMAT_TYPE_INVALID:
1518                 case FORMAT_TYPE_PERCENT_CHAR:
1519                         break;
1520
1521                 case FORMAT_TYPE_WIDTH:
1522                 case FORMAT_TYPE_PRECISION:
1523                         save_arg(int);
1524                         break;
1525
1526                 case FORMAT_TYPE_CHAR:
1527                         save_arg(char);
1528                         break;
1529
1530                 case FORMAT_TYPE_STR: {
1531                         const char *save_str = va_arg(args, char *);
1532                         size_t len;
1533
1534                         if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
1535                                         || (unsigned long)save_str < PAGE_SIZE)
1536                                 save_str = "(null)";
1537                         len = strlen(save_str) + 1;
1538                         if (str + len < end)
1539                                 memcpy(str, save_str, len);
1540                         str += len;
1541                         break;
1542                 }
1543
1544                 case FORMAT_TYPE_PTR:
1545                         save_arg(void *);
1546                         /* skip all alphanumeric pointer suffixes */
1547                         while (isalnum(*fmt))
1548                                 fmt++;
1549                         break;
1550
1551                 case FORMAT_TYPE_NRCHARS: {
1552                         /* skip %n 's argument */
1553                         u8 qualifier = spec.qualifier;
1554                         void *skip_arg;
1555                         if (qualifier == 'l')
1556                                 skip_arg = va_arg(args, long *);
1557                         else if (_tolower(qualifier) == 'z')
1558                                 skip_arg = va_arg(args, size_t *);
1559                         else
1560                                 skip_arg = va_arg(args, int *);
1561                         break;
1562                 }
1563
1564                 default:
1565                         switch (spec.type) {
1566
1567                         case FORMAT_TYPE_LONG_LONG:
1568                                 save_arg(long long);
1569                                 break;
1570                         case FORMAT_TYPE_ULONG:
1571                         case FORMAT_TYPE_LONG:
1572                                 save_arg(unsigned long);
1573                                 break;
1574                         case FORMAT_TYPE_SIZE_T:
1575                                 save_arg(size_t);
1576                                 break;
1577                         case FORMAT_TYPE_PTRDIFF:
1578                                 save_arg(ptrdiff_t);
1579                                 break;
1580                         case FORMAT_TYPE_UBYTE:
1581                         case FORMAT_TYPE_BYTE:
1582                                 save_arg(char);
1583                                 break;
1584                         case FORMAT_TYPE_USHORT:
1585                         case FORMAT_TYPE_SHORT:
1586                                 save_arg(short);
1587                                 break;
1588                         default:
1589                                 save_arg(int);
1590                         }
1591                 }
1592         }
1593
1594         return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
1595 #undef save_arg
1596 }
1597 EXPORT_SYMBOL_GPL(vbin_printf);
1598
1599 /**
1600  * bstr_printf - Format a string from binary arguments and place it in a buffer
1601  * @buf: The buffer to place the result into
1602  * @size: The size of the buffer, including the trailing null space
1603  * @fmt: The format string to use
1604  * @bin_buf: Binary arguments for the format string
1605  *
1606  * This function like C99 vsnprintf, but the difference is that vsnprintf gets
1607  * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
1608  * a binary buffer that generated by vbin_printf.
1609  *
1610  * The format follows C99 vsnprintf, but has some extensions:
1611  *  see vsnprintf comment for details.
1612  *
1613  * The return value is the number of characters which would
1614  * be generated for the given input, excluding the trailing
1615  * '\0', as per ISO C99. If you want to have the exact
1616  * number of characters written into @buf as return value
1617  * (not including the trailing '\0'), use vscnprintf(). If the
1618  * return is greater than or equal to @size, the resulting
1619  * string is truncated.
1620  */
1621 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
1622 {
1623         struct printf_spec spec = {0};
1624         char *str, *end;
1625         const char *args = (const char *)bin_buf;
1626
1627         if (WARN_ON_ONCE((int) size < 0))
1628                 return 0;
1629
1630         str = buf;
1631         end = buf + size;
1632
1633 #define get_arg(type)                                                   \
1634 ({                                                                      \
1635         typeof(type) value;                                             \
1636         if (sizeof(type) == 8) {                                        \
1637                 args = PTR_ALIGN(args, sizeof(u32));                    \
1638                 *(u32 *)&value = *(u32 *)args;                          \
1639                 *((u32 *)&value + 1) = *(u32 *)(args + 4);              \
1640         } else {                                                        \
1641                 args = PTR_ALIGN(args, sizeof(type));                   \
1642                 value = *(typeof(type) *)args;                          \
1643         }                                                               \
1644         args += sizeof(type);                                           \
1645         value;                                                          \
1646 })
1647
1648         /* Make sure end is always >= buf */
1649         if (end < buf) {
1650                 end = ((void *)-1);
1651                 size = end - buf;
1652         }
1653
1654         while (*fmt) {
1655                 const char *old_fmt = fmt;
1656                 int read = format_decode(fmt, &spec);
1657
1658                 fmt += read;
1659
1660                 switch (spec.type) {
1661                 case FORMAT_TYPE_NONE: {
1662                         int copy = read;
1663                         if (str < end) {
1664                                 if (copy > end - str)
1665                                         copy = end - str;
1666                                 memcpy(str, old_fmt, copy);
1667                         }
1668                         str += read;
1669                         break;
1670                 }
1671
1672                 case FORMAT_TYPE_WIDTH:
1673                         spec.field_width = get_arg(int);
1674                         break;
1675
1676                 case FORMAT_TYPE_PRECISION:
1677                         spec.precision = get_arg(int);
1678                         break;
1679
1680                 case FORMAT_TYPE_CHAR: {
1681                         char c;
1682
1683                         if (!(spec.flags & LEFT)) {
1684                                 while (--spec.field_width > 0) {
1685                                         if (str < end)
1686                                                 *str = ' ';
1687                                         ++str;
1688                                 }
1689                         }
1690                         c = (unsigned char) get_arg(char);
1691                         if (str < end)
1692                                 *str = c;
1693                         ++str;
1694                         while (--spec.field_width > 0) {
1695                                 if (str < end)
1696                                         *str = ' ';
1697                                 ++str;
1698                         }
1699                         break;
1700                 }
1701
1702                 case FORMAT_TYPE_STR: {
1703                         const char *str_arg = args;
1704                         args += strlen(str_arg) + 1;
1705                         str = string(str, end, (char *)str_arg, spec);
1706                         break;
1707                 }
1708
1709                 case FORMAT_TYPE_PTR:
1710                         str = pointer(fmt+1, str, end, get_arg(void *), spec);
1711                         while (isalnum(*fmt))
1712                                 fmt++;
1713                         break;
1714
1715                 case FORMAT_TYPE_PERCENT_CHAR:
1716                 case FORMAT_TYPE_INVALID:
1717                         if (str < end)
1718                                 *str = '%';
1719                         ++str;
1720                         break;
1721
1722                 case FORMAT_TYPE_NRCHARS:
1723                         /* skip */
1724                         break;
1725
1726                 default: {
1727                         unsigned long long num;
1728
1729                         switch (spec.type) {
1730
1731                         case FORMAT_TYPE_LONG_LONG:
1732                                 num = get_arg(long long);
1733                                 break;
1734                         case FORMAT_TYPE_ULONG:
1735                         case FORMAT_TYPE_LONG:
1736                                 num = get_arg(unsigned long);
1737                                 break;
1738                         case FORMAT_TYPE_SIZE_T:
1739                                 num = get_arg(size_t);
1740                                 break;
1741                         case FORMAT_TYPE_PTRDIFF:
1742                                 num = get_arg(ptrdiff_t);
1743                                 break;
1744                         case FORMAT_TYPE_UBYTE:
1745                                 num = get_arg(unsigned char);
1746                                 break;
1747                         case FORMAT_TYPE_BYTE:
1748                                 num = get_arg(signed char);
1749                                 break;
1750                         case FORMAT_TYPE_USHORT:
1751                                 num = get_arg(unsigned short);
1752                                 break;
1753                         case FORMAT_TYPE_SHORT:
1754                                 num = get_arg(short);
1755                                 break;
1756                         case FORMAT_TYPE_UINT:
1757                                 num = get_arg(unsigned int);
1758                                 break;
1759                         default:
1760                                 num = get_arg(int);
1761                         }
1762
1763                         str = number(str, end, num, spec);
1764                 } /* default: */
1765                 } /* switch(spec.type) */
1766         } /* while(*fmt) */
1767
1768         if (size > 0) {
1769                 if (str < end)
1770                         *str = '\0';
1771                 else
1772                         end[-1] = '\0';
1773         }
1774
1775 #undef get_arg
1776
1777         /* the trailing null byte doesn't count towards the total */
1778         return str - buf;
1779 }
1780 EXPORT_SYMBOL_GPL(bstr_printf);
1781
1782 /**
1783  * bprintf - Parse a format string and place args' binary value in a buffer
1784  * @bin_buf: The buffer to place args' binary value
1785  * @size: The size of the buffer(by words(32bits), not characters)
1786  * @fmt: The format string to use
1787  * @...: Arguments for the format string
1788  *
1789  * The function returns the number of words(u32) written
1790  * into @bin_buf.
1791  */
1792 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
1793 {
1794         va_list args;
1795         int ret;
1796
1797         va_start(args, fmt);
1798         ret = vbin_printf(bin_buf, size, fmt, args);
1799         va_end(args);
1800
1801         return ret;
1802 }
1803 EXPORT_SYMBOL_GPL(bprintf);
1804
1805 #endif /* CONFIG_BINARY_PRINTF */
1806
1807 /**
1808  * vsscanf - Unformat a buffer into a list of arguments
1809  * @buf:        input buffer
1810  * @fmt:        format of buffer
1811  * @args:       arguments
1812  */
1813 int vsscanf(const char *buf, const char *fmt, va_list args)
1814 {
1815         const char *str = buf;
1816         char *next;
1817         char digit;
1818         int num = 0;
1819         u8 qualifier;
1820         u8 base;
1821         s16 field_width;
1822         bool is_sign;
1823
1824         while (*fmt && *str) {
1825                 /* skip any white space in format */
1826                 /* white space in format matchs any amount of
1827                  * white space, including none, in the input.
1828                  */
1829                 if (isspace(*fmt)) {
1830                         fmt = skip_spaces(++fmt);
1831                         str = skip_spaces(str);
1832                 }
1833
1834                 /* anything that is not a conversion must match exactly */
1835                 if (*fmt != '%' && *fmt) {
1836                         if (*fmt++ != *str++)
1837                                 break;
1838                         continue;
1839                 }
1840
1841                 if (!*fmt)
1842                         break;
1843                 ++fmt;
1844
1845                 /* skip this conversion.
1846                  * advance both strings to next white space
1847                  */
1848                 if (*fmt == '*') {
1849                         while (!isspace(*fmt) && *fmt != '%' && *fmt)
1850                                 fmt++;
1851                         while (!isspace(*str) && *str)
1852                                 str++;
1853                         continue;
1854                 }
1855
1856                 /* get field width */
1857                 field_width = -1;
1858                 if (isdigit(*fmt))
1859                         field_width = skip_atoi(&fmt);
1860
1861                 /* get conversion qualifier */
1862                 qualifier = -1;
1863                 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1864                     _tolower(*fmt) == 'z') {
1865                         qualifier = *fmt++;
1866                         if (unlikely(qualifier == *fmt)) {
1867                                 if (qualifier == 'h') {
1868                                         qualifier = 'H';
1869                                         fmt++;
1870                                 } else if (qualifier == 'l') {
1871                                         qualifier = 'L';
1872                                         fmt++;
1873                                 }
1874                         }
1875                 }
1876
1877                 if (!*fmt || !*str)
1878                         break;
1879
1880                 base = 10;
1881                 is_sign = 0;
1882
1883                 switch (*fmt++) {
1884                 case 'c':
1885                 {
1886                         char *s = (char *)va_arg(args, char*);
1887                         if (field_width == -1)
1888                                 field_width = 1;
1889                         do {
1890                                 *s++ = *str++;
1891                         } while (--field_width > 0 && *str);
1892                         num++;
1893                 }
1894                 continue;
1895                 case 's':
1896                 {
1897                         char *s = (char *)va_arg(args, char *);
1898                         if (field_width == -1)
1899                                 field_width = SHRT_MAX;
1900                         /* first, skip leading white space in buffer */
1901                         str = skip_spaces(str);
1902
1903                         /* now copy until next white space */
1904                         while (*str && !isspace(*str) && field_width--)
1905                                 *s++ = *str++;
1906                         *s = '\0';
1907                         num++;
1908                 }
1909                 continue;
1910                 case 'n':
1911                         /* return number of characters read so far */
1912                 {
1913                         int *i = (int *)va_arg(args, int*);
1914                         *i = str - buf;
1915                 }
1916                 continue;
1917                 case 'o':
1918                         base = 8;
1919                         break;
1920                 case 'x':
1921                 case 'X':
1922                         base = 16;
1923                         break;
1924                 case 'i':
1925                         base = 0;
1926                 case 'd':
1927                         is_sign = 1;
1928                 case 'u':
1929                         break;
1930                 case '%':
1931                         /* looking for '%' in str */
1932                         if (*str++ != '%')
1933                                 return num;
1934                         continue;
1935                 default:
1936                         /* invalid format; stop here */
1937                         return num;
1938                 }
1939
1940                 /* have some sort of integer conversion.
1941                  * first, skip white space in buffer.
1942                  */
1943                 str = skip_spaces(str);
1944
1945                 digit = *str;
1946                 if (is_sign && digit == '-')
1947                         digit = *(str + 1);
1948
1949                 if (!digit
1950                     || (base == 16 && !isxdigit(digit))
1951                     || (base == 10 && !isdigit(digit))
1952                     || (base == 8 && (!isdigit(digit) || digit > '7'))
1953                     || (base == 0 && !isdigit(digit)))
1954                         break;
1955
1956                 switch (qualifier) {
1957                 case 'H':       /* that's 'hh' in format */
1958                         if (is_sign) {
1959                                 signed char *s = (signed char *)va_arg(args, signed char *);
1960                                 *s = (signed char)simple_strtol(str, &next, base);
1961                         } else {
1962                                 unsigned char *s = (unsigned char *)va_arg(args, unsigned char *);
1963                                 *s = (unsigned char)simple_strtoul(str, &next, base);
1964                         }
1965                         break;
1966                 case 'h':
1967                         if (is_sign) {
1968                                 short *s = (short *)va_arg(args, short *);
1969                                 *s = (short)simple_strtol(str, &next, base);
1970                         } else {
1971                                 unsigned short *s = (unsigned short *)va_arg(args, unsigned short *);
1972                                 *s = (unsigned short)simple_strtoul(str, &next, base);
1973                         }
1974                         break;
1975                 case 'l':
1976                         if (is_sign) {
1977                                 long *l = (long *)va_arg(args, long *);
1978                                 *l = simple_strtol(str, &next, base);
1979                         } else {
1980                                 unsigned long *l = (unsigned long *)va_arg(args, unsigned long *);
1981                                 *l = simple_strtoul(str, &next, base);
1982                         }
1983                         break;
1984                 case 'L':
1985                         if (is_sign) {
1986                                 long long *l = (long long *)va_arg(args, long long *);
1987                                 *l = simple_strtoll(str, &next, base);
1988                         } else {
1989                                 unsigned long long *l = (unsigned long long *)va_arg(args, unsigned long long *);
1990                                 *l = simple_strtoull(str, &next, base);
1991                         }
1992                         break;
1993                 case 'Z':
1994                 case 'z':
1995                 {
1996                         size_t *s = (size_t *)va_arg(args, size_t *);
1997                         *s = (size_t)simple_strtoul(str, &next, base);
1998                 }
1999                 break;
2000                 default:
2001                         if (is_sign) {
2002                                 int *i = (int *)va_arg(args, int *);
2003                                 *i = (int)simple_strtol(str, &next, base);
2004                         } else {
2005                                 unsigned int *i = (unsigned int *)va_arg(args, unsigned int*);
2006                                 *i = (unsigned int)simple_strtoul(str, &next, base);
2007                         }
2008                         break;
2009                 }
2010                 num++;
2011
2012                 if (!next)
2013                         break;
2014                 str = next;
2015         }
2016
2017         /*
2018          * Now we've come all the way through so either the input string or the
2019          * format ended. In the former case, there can be a %n at the current
2020          * position in the format that needs to be filled.
2021          */
2022         if (*fmt == '%' && *(fmt + 1) == 'n') {
2023                 int *p = (int *)va_arg(args, int *);
2024                 *p = str - buf;
2025         }
2026
2027         return num;
2028 }
2029 EXPORT_SYMBOL(vsscanf);
2030
2031 /**
2032  * sscanf - Unformat a buffer into a list of arguments
2033  * @buf:        input buffer
2034  * @fmt:        formatting of buffer
2035  * @...:        resulting arguments
2036  */
2037 int sscanf(const char *buf, const char *fmt, ...)
2038 {
2039         va_list args;
2040         int i;
2041
2042         va_start(args, fmt);
2043         i = vsscanf(buf, fmt, args);
2044         va_end(args);
2045
2046         return i;
2047 }
2048 EXPORT_SYMBOL(sscanf);