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