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/clk.h>
21 #include <linux/clk-provider.h>
22 #include <linux/module.h> /* for KSYM_SYMBOL_LEN */
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/ctype.h>
26 #include <linux/kernel.h>
27 #include <linux/kallsyms.h>
28 #include <linux/math64.h>
29 #include <linux/uaccess.h>
30 #include <linux/ioport.h>
31 #include <linux/dcache.h>
32 #include <linux/cred.h>
33 #include <net/addrconf.h>
34
35 #include <asm/page.h> /* for PAGE_SIZE */
36 #include <asm/sections.h> /* for dereference_function_descriptor() */
37 #include <asm/byteorder.h> /* cpu_to_le16 */
38
39 #include <linux/string_helpers.h>
40 #include "kstrtox.h"
41
42 /**
43 * simple_strtoull - convert a string to an unsigned long long
44 * @cp: The start of the string
45 * @endp: A pointer to the end of the parsed string will be placed here
46 * @base: The number base to use
47 *
48 * This function is obsolete. Please use kstrtoull instead.
49 */
simple_strtoull(const char * cp,char ** endp,unsigned int base)50 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
51 {
52 unsigned long long result;
53 unsigned int rv;
54
55 cp = _parse_integer_fixup_radix(cp, &base);
56 rv = _parse_integer(cp, base, &result);
57 /* FIXME */
58 cp += (rv & ~KSTRTOX_OVERFLOW);
59
60 if (endp)
61 *endp = (char *)cp;
62
63 return result;
64 }
65 EXPORT_SYMBOL(simple_strtoull);
66
67 /**
68 * simple_strtoul - convert a string to an unsigned long
69 * @cp: The start of the string
70 * @endp: A pointer to the end of the parsed string will be placed here
71 * @base: The number base to use
72 *
73 * This function is obsolete. Please use kstrtoul instead.
74 */
simple_strtoul(const char * cp,char ** endp,unsigned int base)75 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
76 {
77 return simple_strtoull(cp, endp, base);
78 }
79 EXPORT_SYMBOL(simple_strtoul);
80
81 /**
82 * simple_strtol - convert a string to a signed 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 * This function is obsolete. Please use kstrtol instead.
88 */
simple_strtol(const char * cp,char ** endp,unsigned int base)89 long simple_strtol(const char *cp, char **endp, unsigned int base)
90 {
91 if (*cp == '-')
92 return -simple_strtoul(cp + 1, endp, base);
93
94 return simple_strtoul(cp, endp, base);
95 }
96 EXPORT_SYMBOL(simple_strtol);
97
98 /**
99 * simple_strtoll - convert a string to a signed long long
100 * @cp: The start of the string
101 * @endp: A pointer to the end of the parsed string will be placed here
102 * @base: The number base to use
103 *
104 * This function is obsolete. Please use kstrtoll instead.
105 */
simple_strtoll(const char * cp,char ** endp,unsigned int base)106 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
107 {
108 if (*cp == '-')
109 return -simple_strtoull(cp + 1, endp, base);
110
111 return simple_strtoull(cp, endp, base);
112 }
113 EXPORT_SYMBOL(simple_strtoll);
114
115 static noinline_for_stack
skip_atoi(const char ** s)116 int skip_atoi(const char **s)
117 {
118 int i = 0;
119
120 do {
121 i = i*10 + *((*s)++) - '0';
122 } while (isdigit(**s));
123
124 return i;
125 }
126
127 /*
128 * Decimal conversion is by far the most typical, and is used for
129 * /proc and /sys data. This directly impacts e.g. top performance
130 * with many processes running. We optimize it for speed by emitting
131 * two characters at a time, using a 200 byte lookup table. This
132 * roughly halves the number of multiplications compared to computing
133 * the digits one at a time. Implementation strongly inspired by the
134 * previous version, which in turn used ideas described at
135 * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
136 * from the author, Douglas W. Jones).
137 *
138 * It turns out there is precisely one 26 bit fixed-point
139 * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
140 * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
141 * range happens to be somewhat larger (x <= 1073741898), but that's
142 * irrelevant for our purpose.
143 *
144 * For dividing a number in the range [10^4, 10^6-1] by 100, we still
145 * need a 32x32->64 bit multiply, so we simply use the same constant.
146 *
147 * For dividing a number in the range [100, 10^4-1] by 100, there are
148 * several options. The simplest is (x * 0x147b) >> 19, which is valid
149 * for all x <= 43698.
150 */
151
152 static const u16 decpair[100] = {
153 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
154 _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
155 _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
156 _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
157 _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
158 _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
159 _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
160 _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
161 _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
162 _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
163 _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
164 #undef _
165 };
166
167 /*
168 * This will print a single '0' even if r == 0, since we would
169 * immediately jump to out_r where two 0s would be written but only
170 * one of them accounted for in buf. This is needed by ip4_string
171 * below. All other callers pass a non-zero value of r.
172 */
173 static noinline_for_stack
put_dec_trunc8(char * buf,unsigned r)174 char *put_dec_trunc8(char *buf, unsigned r)
175 {
176 unsigned q;
177
178 /* 1 <= r < 10^8 */
179 if (r < 100)
180 goto out_r;
181
182 /* 100 <= r < 10^8 */
183 q = (r * (u64)0x28f5c29) >> 32;
184 *((u16 *)buf) = decpair[r - 100*q];
185 buf += 2;
186
187 /* 1 <= q < 10^6 */
188 if (q < 100)
189 goto out_q;
190
191 /* 100 <= q < 10^6 */
192 r = (q * (u64)0x28f5c29) >> 32;
193 *((u16 *)buf) = decpair[q - 100*r];
194 buf += 2;
195
196 /* 1 <= r < 10^4 */
197 if (r < 100)
198 goto out_r;
199
200 /* 100 <= r < 10^4 */
201 q = (r * 0x147b) >> 19;
202 *((u16 *)buf) = decpair[r - 100*q];
203 buf += 2;
204 out_q:
205 /* 1 <= q < 100 */
206 r = q;
207 out_r:
208 /* 1 <= r < 100 */
209 *((u16 *)buf) = decpair[r];
210 buf += r < 10 ? 1 : 2;
211 return buf;
212 }
213
214 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
215 static noinline_for_stack
put_dec_full8(char * buf,unsigned r)216 char *put_dec_full8(char *buf, unsigned r)
217 {
218 unsigned q;
219
220 /* 0 <= r < 10^8 */
221 q = (r * (u64)0x28f5c29) >> 32;
222 *((u16 *)buf) = decpair[r - 100*q];
223 buf += 2;
224
225 /* 0 <= q < 10^6 */
226 r = (q * (u64)0x28f5c29) >> 32;
227 *((u16 *)buf) = decpair[q - 100*r];
228 buf += 2;
229
230 /* 0 <= r < 10^4 */
231 q = (r * 0x147b) >> 19;
232 *((u16 *)buf) = decpair[r - 100*q];
233 buf += 2;
234
235 /* 0 <= q < 100 */
236 *((u16 *)buf) = decpair[q];
237 buf += 2;
238 return buf;
239 }
240
241 static noinline_for_stack
put_dec(char * buf,unsigned long long n)242 char *put_dec(char *buf, unsigned long long n)
243 {
244 if (n >= 100*1000*1000)
245 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
246 /* 1 <= n <= 1.6e11 */
247 if (n >= 100*1000*1000)
248 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
249 /* 1 <= n < 1e8 */
250 return put_dec_trunc8(buf, n);
251 }
252
253 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
254
255 static void
put_dec_full4(char * buf,unsigned r)256 put_dec_full4(char *buf, unsigned r)
257 {
258 unsigned q;
259
260 /* 0 <= r < 10^4 */
261 q = (r * 0x147b) >> 19;
262 *((u16 *)buf) = decpair[r - 100*q];
263 buf += 2;
264 /* 0 <= q < 100 */
265 *((u16 *)buf) = decpair[q];
266 }
267
268 /*
269 * Call put_dec_full4 on x % 10000, return x / 10000.
270 * The approximation x/10000 == (x * 0x346DC5D7) >> 43
271 * holds for all x < 1,128,869,999. The largest value this
272 * helper will ever be asked to convert is 1,125,520,955.
273 * (second call in the put_dec code, assuming n is all-ones).
274 */
275 static noinline_for_stack
put_dec_helper4(char * buf,unsigned x)276 unsigned put_dec_helper4(char *buf, unsigned x)
277 {
278 uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
279
280 put_dec_full4(buf, x - q * 10000);
281 return q;
282 }
283
284 /* Based on code by Douglas W. Jones found at
285 * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
286 * (with permission from the author).
287 * Performs no 64-bit division and hence should be fast on 32-bit machines.
288 */
289 static
put_dec(char * buf,unsigned long long n)290 char *put_dec(char *buf, unsigned long long n)
291 {
292 uint32_t d3, d2, d1, q, h;
293
294 if (n < 100*1000*1000)
295 return put_dec_trunc8(buf, n);
296
297 d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
298 h = (n >> 32);
299 d2 = (h ) & 0xffff;
300 d3 = (h >> 16); /* implicit "& 0xffff" */
301
302 /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
303 = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
304 q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
305 q = put_dec_helper4(buf, q);
306
307 q += 7671 * d3 + 9496 * d2 + 6 * d1;
308 q = put_dec_helper4(buf+4, q);
309
310 q += 4749 * d3 + 42 * d2;
311 q = put_dec_helper4(buf+8, q);
312
313 q += 281 * d3;
314 buf += 12;
315 if (q)
316 buf = put_dec_trunc8(buf, q);
317 else while (buf[-1] == '0')
318 --buf;
319
320 return buf;
321 }
322
323 #endif
324
325 /*
326 * Convert passed number to decimal string.
327 * Returns the length of string. On buffer overflow, returns 0.
328 *
329 * If speed is not important, use snprintf(). It's easy to read the code.
330 */
num_to_str(char * buf,int size,unsigned long long num)331 int num_to_str(char *buf, int size, unsigned long long num)
332 {
333 /* put_dec requires 2-byte alignment of the buffer. */
334 char tmp[sizeof(num) * 3] __aligned(2);
335 int idx, len;
336
337 /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
338 if (num <= 9) {
339 tmp[0] = '0' + num;
340 len = 1;
341 } else {
342 len = put_dec(tmp, num) - tmp;
343 }
344
345 if (len > size)
346 return 0;
347 for (idx = 0; idx < len; ++idx)
348 buf[idx] = tmp[len - idx - 1];
349 return len;
350 }
351
352 #define SIGN 1 /* unsigned/signed, must be 1 */
353 #define LEFT 2 /* left justified */
354 #define PLUS 4 /* show plus */
355 #define SPACE 8 /* space if plus */
356 #define ZEROPAD 16 /* pad with zero, must be 16 == '0' - ' ' */
357 #define SMALL 32 /* use lowercase in hex (must be 32 == 0x20) */
358 #define SPECIAL 64 /* prefix hex with "0x", octal with "0" */
359
360 enum format_type {
361 FORMAT_TYPE_NONE, /* Just a string part */
362 FORMAT_TYPE_WIDTH,
363 FORMAT_TYPE_PRECISION,
364 FORMAT_TYPE_CHAR,
365 FORMAT_TYPE_STR,
366 FORMAT_TYPE_PTR,
367 FORMAT_TYPE_PERCENT_CHAR,
368 FORMAT_TYPE_INVALID,
369 FORMAT_TYPE_LONG_LONG,
370 FORMAT_TYPE_ULONG,
371 FORMAT_TYPE_LONG,
372 FORMAT_TYPE_UBYTE,
373 FORMAT_TYPE_BYTE,
374 FORMAT_TYPE_USHORT,
375 FORMAT_TYPE_SHORT,
376 FORMAT_TYPE_UINT,
377 FORMAT_TYPE_INT,
378 FORMAT_TYPE_SIZE_T,
379 FORMAT_TYPE_PTRDIFF
380 };
381
382 struct printf_spec {
383 u8 type; /* format_type enum */
384 u8 flags; /* flags to number() */
385 u8 base; /* number base, 8, 10 or 16 only */
386 u8 qualifier; /* number qualifier, one of 'hHlLtzZ' */
387 s16 field_width; /* width of output field */
388 s16 precision; /* # of digits/chars */
389 };
390
391 static noinline_for_stack
number(char * buf,char * end,unsigned long long num,struct printf_spec spec)392 char *number(char *buf, char *end, unsigned long long num,
393 struct printf_spec spec)
394 {
395 /* put_dec requires 2-byte alignment of the buffer. */
396 char tmp[3 * sizeof(num)] __aligned(2);
397 char sign;
398 char locase;
399 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
400 int i;
401 bool is_zero = num == 0LL;
402
403 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
404 * produces same digits or (maybe lowercased) letters */
405 locase = (spec.flags & SMALL);
406 if (spec.flags & LEFT)
407 spec.flags &= ~ZEROPAD;
408 sign = 0;
409 if (spec.flags & SIGN) {
410 if ((signed long long)num < 0) {
411 sign = '-';
412 num = -(signed long long)num;
413 spec.field_width--;
414 } else if (spec.flags & PLUS) {
415 sign = '+';
416 spec.field_width--;
417 } else if (spec.flags & SPACE) {
418 sign = ' ';
419 spec.field_width--;
420 }
421 }
422 if (need_pfx) {
423 if (spec.base == 16)
424 spec.field_width -= 2;
425 else if (!is_zero)
426 spec.field_width--;
427 }
428
429 /* generate full string in tmp[], in reverse order */
430 i = 0;
431 if (num < spec.base)
432 tmp[i++] = hex_asc_upper[num] | locase;
433 else if (spec.base != 10) { /* 8 or 16 */
434 int mask = spec.base - 1;
435 int shift = 3;
436
437 if (spec.base == 16)
438 shift = 4;
439 do {
440 tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
441 num >>= shift;
442 } while (num);
443 } else { /* base 10 */
444 i = put_dec(tmp, num) - tmp;
445 }
446
447 /* printing 100 using %2d gives "100", not "00" */
448 if (i > spec.precision)
449 spec.precision = i;
450 /* leading space padding */
451 spec.field_width -= spec.precision;
452 if (!(spec.flags & (ZEROPAD | LEFT))) {
453 while (--spec.field_width >= 0) {
454 if (buf < end)
455 *buf = ' ';
456 ++buf;
457 }
458 }
459 /* sign */
460 if (sign) {
461 if (buf < end)
462 *buf = sign;
463 ++buf;
464 }
465 /* "0x" / "0" prefix */
466 if (need_pfx) {
467 if (spec.base == 16 || !is_zero) {
468 if (buf < end)
469 *buf = '0';
470 ++buf;
471 }
472 if (spec.base == 16) {
473 if (buf < end)
474 *buf = ('X' | locase);
475 ++buf;
476 }
477 }
478 /* zero or space padding */
479 if (!(spec.flags & LEFT)) {
480 char c = ' ' + (spec.flags & ZEROPAD);
481 BUILD_BUG_ON(' ' + ZEROPAD != '0');
482 while (--spec.field_width >= 0) {
483 if (buf < end)
484 *buf = c;
485 ++buf;
486 }
487 }
488 /* hmm even more zero padding? */
489 while (i <= --spec.precision) {
490 if (buf < end)
491 *buf = '0';
492 ++buf;
493 }
494 /* actual digits of result */
495 while (--i >= 0) {
496 if (buf < end)
497 *buf = tmp[i];
498 ++buf;
499 }
500 /* trailing space padding */
501 while (--spec.field_width >= 0) {
502 if (buf < end)
503 *buf = ' ';
504 ++buf;
505 }
506
507 return buf;
508 }
509
510 static noinline_for_stack
string(char * buf,char * end,const char * s,struct printf_spec spec)511 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
512 {
513 int len, i;
514
515 if ((unsigned long)s < PAGE_SIZE)
516 s = "(null)";
517
518 len = strnlen(s, spec.precision);
519
520 if (!(spec.flags & LEFT)) {
521 while (len < spec.field_width--) {
522 if (buf < end)
523 *buf = ' ';
524 ++buf;
525 }
526 }
527 for (i = 0; i < len; ++i) {
528 if (buf < end)
529 *buf = *s;
530 ++buf; ++s;
531 }
532 while (len < spec.field_width--) {
533 if (buf < end)
534 *buf = ' ';
535 ++buf;
536 }
537
538 return buf;
539 }
540
widen(char * buf,char * end,unsigned len,unsigned spaces)541 static void widen(char *buf, char *end, unsigned len, unsigned spaces)
542 {
543 size_t size;
544 if (buf >= end) /* nowhere to put anything */
545 return;
546 size = end - buf;
547 if (size <= spaces) {
548 memset(buf, ' ', size);
549 return;
550 }
551 if (len) {
552 if (len > size - spaces)
553 len = size - spaces;
554 memmove(buf + spaces, buf, len);
555 }
556 memset(buf, ' ', spaces);
557 }
558
559 static noinline_for_stack
dentry_name(char * buf,char * end,const struct dentry * d,struct printf_spec spec,const char * fmt)560 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
561 const char *fmt)
562 {
563 const char *array[4], *s;
564 const struct dentry *p;
565 int depth;
566 int i, n;
567
568 switch (fmt[1]) {
569 case '2': case '3': case '4':
570 depth = fmt[1] - '0';
571 break;
572 default:
573 depth = 1;
574 }
575
576 rcu_read_lock();
577 for (i = 0; i < depth; i++, d = p) {
578 p = ACCESS_ONCE(d->d_parent);
579 array[i] = ACCESS_ONCE(d->d_name.name);
580 if (p == d) {
581 if (i)
582 array[i] = "";
583 i++;
584 break;
585 }
586 }
587 s = array[--i];
588 for (n = 0; n != spec.precision; n++, buf++) {
589 char c = *s++;
590 if (!c) {
591 if (!i)
592 break;
593 c = '/';
594 s = array[--i];
595 }
596 if (buf < end)
597 *buf = c;
598 }
599 rcu_read_unlock();
600 if (n < spec.field_width) {
601 /* we want to pad the sucker */
602 unsigned spaces = spec.field_width - n;
603 if (!(spec.flags & LEFT)) {
604 widen(buf - n, end, n, spaces);
605 return buf + spaces;
606 }
607 while (spaces--) {
608 if (buf < end)
609 *buf = ' ';
610 ++buf;
611 }
612 }
613 return buf;
614 }
615
616 static noinline_for_stack
symbol_string(char * buf,char * end,void * ptr,struct printf_spec spec,const char * fmt)617 char *symbol_string(char *buf, char *end, void *ptr,
618 struct printf_spec spec, const char *fmt)
619 {
620 unsigned long value;
621 #ifdef CONFIG_KALLSYMS
622 char sym[KSYM_SYMBOL_LEN];
623 #endif
624
625 if (fmt[1] == 'R')
626 ptr = __builtin_extract_return_addr(ptr);
627 value = (unsigned long)ptr;
628
629 #ifdef CONFIG_KALLSYMS
630 if (*fmt == 'B')
631 sprint_backtrace(sym, value);
632 else if (*fmt != 'f' && *fmt != 's')
633 sprint_symbol(sym, value);
634 else
635 sprint_symbol_no_offset(sym, value);
636
637 return string(buf, end, sym, spec);
638 #else
639 spec.field_width = 2 * sizeof(void *);
640 spec.flags |= SPECIAL | SMALL | ZEROPAD;
641 spec.base = 16;
642
643 return number(buf, end, value, spec);
644 #endif
645 }
646
647 static noinline_for_stack
resource_string(char * buf,char * end,struct resource * res,struct printf_spec spec,const char * fmt)648 char *resource_string(char *buf, char *end, struct resource *res,
649 struct printf_spec spec, const char *fmt)
650 {
651 #ifndef IO_RSRC_PRINTK_SIZE
652 #define IO_RSRC_PRINTK_SIZE 6
653 #endif
654
655 #ifndef MEM_RSRC_PRINTK_SIZE
656 #define MEM_RSRC_PRINTK_SIZE 10
657 #endif
658 static const struct printf_spec io_spec = {
659 .base = 16,
660 .field_width = IO_RSRC_PRINTK_SIZE,
661 .precision = -1,
662 .flags = SPECIAL | SMALL | ZEROPAD,
663 };
664 static const struct printf_spec mem_spec = {
665 .base = 16,
666 .field_width = MEM_RSRC_PRINTK_SIZE,
667 .precision = -1,
668 .flags = SPECIAL | SMALL | ZEROPAD,
669 };
670 static const struct printf_spec bus_spec = {
671 .base = 16,
672 .field_width = 2,
673 .precision = -1,
674 .flags = SMALL | ZEROPAD,
675 };
676 static const struct printf_spec dec_spec = {
677 .base = 10,
678 .precision = -1,
679 .flags = 0,
680 };
681 static const struct printf_spec str_spec = {
682 .field_width = -1,
683 .precision = 10,
684 .flags = LEFT,
685 };
686 static const struct printf_spec flag_spec = {
687 .base = 16,
688 .precision = -1,
689 .flags = SPECIAL | SMALL,
690 };
691
692 /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
693 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
694 #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
695 #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
696 #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
697 #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
698 char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
699 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
700
701 char *p = sym, *pend = sym + sizeof(sym);
702 int decode = (fmt[0] == 'R') ? 1 : 0;
703 const struct printf_spec *specp;
704
705 *p++ = '[';
706 if (res->flags & IORESOURCE_IO) {
707 p = string(p, pend, "io ", str_spec);
708 specp = &io_spec;
709 } else if (res->flags & IORESOURCE_MEM) {
710 p = string(p, pend, "mem ", str_spec);
711 specp = &mem_spec;
712 } else if (res->flags & IORESOURCE_IRQ) {
713 p = string(p, pend, "irq ", str_spec);
714 specp = &dec_spec;
715 } else if (res->flags & IORESOURCE_DMA) {
716 p = string(p, pend, "dma ", str_spec);
717 specp = &dec_spec;
718 } else if (res->flags & IORESOURCE_BUS) {
719 p = string(p, pend, "bus ", str_spec);
720 specp = &bus_spec;
721 } else {
722 p = string(p, pend, "??? ", str_spec);
723 specp = &mem_spec;
724 decode = 0;
725 }
726 if (decode && res->flags & IORESOURCE_UNSET) {
727 p = string(p, pend, "size ", str_spec);
728 p = number(p, pend, resource_size(res), *specp);
729 } else {
730 p = number(p, pend, res->start, *specp);
731 if (res->start != res->end) {
732 *p++ = '-';
733 p = number(p, pend, res->end, *specp);
734 }
735 }
736 if (decode) {
737 if (res->flags & IORESOURCE_MEM_64)
738 p = string(p, pend, " 64bit", str_spec);
739 if (res->flags & IORESOURCE_PREFETCH)
740 p = string(p, pend, " pref", str_spec);
741 if (res->flags & IORESOURCE_WINDOW)
742 p = string(p, pend, " window", str_spec);
743 if (res->flags & IORESOURCE_DISABLED)
744 p = string(p, pend, " disabled", str_spec);
745 } else {
746 p = string(p, pend, " flags ", str_spec);
747 p = number(p, pend, res->flags, flag_spec);
748 }
749 *p++ = ']';
750 *p = '\0';
751
752 return string(buf, end, sym, spec);
753 }
754
755 static noinline_for_stack
hex_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)756 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
757 const char *fmt)
758 {
759 int i, len = 1; /* if we pass '%ph[CDN]', field width remains
760 negative value, fallback to the default */
761 char separator;
762
763 if (spec.field_width == 0)
764 /* nothing to print */
765 return buf;
766
767 if (ZERO_OR_NULL_PTR(addr))
768 /* NULL pointer */
769 return string(buf, end, NULL, spec);
770
771 switch (fmt[1]) {
772 case 'C':
773 separator = ':';
774 break;
775 case 'D':
776 separator = '-';
777 break;
778 case 'N':
779 separator = 0;
780 break;
781 default:
782 separator = ' ';
783 break;
784 }
785
786 if (spec.field_width > 0)
787 len = min_t(int, spec.field_width, 64);
788
789 for (i = 0; i < len; ++i) {
790 if (buf < end)
791 *buf = hex_asc_hi(addr[i]);
792 ++buf;
793 if (buf < end)
794 *buf = hex_asc_lo(addr[i]);
795 ++buf;
796
797 if (separator && i != len - 1) {
798 if (buf < end)
799 *buf = separator;
800 ++buf;
801 }
802 }
803
804 return buf;
805 }
806
807 static noinline_for_stack
bitmap_string(char * buf,char * end,unsigned long * bitmap,struct printf_spec spec,const char * fmt)808 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
809 struct printf_spec spec, const char *fmt)
810 {
811 const int CHUNKSZ = 32;
812 int nr_bits = max_t(int, spec.field_width, 0);
813 int i, chunksz;
814 bool first = true;
815
816 /* reused to print numbers */
817 spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
818
819 chunksz = nr_bits & (CHUNKSZ - 1);
820 if (chunksz == 0)
821 chunksz = CHUNKSZ;
822
823 i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
824 for (; i >= 0; i -= CHUNKSZ) {
825 u32 chunkmask, val;
826 int word, bit;
827
828 chunkmask = ((1ULL << chunksz) - 1);
829 word = i / BITS_PER_LONG;
830 bit = i % BITS_PER_LONG;
831 val = (bitmap[word] >> bit) & chunkmask;
832
833 if (!first) {
834 if (buf < end)
835 *buf = ',';
836 buf++;
837 }
838 first = false;
839
840 spec.field_width = DIV_ROUND_UP(chunksz, 4);
841 buf = number(buf, end, val, spec);
842
843 chunksz = CHUNKSZ;
844 }
845 return buf;
846 }
847
848 static noinline_for_stack
bitmap_list_string(char * buf,char * end,unsigned long * bitmap,struct printf_spec spec,const char * fmt)849 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
850 struct printf_spec spec, const char *fmt)
851 {
852 int nr_bits = max_t(int, spec.field_width, 0);
853 /* current bit is 'cur', most recently seen range is [rbot, rtop] */
854 int cur, rbot, rtop;
855 bool first = true;
856
857 /* reused to print numbers */
858 spec = (struct printf_spec){ .base = 10 };
859
860 rbot = cur = find_first_bit(bitmap, nr_bits);
861 while (cur < nr_bits) {
862 rtop = cur;
863 cur = find_next_bit(bitmap, nr_bits, cur + 1);
864 if (cur < nr_bits && cur <= rtop + 1)
865 continue;
866
867 if (!first) {
868 if (buf < end)
869 *buf = ',';
870 buf++;
871 }
872 first = false;
873
874 buf = number(buf, end, rbot, spec);
875 if (rbot < rtop) {
876 if (buf < end)
877 *buf = '-';
878 buf++;
879
880 buf = number(buf, end, rtop, spec);
881 }
882
883 rbot = cur;
884 }
885 return buf;
886 }
887
888 static noinline_for_stack
mac_address_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)889 char *mac_address_string(char *buf, char *end, u8 *addr,
890 struct printf_spec spec, const char *fmt)
891 {
892 char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
893 char *p = mac_addr;
894 int i;
895 char separator;
896 bool reversed = false;
897
898 switch (fmt[1]) {
899 case 'F':
900 separator = '-';
901 break;
902
903 case 'R':
904 reversed = true;
905 /* fall through */
906
907 default:
908 separator = ':';
909 break;
910 }
911
912 for (i = 0; i < 6; i++) {
913 if (reversed)
914 p = hex_byte_pack(p, addr[5 - i]);
915 else
916 p = hex_byte_pack(p, addr[i]);
917
918 if (fmt[0] == 'M' && i != 5)
919 *p++ = separator;
920 }
921 *p = '\0';
922
923 return string(buf, end, mac_addr, spec);
924 }
925
926 static noinline_for_stack
ip4_string(char * p,const u8 * addr,const char * fmt)927 char *ip4_string(char *p, const u8 *addr, const char *fmt)
928 {
929 int i;
930 bool leading_zeros = (fmt[0] == 'i');
931 int index;
932 int step;
933
934 switch (fmt[2]) {
935 case 'h':
936 #ifdef __BIG_ENDIAN
937 index = 0;
938 step = 1;
939 #else
940 index = 3;
941 step = -1;
942 #endif
943 break;
944 case 'l':
945 index = 3;
946 step = -1;
947 break;
948 case 'n':
949 case 'b':
950 default:
951 index = 0;
952 step = 1;
953 break;
954 }
955 for (i = 0; i < 4; i++) {
956 char temp[4] __aligned(2); /* hold each IP quad in reverse order */
957 int digits = put_dec_trunc8(temp, addr[index]) - temp;
958 if (leading_zeros) {
959 if (digits < 3)
960 *p++ = '0';
961 if (digits < 2)
962 *p++ = '0';
963 }
964 /* reverse the digits in the quad */
965 while (digits--)
966 *p++ = temp[digits];
967 if (i < 3)
968 *p++ = '.';
969 index += step;
970 }
971 *p = '\0';
972
973 return p;
974 }
975
976 static noinline_for_stack
ip6_compressed_string(char * p,const char * addr)977 char *ip6_compressed_string(char *p, const char *addr)
978 {
979 int i, j, range;
980 unsigned char zerolength[8];
981 int longest = 1;
982 int colonpos = -1;
983 u16 word;
984 u8 hi, lo;
985 bool needcolon = false;
986 bool useIPv4;
987 struct in6_addr in6;
988
989 memcpy(&in6, addr, sizeof(struct in6_addr));
990
991 useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
992
993 memset(zerolength, 0, sizeof(zerolength));
994
995 if (useIPv4)
996 range = 6;
997 else
998 range = 8;
999
1000 /* find position of longest 0 run */
1001 for (i = 0; i < range; i++) {
1002 for (j = i; j < range; j++) {
1003 if (in6.s6_addr16[j] != 0)
1004 break;
1005 zerolength[i]++;
1006 }
1007 }
1008 for (i = 0; i < range; i++) {
1009 if (zerolength[i] > longest) {
1010 longest = zerolength[i];
1011 colonpos = i;
1012 }
1013 }
1014 if (longest == 1) /* don't compress a single 0 */
1015 colonpos = -1;
1016
1017 /* emit address */
1018 for (i = 0; i < range; i++) {
1019 if (i == colonpos) {
1020 if (needcolon || i == 0)
1021 *p++ = ':';
1022 *p++ = ':';
1023 needcolon = false;
1024 i += longest - 1;
1025 continue;
1026 }
1027 if (needcolon) {
1028 *p++ = ':';
1029 needcolon = false;
1030 }
1031 /* hex u16 without leading 0s */
1032 word = ntohs(in6.s6_addr16[i]);
1033 hi = word >> 8;
1034 lo = word & 0xff;
1035 if (hi) {
1036 if (hi > 0x0f)
1037 p = hex_byte_pack(p, hi);
1038 else
1039 *p++ = hex_asc_lo(hi);
1040 p = hex_byte_pack(p, lo);
1041 }
1042 else if (lo > 0x0f)
1043 p = hex_byte_pack(p, lo);
1044 else
1045 *p++ = hex_asc_lo(lo);
1046 needcolon = true;
1047 }
1048
1049 if (useIPv4) {
1050 if (needcolon)
1051 *p++ = ':';
1052 p = ip4_string(p, &in6.s6_addr[12], "I4");
1053 }
1054 *p = '\0';
1055
1056 return p;
1057 }
1058
1059 static noinline_for_stack
ip6_string(char * p,const char * addr,const char * fmt)1060 char *ip6_string(char *p, const char *addr, const char *fmt)
1061 {
1062 int i;
1063
1064 for (i = 0; i < 8; i++) {
1065 p = hex_byte_pack(p, *addr++);
1066 p = hex_byte_pack(p, *addr++);
1067 if (fmt[0] == 'I' && i != 7)
1068 *p++ = ':';
1069 }
1070 *p = '\0';
1071
1072 return p;
1073 }
1074
1075 static noinline_for_stack
ip6_addr_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1076 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1077 struct printf_spec spec, const char *fmt)
1078 {
1079 char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1080
1081 if (fmt[0] == 'I' && fmt[2] == 'c')
1082 ip6_compressed_string(ip6_addr, addr);
1083 else
1084 ip6_string(ip6_addr, addr, fmt);
1085
1086 return string(buf, end, ip6_addr, spec);
1087 }
1088
1089 static noinline_for_stack
ip4_addr_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1090 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1091 struct printf_spec spec, const char *fmt)
1092 {
1093 char ip4_addr[sizeof("255.255.255.255")];
1094
1095 ip4_string(ip4_addr, addr, fmt);
1096
1097 return string(buf, end, ip4_addr, spec);
1098 }
1099
1100 static noinline_for_stack
ip6_addr_string_sa(char * buf,char * end,const struct sockaddr_in6 * sa,struct printf_spec spec,const char * fmt)1101 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1102 struct printf_spec spec, const char *fmt)
1103 {
1104 bool have_p = false, have_s = false, have_f = false, have_c = false;
1105 char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1106 sizeof(":12345") + sizeof("/123456789") +
1107 sizeof("%1234567890")];
1108 char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1109 const u8 *addr = (const u8 *) &sa->sin6_addr;
1110 char fmt6[2] = { fmt[0], '6' };
1111 u8 off = 0;
1112
1113 fmt++;
1114 while (isalpha(*++fmt)) {
1115 switch (*fmt) {
1116 case 'p':
1117 have_p = true;
1118 break;
1119 case 'f':
1120 have_f = true;
1121 break;
1122 case 's':
1123 have_s = true;
1124 break;
1125 case 'c':
1126 have_c = true;
1127 break;
1128 }
1129 }
1130
1131 if (have_p || have_s || have_f) {
1132 *p = '[';
1133 off = 1;
1134 }
1135
1136 if (fmt6[0] == 'I' && have_c)
1137 p = ip6_compressed_string(ip6_addr + off, addr);
1138 else
1139 p = ip6_string(ip6_addr + off, addr, fmt6);
1140
1141 if (have_p || have_s || have_f)
1142 *p++ = ']';
1143
1144 if (have_p) {
1145 *p++ = ':';
1146 p = number(p, pend, ntohs(sa->sin6_port), spec);
1147 }
1148 if (have_f) {
1149 *p++ = '/';
1150 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1151 IPV6_FLOWINFO_MASK), spec);
1152 }
1153 if (have_s) {
1154 *p++ = '%';
1155 p = number(p, pend, sa->sin6_scope_id, spec);
1156 }
1157 *p = '\0';
1158
1159 return string(buf, end, ip6_addr, spec);
1160 }
1161
1162 static noinline_for_stack
ip4_addr_string_sa(char * buf,char * end,const struct sockaddr_in * sa,struct printf_spec spec,const char * fmt)1163 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1164 struct printf_spec spec, const char *fmt)
1165 {
1166 bool have_p = false;
1167 char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1168 char *pend = ip4_addr + sizeof(ip4_addr);
1169 const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1170 char fmt4[3] = { fmt[0], '4', 0 };
1171
1172 fmt++;
1173 while (isalpha(*++fmt)) {
1174 switch (*fmt) {
1175 case 'p':
1176 have_p = true;
1177 break;
1178 case 'h':
1179 case 'l':
1180 case 'n':
1181 case 'b':
1182 fmt4[2] = *fmt;
1183 break;
1184 }
1185 }
1186
1187 p = ip4_string(ip4_addr, addr, fmt4);
1188 if (have_p) {
1189 *p++ = ':';
1190 p = number(p, pend, ntohs(sa->sin_port), spec);
1191 }
1192 *p = '\0';
1193
1194 return string(buf, end, ip4_addr, spec);
1195 }
1196
1197 static noinline_for_stack
escaped_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)1198 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1199 const char *fmt)
1200 {
1201 bool found = true;
1202 int count = 1;
1203 unsigned int flags = 0;
1204 int len;
1205
1206 if (spec.field_width == 0)
1207 return buf; /* nothing to print */
1208
1209 if (ZERO_OR_NULL_PTR(addr))
1210 return string(buf, end, NULL, spec); /* NULL pointer */
1211
1212
1213 do {
1214 switch (fmt[count++]) {
1215 case 'a':
1216 flags |= ESCAPE_ANY;
1217 break;
1218 case 'c':
1219 flags |= ESCAPE_SPECIAL;
1220 break;
1221 case 'h':
1222 flags |= ESCAPE_HEX;
1223 break;
1224 case 'n':
1225 flags |= ESCAPE_NULL;
1226 break;
1227 case 'o':
1228 flags |= ESCAPE_OCTAL;
1229 break;
1230 case 'p':
1231 flags |= ESCAPE_NP;
1232 break;
1233 case 's':
1234 flags |= ESCAPE_SPACE;
1235 break;
1236 default:
1237 found = false;
1238 break;
1239 }
1240 } while (found);
1241
1242 if (!flags)
1243 flags = ESCAPE_ANY_NP;
1244
1245 len = spec.field_width < 0 ? 1 : spec.field_width;
1246
1247 /*
1248 * string_escape_mem() writes as many characters as it can to
1249 * the given buffer, and returns the total size of the output
1250 * had the buffer been big enough.
1251 */
1252 buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1253
1254 return buf;
1255 }
1256
1257 static noinline_for_stack
uuid_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1258 char *uuid_string(char *buf, char *end, const u8 *addr,
1259 struct printf_spec spec, const char *fmt)
1260 {
1261 char uuid[sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")];
1262 char *p = uuid;
1263 int i;
1264 static const u8 be[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
1265 static const u8 le[16] = {3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15};
1266 const u8 *index = be;
1267 bool uc = false;
1268
1269 switch (*(++fmt)) {
1270 case 'L':
1271 uc = true; /* fall-through */
1272 case 'l':
1273 index = le;
1274 break;
1275 case 'B':
1276 uc = true;
1277 break;
1278 }
1279
1280 for (i = 0; i < 16; i++) {
1281 p = hex_byte_pack(p, addr[index[i]]);
1282 switch (i) {
1283 case 3:
1284 case 5:
1285 case 7:
1286 case 9:
1287 *p++ = '-';
1288 break;
1289 }
1290 }
1291
1292 *p = 0;
1293
1294 if (uc) {
1295 p = uuid;
1296 do {
1297 *p = toupper(*p);
1298 } while (*(++p));
1299 }
1300
1301 return string(buf, end, uuid, spec);
1302 }
1303
1304 static
netdev_feature_string(char * buf,char * end,const u8 * addr,struct printf_spec spec)1305 char *netdev_feature_string(char *buf, char *end, const u8 *addr,
1306 struct printf_spec spec)
1307 {
1308 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1309 if (spec.field_width == -1)
1310 spec.field_width = 2 + 2 * sizeof(netdev_features_t);
1311 spec.base = 16;
1312
1313 return number(buf, end, *(const netdev_features_t *)addr, spec);
1314 }
1315
1316 static noinline_for_stack
address_val(char * buf,char * end,const void * addr,struct printf_spec spec,const char * fmt)1317 char *address_val(char *buf, char *end, const void *addr,
1318 struct printf_spec spec, const char *fmt)
1319 {
1320 unsigned long long num;
1321
1322 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1323 spec.base = 16;
1324
1325 switch (fmt[1]) {
1326 case 'd':
1327 num = *(const dma_addr_t *)addr;
1328 spec.field_width = sizeof(dma_addr_t) * 2 + 2;
1329 break;
1330 case 'p':
1331 default:
1332 num = *(const phys_addr_t *)addr;
1333 spec.field_width = sizeof(phys_addr_t) * 2 + 2;
1334 break;
1335 }
1336
1337 return number(buf, end, num, spec);
1338 }
1339
1340 static noinline_for_stack
clock(char * buf,char * end,struct clk * clk,struct printf_spec spec,const char * fmt)1341 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1342 const char *fmt)
1343 {
1344 if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1345 return string(buf, end, NULL, spec);
1346
1347 switch (fmt[1]) {
1348 case 'n':
1349 default:
1350 #ifdef CONFIG_COMMON_CLK
1351 return string(buf, end, __clk_get_name(clk), spec);
1352 #else
1353 spec.base = 16;
1354 spec.field_width = sizeof(unsigned long) * 2 + 2;
1355 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1356 return number(buf, end, (unsigned long)clk, spec);
1357 #endif
1358 }
1359 }
1360
1361 int kptr_restrict __read_mostly;
1362
1363 /*
1364 * Show a '%p' thing. A kernel extension is that the '%p' is followed
1365 * by an extra set of alphanumeric characters that are extended format
1366 * specifiers.
1367 *
1368 * Right now we handle:
1369 *
1370 * - 'F' For symbolic function descriptor pointers with offset
1371 * - 'f' For simple symbolic function names without offset
1372 * - 'S' For symbolic direct pointers with offset
1373 * - 's' For symbolic direct pointers without offset
1374 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1375 * - 'B' For backtraced symbolic direct pointers with offset
1376 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1377 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1378 * - 'b[l]' For a bitmap, the number of bits is determined by the field
1379 * width which must be explicitly specified either as part of the
1380 * format string '%32b[l]' or through '%*b[l]', [l] selects
1381 * range-list format instead of hex format
1382 * - 'M' For a 6-byte MAC address, it prints the address in the
1383 * usual colon-separated hex notation
1384 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1385 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1386 * with a dash-separated hex notation
1387 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1388 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1389 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1390 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
1391 * [S][pfs]
1392 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1393 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1394 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1395 * IPv6 omits the colons (01020304...0f)
1396 * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1397 * [S][pfs]
1398 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1399 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1400 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1401 * - 'I[6S]c' for IPv6 addresses printed as specified by
1402 * http://tools.ietf.org/html/rfc5952
1403 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1404 * of the following flags (see string_escape_mem() for the
1405 * details):
1406 * a - ESCAPE_ANY
1407 * c - ESCAPE_SPECIAL
1408 * h - ESCAPE_HEX
1409 * n - ESCAPE_NULL
1410 * o - ESCAPE_OCTAL
1411 * p - ESCAPE_NP
1412 * s - ESCAPE_SPACE
1413 * By default ESCAPE_ANY_NP is used.
1414 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1415 * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1416 * Options for %pU are:
1417 * b big endian lower case hex (default)
1418 * B big endian UPPER case hex
1419 * l little endian lower case hex
1420 * L little endian UPPER case hex
1421 * big endian output byte order is:
1422 * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1423 * little endian output byte order is:
1424 * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1425 * - 'V' For a struct va_format which contains a format string * and va_list *,
1426 * call vsnprintf(->format, *->va_list).
1427 * Implements a "recursive vsnprintf".
1428 * Do not use this feature without some mechanism to verify the
1429 * correctness of the format string and va_list arguments.
1430 * - 'K' For a kernel pointer that should be hidden from unprivileged users
1431 * - 'NF' For a netdev_features_t
1432 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1433 * a certain separator (' ' by default):
1434 * C colon
1435 * D dash
1436 * N no separator
1437 * The maximum supported length is 64 bytes of the input. Consider
1438 * to use print_hex_dump() for the larger input.
1439 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1440 * (default assumed to be phys_addr_t, passed by reference)
1441 * - 'd[234]' For a dentry name (optionally 2-4 last components)
1442 * - 'D[234]' Same as 'd' but for a struct file
1443 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1444 * (legacy clock framework) of the clock
1445 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1446 * (legacy clock framework) of the clock
1447 * - 'Cr' For a clock, it prints the current rate of the clock
1448 *
1449 * ** Please update also Documentation/printk-formats.txt when making changes **
1450 *
1451 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1452 * function pointers are really function descriptors, which contain a
1453 * pointer to the real address.
1454 */
1455 static noinline_for_stack
pointer(const char * fmt,char * buf,char * end,void * ptr,struct printf_spec spec)1456 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1457 struct printf_spec spec)
1458 {
1459 const int default_width = 2 * sizeof(void *);
1460
1461 if (!ptr && *fmt != 'K') {
1462 /*
1463 * Print (null) with the same width as a pointer so it makes
1464 * tabular output look nice.
1465 */
1466 if (spec.field_width == -1)
1467 spec.field_width = default_width;
1468 return string(buf, end, "(null)", spec);
1469 }
1470
1471 switch (*fmt) {
1472 case 'F':
1473 case 'f':
1474 ptr = dereference_function_descriptor(ptr);
1475 /* Fallthrough */
1476 case 'S':
1477 case 's':
1478 case 'B':
1479 return symbol_string(buf, end, ptr, spec, fmt);
1480 case 'R':
1481 case 'r':
1482 return resource_string(buf, end, ptr, spec, fmt);
1483 case 'h':
1484 return hex_string(buf, end, ptr, spec, fmt);
1485 case 'b':
1486 switch (fmt[1]) {
1487 case 'l':
1488 return bitmap_list_string(buf, end, ptr, spec, fmt);
1489 default:
1490 return bitmap_string(buf, end, ptr, spec, fmt);
1491 }
1492 case 'M': /* Colon separated: 00:01:02:03:04:05 */
1493 case 'm': /* Contiguous: 000102030405 */
1494 /* [mM]F (FDDI) */
1495 /* [mM]R (Reverse order; Bluetooth) */
1496 return mac_address_string(buf, end, ptr, spec, fmt);
1497 case 'I': /* Formatted IP supported
1498 * 4: 1.2.3.4
1499 * 6: 0001:0203:...:0708
1500 * 6c: 1::708 or 1::1.2.3.4
1501 */
1502 case 'i': /* Contiguous:
1503 * 4: 001.002.003.004
1504 * 6: 000102...0f
1505 */
1506 switch (fmt[1]) {
1507 case '6':
1508 return ip6_addr_string(buf, end, ptr, spec, fmt);
1509 case '4':
1510 return ip4_addr_string(buf, end, ptr, spec, fmt);
1511 case 'S': {
1512 const union {
1513 struct sockaddr raw;
1514 struct sockaddr_in v4;
1515 struct sockaddr_in6 v6;
1516 } *sa = ptr;
1517
1518 switch (sa->raw.sa_family) {
1519 case AF_INET:
1520 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1521 case AF_INET6:
1522 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1523 default:
1524 return string(buf, end, "(invalid address)", spec);
1525 }}
1526 }
1527 break;
1528 case 'E':
1529 return escaped_string(buf, end, ptr, spec, fmt);
1530 case 'U':
1531 return uuid_string(buf, end, ptr, spec, fmt);
1532 case 'V':
1533 {
1534 va_list va;
1535
1536 va_copy(va, *((struct va_format *)ptr)->va);
1537 buf += vsnprintf(buf, end > buf ? end - buf : 0,
1538 ((struct va_format *)ptr)->fmt, va);
1539 va_end(va);
1540 return buf;
1541 }
1542 case 'K':
1543 /*
1544 * %pK cannot be used in IRQ context because its test
1545 * for CAP_SYSLOG would be meaningless.
1546 */
1547 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
1548 in_nmi())) {
1549 if (spec.field_width == -1)
1550 spec.field_width = default_width;
1551 return string(buf, end, "pK-error", spec);
1552 }
1553
1554 switch (kptr_restrict) {
1555 case 0:
1556 /* Always print %pK values */
1557 break;
1558 case 1: {
1559 /*
1560 * Only print the real pointer value if the current
1561 * process has CAP_SYSLOG and is running with the
1562 * same credentials it started with. This is because
1563 * access to files is checked at open() time, but %pK
1564 * checks permission at read() time. We don't want to
1565 * leak pointer values if a binary opens a file using
1566 * %pK and then elevates privileges before reading it.
1567 */
1568 const struct cred *cred = current_cred();
1569
1570 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
1571 !uid_eq(cred->euid, cred->uid) ||
1572 !gid_eq(cred->egid, cred->gid))
1573 ptr = NULL;
1574 break;
1575 }
1576 case 2:
1577 default:
1578 /* Always print 0's for %pK */
1579 ptr = NULL;
1580 break;
1581 }
1582 break;
1583
1584 case 'N':
1585 switch (fmt[1]) {
1586 case 'F':
1587 return netdev_feature_string(buf, end, ptr, spec);
1588 }
1589 break;
1590 case 'a':
1591 return address_val(buf, end, ptr, spec, fmt);
1592 case 'd':
1593 return dentry_name(buf, end, ptr, spec, fmt);
1594 case 'C':
1595 return clock(buf, end, ptr, spec, fmt);
1596 case 'D':
1597 return dentry_name(buf, end,
1598 ((const struct file *)ptr)->f_path.dentry,
1599 spec, fmt);
1600 }
1601 spec.flags |= SMALL;
1602 if (spec.field_width == -1) {
1603 spec.field_width = default_width;
1604 spec.flags |= ZEROPAD;
1605 }
1606 spec.base = 16;
1607
1608 return number(buf, end, (unsigned long) ptr, spec);
1609 }
1610
1611 /*
1612 * Helper function to decode printf style format.
1613 * Each call decode a token from the format and return the
1614 * number of characters read (or likely the delta where it wants
1615 * to go on the next call).
1616 * The decoded token is returned through the parameters
1617 *
1618 * 'h', 'l', or 'L' for integer fields
1619 * 'z' support added 23/7/1999 S.H.
1620 * 'z' changed to 'Z' --davidm 1/25/99
1621 * 't' added for ptrdiff_t
1622 *
1623 * @fmt: the format string
1624 * @type of the token returned
1625 * @flags: various flags such as +, -, # tokens..
1626 * @field_width: overwritten width
1627 * @base: base of the number (octal, hex, ...)
1628 * @precision: precision of a number
1629 * @qualifier: qualifier of a number (long, size_t, ...)
1630 */
1631 static noinline_for_stack
format_decode(const char * fmt,struct printf_spec * spec)1632 int format_decode(const char *fmt, struct printf_spec *spec)
1633 {
1634 const char *start = fmt;
1635
1636 /* we finished early by reading the field width */
1637 if (spec->type == FORMAT_TYPE_WIDTH) {
1638 if (spec->field_width < 0) {
1639 spec->field_width = -spec->field_width;
1640 spec->flags |= LEFT;
1641 }
1642 spec->type = FORMAT_TYPE_NONE;
1643 goto precision;
1644 }
1645
1646 /* we finished early by reading the precision */
1647 if (spec->type == FORMAT_TYPE_PRECISION) {
1648 if (spec->precision < 0)
1649 spec->precision = 0;
1650
1651 spec->type = FORMAT_TYPE_NONE;
1652 goto qualifier;
1653 }
1654
1655 /* By default */
1656 spec->type = FORMAT_TYPE_NONE;
1657
1658 for (; *fmt ; ++fmt) {
1659 if (*fmt == '%')
1660 break;
1661 }
1662
1663 /* Return the current non-format string */
1664 if (fmt != start || !*fmt)
1665 return fmt - start;
1666
1667 /* Process flags */
1668 spec->flags = 0;
1669
1670 while (1) { /* this also skips first '%' */
1671 bool found = true;
1672
1673 ++fmt;
1674
1675 switch (*fmt) {
1676 case '-': spec->flags |= LEFT; break;
1677 case '+': spec->flags |= PLUS; break;
1678 case ' ': spec->flags |= SPACE; break;
1679 case '#': spec->flags |= SPECIAL; break;
1680 case '0': spec->flags |= ZEROPAD; break;
1681 default: found = false;
1682 }
1683
1684 if (!found)
1685 break;
1686 }
1687
1688 /* get field width */
1689 spec->field_width = -1;
1690
1691 if (isdigit(*fmt))
1692 spec->field_width = skip_atoi(&fmt);
1693 else if (*fmt == '*') {
1694 /* it's the next argument */
1695 spec->type = FORMAT_TYPE_WIDTH;
1696 return ++fmt - start;
1697 }
1698
1699 precision:
1700 /* get the precision */
1701 spec->precision = -1;
1702 if (*fmt == '.') {
1703 ++fmt;
1704 if (isdigit(*fmt)) {
1705 spec->precision = skip_atoi(&fmt);
1706 if (spec->precision < 0)
1707 spec->precision = 0;
1708 } else if (*fmt == '*') {
1709 /* it's the next argument */
1710 spec->type = FORMAT_TYPE_PRECISION;
1711 return ++fmt - start;
1712 }
1713 }
1714
1715 qualifier:
1716 /* get the conversion qualifier */
1717 spec->qualifier = -1;
1718 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1719 _tolower(*fmt) == 'z' || *fmt == 't') {
1720 spec->qualifier = *fmt++;
1721 if (unlikely(spec->qualifier == *fmt)) {
1722 if (spec->qualifier == 'l') {
1723 spec->qualifier = 'L';
1724 ++fmt;
1725 } else if (spec->qualifier == 'h') {
1726 spec->qualifier = 'H';
1727 ++fmt;
1728 }
1729 }
1730 }
1731
1732 /* default base */
1733 spec->base = 10;
1734 switch (*fmt) {
1735 case 'c':
1736 spec->type = FORMAT_TYPE_CHAR;
1737 return ++fmt - start;
1738
1739 case 's':
1740 spec->type = FORMAT_TYPE_STR;
1741 return ++fmt - start;
1742
1743 case 'p':
1744 spec->type = FORMAT_TYPE_PTR;
1745 return ++fmt - start;
1746
1747 case '%':
1748 spec->type = FORMAT_TYPE_PERCENT_CHAR;
1749 return ++fmt - start;
1750
1751 /* integer number formats - set up the flags and "break" */
1752 case 'o':
1753 spec->base = 8;
1754 break;
1755
1756 case 'x':
1757 spec->flags |= SMALL;
1758
1759 case 'X':
1760 spec->base = 16;
1761 break;
1762
1763 case 'd':
1764 case 'i':
1765 spec->flags |= SIGN;
1766 case 'u':
1767 break;
1768
1769 case 'n':
1770 /*
1771 * Since %n poses a greater security risk than
1772 * utility, treat it as any other invalid or
1773 * unsupported format specifier.
1774 */
1775 /* Fall-through */
1776
1777 default:
1778 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
1779 spec->type = FORMAT_TYPE_INVALID;
1780 return fmt - start;
1781 }
1782
1783 if (spec->qualifier == 'L')
1784 spec->type = FORMAT_TYPE_LONG_LONG;
1785 else if (spec->qualifier == 'l') {
1786 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
1787 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
1788 } else if (_tolower(spec->qualifier) == 'z') {
1789 spec->type = FORMAT_TYPE_SIZE_T;
1790 } else if (spec->qualifier == 't') {
1791 spec->type = FORMAT_TYPE_PTRDIFF;
1792 } else if (spec->qualifier == 'H') {
1793 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
1794 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
1795 } else if (spec->qualifier == 'h') {
1796 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
1797 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
1798 } else {
1799 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
1800 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
1801 }
1802
1803 return ++fmt - start;
1804 }
1805
1806 /**
1807 * vsnprintf - Format a string and place it in a buffer
1808 * @buf: The buffer to place the result into
1809 * @size: The size of the buffer, including the trailing null space
1810 * @fmt: The format string to use
1811 * @args: Arguments for the format string
1812 *
1813 * This function generally follows C99 vsnprintf, but has some
1814 * extensions and a few limitations:
1815 *
1816 * %n is unsupported
1817 * %p* is handled by pointer()
1818 *
1819 * See pointer() or Documentation/printk-formats.txt for more
1820 * extensive description.
1821 *
1822 * ** Please update the documentation in both places when making changes **
1823 *
1824 * The return value is the number of characters which would
1825 * be generated for the given input, excluding the trailing
1826 * '\0', as per ISO C99. If you want to have the exact
1827 * number of characters written into @buf as return value
1828 * (not including the trailing '\0'), use vscnprintf(). If the
1829 * return is greater than or equal to @size, the resulting
1830 * string is truncated.
1831 *
1832 * If you're not already dealing with a va_list consider using snprintf().
1833 */
vsnprintf(char * buf,size_t size,const char * fmt,va_list args)1834 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1835 {
1836 unsigned long long num;
1837 char *str, *end;
1838 struct printf_spec spec = {0};
1839
1840 /* Reject out-of-range values early. Large positive sizes are
1841 used for unknown buffer sizes. */
1842 if (WARN_ON_ONCE(size > INT_MAX))
1843 return 0;
1844
1845 str = buf;
1846 end = buf + size;
1847
1848 /* Make sure end is always >= buf */
1849 if (end < buf) {
1850 end = ((void *)-1);
1851 size = end - buf;
1852 }
1853
1854 while (*fmt) {
1855 const char *old_fmt = fmt;
1856 int read = format_decode(fmt, &spec);
1857
1858 fmt += read;
1859
1860 switch (spec.type) {
1861 case FORMAT_TYPE_NONE: {
1862 int copy = read;
1863 if (str < end) {
1864 if (copy > end - str)
1865 copy = end - str;
1866 memcpy(str, old_fmt, copy);
1867 }
1868 str += read;
1869 break;
1870 }
1871
1872 case FORMAT_TYPE_WIDTH:
1873 spec.field_width = va_arg(args, int);
1874 break;
1875
1876 case FORMAT_TYPE_PRECISION:
1877 spec.precision = va_arg(args, int);
1878 break;
1879
1880 case FORMAT_TYPE_CHAR: {
1881 char c;
1882
1883 if (!(spec.flags & LEFT)) {
1884 while (--spec.field_width > 0) {
1885 if (str < end)
1886 *str = ' ';
1887 ++str;
1888
1889 }
1890 }
1891 c = (unsigned char) va_arg(args, int);
1892 if (str < end)
1893 *str = c;
1894 ++str;
1895 while (--spec.field_width > 0) {
1896 if (str < end)
1897 *str = ' ';
1898 ++str;
1899 }
1900 break;
1901 }
1902
1903 case FORMAT_TYPE_STR:
1904 str = string(str, end, va_arg(args, char *), spec);
1905 break;
1906
1907 case FORMAT_TYPE_PTR:
1908 str = pointer(fmt, str, end, va_arg(args, void *),
1909 spec);
1910 while (isalnum(*fmt))
1911 fmt++;
1912 break;
1913
1914 case FORMAT_TYPE_PERCENT_CHAR:
1915 if (str < end)
1916 *str = '%';
1917 ++str;
1918 break;
1919
1920 case FORMAT_TYPE_INVALID:
1921 /*
1922 * Presumably the arguments passed gcc's type
1923 * checking, but there is no safe or sane way
1924 * for us to continue parsing the format and
1925 * fetching from the va_list; the remaining
1926 * specifiers and arguments would be out of
1927 * sync.
1928 */
1929 goto out;
1930
1931 default:
1932 switch (spec.type) {
1933 case FORMAT_TYPE_LONG_LONG:
1934 num = va_arg(args, long long);
1935 break;
1936 case FORMAT_TYPE_ULONG:
1937 num = va_arg(args, unsigned long);
1938 break;
1939 case FORMAT_TYPE_LONG:
1940 num = va_arg(args, long);
1941 break;
1942 case FORMAT_TYPE_SIZE_T:
1943 if (spec.flags & SIGN)
1944 num = va_arg(args, ssize_t);
1945 else
1946 num = va_arg(args, size_t);
1947 break;
1948 case FORMAT_TYPE_PTRDIFF:
1949 num = va_arg(args, ptrdiff_t);
1950 break;
1951 case FORMAT_TYPE_UBYTE:
1952 num = (unsigned char) va_arg(args, int);
1953 break;
1954 case FORMAT_TYPE_BYTE:
1955 num = (signed char) va_arg(args, int);
1956 break;
1957 case FORMAT_TYPE_USHORT:
1958 num = (unsigned short) va_arg(args, int);
1959 break;
1960 case FORMAT_TYPE_SHORT:
1961 num = (short) va_arg(args, int);
1962 break;
1963 case FORMAT_TYPE_INT:
1964 num = (int) va_arg(args, int);
1965 break;
1966 default:
1967 num = va_arg(args, unsigned int);
1968 }
1969
1970 str = number(str, end, num, spec);
1971 }
1972 }
1973
1974 out:
1975 if (size > 0) {
1976 if (str < end)
1977 *str = '\0';
1978 else
1979 end[-1] = '\0';
1980 }
1981
1982 /* the trailing null byte doesn't count towards the total */
1983 return str-buf;
1984
1985 }
1986 EXPORT_SYMBOL(vsnprintf);
1987
1988 /**
1989 * vscnprintf - Format a string and place it in a buffer
1990 * @buf: The buffer to place the result into
1991 * @size: The size of the buffer, including the trailing null space
1992 * @fmt: The format string to use
1993 * @args: Arguments for the format string
1994 *
1995 * The return value is the number of characters which have been written into
1996 * the @buf not including the trailing '\0'. If @size is == 0 the function
1997 * returns 0.
1998 *
1999 * If you're not already dealing with a va_list consider using scnprintf().
2000 *
2001 * See the vsnprintf() documentation for format string extensions over C99.
2002 */
vscnprintf(char * buf,size_t size,const char * fmt,va_list args)2003 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2004 {
2005 int i;
2006
2007 i = vsnprintf(buf, size, fmt, args);
2008
2009 if (likely(i < size))
2010 return i;
2011 if (size != 0)
2012 return size - 1;
2013 return 0;
2014 }
2015 EXPORT_SYMBOL(vscnprintf);
2016
2017 /**
2018 * snprintf - Format a string and place it in a buffer
2019 * @buf: The buffer to place the result into
2020 * @size: The size of the buffer, including the trailing null space
2021 * @fmt: The format string to use
2022 * @...: Arguments for the format string
2023 *
2024 * The return value is the number of characters which would be
2025 * generated for the given input, excluding the trailing null,
2026 * as per ISO C99. If the return is greater than or equal to
2027 * @size, the resulting string is truncated.
2028 *
2029 * See the vsnprintf() documentation for format string extensions over C99.
2030 */
snprintf(char * buf,size_t size,const char * fmt,...)2031 int snprintf(char *buf, size_t size, const char *fmt, ...)
2032 {
2033 va_list args;
2034 int i;
2035
2036 va_start(args, fmt);
2037 i = vsnprintf(buf, size, fmt, args);
2038 va_end(args);
2039
2040 return i;
2041 }
2042 EXPORT_SYMBOL(snprintf);
2043
2044 /**
2045 * scnprintf - Format a string and place it in a buffer
2046 * @buf: The buffer to place the result into
2047 * @size: The size of the buffer, including the trailing null space
2048 * @fmt: The format string to use
2049 * @...: Arguments for the format string
2050 *
2051 * The return value is the number of characters written into @buf not including
2052 * the trailing '\0'. If @size is == 0 the function returns 0.
2053 */
2054
scnprintf(char * buf,size_t size,const char * fmt,...)2055 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2056 {
2057 va_list args;
2058 int i;
2059
2060 va_start(args, fmt);
2061 i = vscnprintf(buf, size, fmt, args);
2062 va_end(args);
2063
2064 return i;
2065 }
2066 EXPORT_SYMBOL(scnprintf);
2067
2068 /**
2069 * vsprintf - Format a string and place it in a buffer
2070 * @buf: The buffer to place the result into
2071 * @fmt: The format string to use
2072 * @args: Arguments for the format string
2073 *
2074 * The function returns the number of characters written
2075 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2076 * buffer overflows.
2077 *
2078 * If you're not already dealing with a va_list consider using sprintf().
2079 *
2080 * See the vsnprintf() documentation for format string extensions over C99.
2081 */
vsprintf(char * buf,const char * fmt,va_list args)2082 int vsprintf(char *buf, const char *fmt, va_list args)
2083 {
2084 return vsnprintf(buf, INT_MAX, fmt, args);
2085 }
2086 EXPORT_SYMBOL(vsprintf);
2087
2088 /**
2089 * sprintf - Format a string and place it in a buffer
2090 * @buf: The buffer to place the result into
2091 * @fmt: The format string to use
2092 * @...: Arguments for the format string
2093 *
2094 * The function returns the number of characters written
2095 * into @buf. Use snprintf() or scnprintf() in order to avoid
2096 * buffer overflows.
2097 *
2098 * See the vsnprintf() documentation for format string extensions over C99.
2099 */
sprintf(char * buf,const char * fmt,...)2100 int sprintf(char *buf, const char *fmt, ...)
2101 {
2102 va_list args;
2103 int i;
2104
2105 va_start(args, fmt);
2106 i = vsnprintf(buf, INT_MAX, fmt, args);
2107 va_end(args);
2108
2109 return i;
2110 }
2111 EXPORT_SYMBOL(sprintf);
2112
2113 #ifdef CONFIG_BINARY_PRINTF
2114 /*
2115 * bprintf service:
2116 * vbin_printf() - VA arguments to binary data
2117 * bstr_printf() - Binary data to text string
2118 */
2119
2120 /**
2121 * vbin_printf - Parse a format string and place args' binary value in a buffer
2122 * @bin_buf: The buffer to place args' binary value
2123 * @size: The size of the buffer(by words(32bits), not characters)
2124 * @fmt: The format string to use
2125 * @args: Arguments for the format string
2126 *
2127 * The format follows C99 vsnprintf, except %n is ignored, and its argument
2128 * is skipped.
2129 *
2130 * The return value is the number of words(32bits) which would be generated for
2131 * the given input.
2132 *
2133 * NOTE:
2134 * If the return value is greater than @size, the resulting bin_buf is NOT
2135 * valid for bstr_printf().
2136 */
vbin_printf(u32 * bin_buf,size_t size,const char * fmt,va_list args)2137 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2138 {
2139 struct printf_spec spec = {0};
2140 char *str, *end;
2141
2142 str = (char *)bin_buf;
2143 end = (char *)(bin_buf + size);
2144
2145 #define save_arg(type) \
2146 do { \
2147 if (sizeof(type) == 8) { \
2148 unsigned long long value; \
2149 str = PTR_ALIGN(str, sizeof(u32)); \
2150 value = va_arg(args, unsigned long long); \
2151 if (str + sizeof(type) <= end) { \
2152 *(u32 *)str = *(u32 *)&value; \
2153 *(u32 *)(str + 4) = *((u32 *)&value + 1); \
2154 } \
2155 } else { \
2156 unsigned long value; \
2157 str = PTR_ALIGN(str, sizeof(type)); \
2158 value = va_arg(args, int); \
2159 if (str + sizeof(type) <= end) \
2160 *(typeof(type) *)str = (type)value; \
2161 } \
2162 str += sizeof(type); \
2163 } while (0)
2164
2165 while (*fmt) {
2166 int read = format_decode(fmt, &spec);
2167
2168 fmt += read;
2169
2170 switch (spec.type) {
2171 case FORMAT_TYPE_NONE:
2172 case FORMAT_TYPE_PERCENT_CHAR:
2173 break;
2174 case FORMAT_TYPE_INVALID:
2175 goto out;
2176
2177 case FORMAT_TYPE_WIDTH:
2178 case FORMAT_TYPE_PRECISION:
2179 save_arg(int);
2180 break;
2181
2182 case FORMAT_TYPE_CHAR:
2183 save_arg(char);
2184 break;
2185
2186 case FORMAT_TYPE_STR: {
2187 const char *save_str = va_arg(args, char *);
2188 size_t len;
2189
2190 if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2191 || (unsigned long)save_str < PAGE_SIZE)
2192 save_str = "(null)";
2193 len = strlen(save_str) + 1;
2194 if (str + len < end)
2195 memcpy(str, save_str, len);
2196 str += len;
2197 break;
2198 }
2199
2200 case FORMAT_TYPE_PTR:
2201 save_arg(void *);
2202 /* skip all alphanumeric pointer suffixes */
2203 while (isalnum(*fmt))
2204 fmt++;
2205 break;
2206
2207 default:
2208 switch (spec.type) {
2209
2210 case FORMAT_TYPE_LONG_LONG:
2211 save_arg(long long);
2212 break;
2213 case FORMAT_TYPE_ULONG:
2214 case FORMAT_TYPE_LONG:
2215 save_arg(unsigned long);
2216 break;
2217 case FORMAT_TYPE_SIZE_T:
2218 save_arg(size_t);
2219 break;
2220 case FORMAT_TYPE_PTRDIFF:
2221 save_arg(ptrdiff_t);
2222 break;
2223 case FORMAT_TYPE_UBYTE:
2224 case FORMAT_TYPE_BYTE:
2225 save_arg(char);
2226 break;
2227 case FORMAT_TYPE_USHORT:
2228 case FORMAT_TYPE_SHORT:
2229 save_arg(short);
2230 break;
2231 default:
2232 save_arg(int);
2233 }
2234 }
2235 }
2236
2237 out:
2238 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2239 #undef save_arg
2240 }
2241 EXPORT_SYMBOL_GPL(vbin_printf);
2242
2243 /**
2244 * bstr_printf - Format a string from binary arguments and place it in a buffer
2245 * @buf: The buffer to place the result into
2246 * @size: The size of the buffer, including the trailing null space
2247 * @fmt: The format string to use
2248 * @bin_buf: Binary arguments for the format string
2249 *
2250 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2251 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2252 * a binary buffer that generated by vbin_printf.
2253 *
2254 * The format follows C99 vsnprintf, but has some extensions:
2255 * see vsnprintf comment for details.
2256 *
2257 * The return value is the number of characters which would
2258 * be generated for the given input, excluding the trailing
2259 * '\0', as per ISO C99. If you want to have the exact
2260 * number of characters written into @buf as return value
2261 * (not including the trailing '\0'), use vscnprintf(). If the
2262 * return is greater than or equal to @size, the resulting
2263 * string is truncated.
2264 */
bstr_printf(char * buf,size_t size,const char * fmt,const u32 * bin_buf)2265 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2266 {
2267 struct printf_spec spec = {0};
2268 char *str, *end;
2269 const char *args = (const char *)bin_buf;
2270
2271 if (WARN_ON_ONCE(size > INT_MAX))
2272 return 0;
2273
2274 str = buf;
2275 end = buf + size;
2276
2277 #define get_arg(type) \
2278 ({ \
2279 typeof(type) value; \
2280 if (sizeof(type) == 8) { \
2281 args = PTR_ALIGN(args, sizeof(u32)); \
2282 *(u32 *)&value = *(u32 *)args; \
2283 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
2284 } else { \
2285 args = PTR_ALIGN(args, sizeof(type)); \
2286 value = *(typeof(type) *)args; \
2287 } \
2288 args += sizeof(type); \
2289 value; \
2290 })
2291
2292 /* Make sure end is always >= buf */
2293 if (end < buf) {
2294 end = ((void *)-1);
2295 size = end - buf;
2296 }
2297
2298 while (*fmt) {
2299 const char *old_fmt = fmt;
2300 int read = format_decode(fmt, &spec);
2301
2302 fmt += read;
2303
2304 switch (spec.type) {
2305 case FORMAT_TYPE_NONE: {
2306 int copy = read;
2307 if (str < end) {
2308 if (copy > end - str)
2309 copy = end - str;
2310 memcpy(str, old_fmt, copy);
2311 }
2312 str += read;
2313 break;
2314 }
2315
2316 case FORMAT_TYPE_WIDTH:
2317 spec.field_width = get_arg(int);
2318 break;
2319
2320 case FORMAT_TYPE_PRECISION:
2321 spec.precision = get_arg(int);
2322 break;
2323
2324 case FORMAT_TYPE_CHAR: {
2325 char c;
2326
2327 if (!(spec.flags & LEFT)) {
2328 while (--spec.field_width > 0) {
2329 if (str < end)
2330 *str = ' ';
2331 ++str;
2332 }
2333 }
2334 c = (unsigned char) get_arg(char);
2335 if (str < end)
2336 *str = c;
2337 ++str;
2338 while (--spec.field_width > 0) {
2339 if (str < end)
2340 *str = ' ';
2341 ++str;
2342 }
2343 break;
2344 }
2345
2346 case FORMAT_TYPE_STR: {
2347 const char *str_arg = args;
2348 args += strlen(str_arg) + 1;
2349 str = string(str, end, (char *)str_arg, spec);
2350 break;
2351 }
2352
2353 case FORMAT_TYPE_PTR:
2354 str = pointer(fmt, str, end, get_arg(void *), spec);
2355 while (isalnum(*fmt))
2356 fmt++;
2357 break;
2358
2359 case FORMAT_TYPE_PERCENT_CHAR:
2360 if (str < end)
2361 *str = '%';
2362 ++str;
2363 break;
2364
2365 case FORMAT_TYPE_INVALID:
2366 goto out;
2367
2368 default: {
2369 unsigned long long num;
2370
2371 switch (spec.type) {
2372
2373 case FORMAT_TYPE_LONG_LONG:
2374 num = get_arg(long long);
2375 break;
2376 case FORMAT_TYPE_ULONG:
2377 case FORMAT_TYPE_LONG:
2378 num = get_arg(unsigned long);
2379 break;
2380 case FORMAT_TYPE_SIZE_T:
2381 num = get_arg(size_t);
2382 break;
2383 case FORMAT_TYPE_PTRDIFF:
2384 num = get_arg(ptrdiff_t);
2385 break;
2386 case FORMAT_TYPE_UBYTE:
2387 num = get_arg(unsigned char);
2388 break;
2389 case FORMAT_TYPE_BYTE:
2390 num = get_arg(signed char);
2391 break;
2392 case FORMAT_TYPE_USHORT:
2393 num = get_arg(unsigned short);
2394 break;
2395 case FORMAT_TYPE_SHORT:
2396 num = get_arg(short);
2397 break;
2398 case FORMAT_TYPE_UINT:
2399 num = get_arg(unsigned int);
2400 break;
2401 default:
2402 num = get_arg(int);
2403 }
2404
2405 str = number(str, end, num, spec);
2406 } /* default: */
2407 } /* switch(spec.type) */
2408 } /* while(*fmt) */
2409
2410 out:
2411 if (size > 0) {
2412 if (str < end)
2413 *str = '\0';
2414 else
2415 end[-1] = '\0';
2416 }
2417
2418 #undef get_arg
2419
2420 /* the trailing null byte doesn't count towards the total */
2421 return str - buf;
2422 }
2423 EXPORT_SYMBOL_GPL(bstr_printf);
2424
2425 /**
2426 * bprintf - Parse a format string and place args' binary value in a buffer
2427 * @bin_buf: The buffer to place args' binary value
2428 * @size: The size of the buffer(by words(32bits), not characters)
2429 * @fmt: The format string to use
2430 * @...: Arguments for the format string
2431 *
2432 * The function returns the number of words(u32) written
2433 * into @bin_buf.
2434 */
bprintf(u32 * bin_buf,size_t size,const char * fmt,...)2435 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2436 {
2437 va_list args;
2438 int ret;
2439
2440 va_start(args, fmt);
2441 ret = vbin_printf(bin_buf, size, fmt, args);
2442 va_end(args);
2443
2444 return ret;
2445 }
2446 EXPORT_SYMBOL_GPL(bprintf);
2447
2448 #endif /* CONFIG_BINARY_PRINTF */
2449
2450 /**
2451 * vsscanf - Unformat a buffer into a list of arguments
2452 * @buf: input buffer
2453 * @fmt: format of buffer
2454 * @args: arguments
2455 */
vsscanf(const char * buf,const char * fmt,va_list args)2456 int vsscanf(const char *buf, const char *fmt, va_list args)
2457 {
2458 const char *str = buf;
2459 char *next;
2460 char digit;
2461 int num = 0;
2462 u8 qualifier;
2463 unsigned int base;
2464 union {
2465 long long s;
2466 unsigned long long u;
2467 } val;
2468 s16 field_width;
2469 bool is_sign;
2470
2471 while (*fmt) {
2472 /* skip any white space in format */
2473 /* white space in format matchs any amount of
2474 * white space, including none, in the input.
2475 */
2476 if (isspace(*fmt)) {
2477 fmt = skip_spaces(++fmt);
2478 str = skip_spaces(str);
2479 }
2480
2481 /* anything that is not a conversion must match exactly */
2482 if (*fmt != '%' && *fmt) {
2483 if (*fmt++ != *str++)
2484 break;
2485 continue;
2486 }
2487
2488 if (!*fmt)
2489 break;
2490 ++fmt;
2491
2492 /* skip this conversion.
2493 * advance both strings to next white space
2494 */
2495 if (*fmt == '*') {
2496 if (!*str)
2497 break;
2498 while (!isspace(*fmt) && *fmt != '%' && *fmt)
2499 fmt++;
2500 while (!isspace(*str) && *str)
2501 str++;
2502 continue;
2503 }
2504
2505 /* get field width */
2506 field_width = -1;
2507 if (isdigit(*fmt)) {
2508 field_width = skip_atoi(&fmt);
2509 if (field_width <= 0)
2510 break;
2511 }
2512
2513 /* get conversion qualifier */
2514 qualifier = -1;
2515 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2516 _tolower(*fmt) == 'z') {
2517 qualifier = *fmt++;
2518 if (unlikely(qualifier == *fmt)) {
2519 if (qualifier == 'h') {
2520 qualifier = 'H';
2521 fmt++;
2522 } else if (qualifier == 'l') {
2523 qualifier = 'L';
2524 fmt++;
2525 }
2526 }
2527 }
2528
2529 if (!*fmt)
2530 break;
2531
2532 if (*fmt == 'n') {
2533 /* return number of characters read so far */
2534 *va_arg(args, int *) = str - buf;
2535 ++fmt;
2536 continue;
2537 }
2538
2539 if (!*str)
2540 break;
2541
2542 base = 10;
2543 is_sign = false;
2544
2545 switch (*fmt++) {
2546 case 'c':
2547 {
2548 char *s = (char *)va_arg(args, char*);
2549 if (field_width == -1)
2550 field_width = 1;
2551 do {
2552 *s++ = *str++;
2553 } while (--field_width > 0 && *str);
2554 num++;
2555 }
2556 continue;
2557 case 's':
2558 {
2559 char *s = (char *)va_arg(args, char *);
2560 if (field_width == -1)
2561 field_width = SHRT_MAX;
2562 /* first, skip leading white space in buffer */
2563 str = skip_spaces(str);
2564
2565 /* now copy until next white space */
2566 while (*str && !isspace(*str) && field_width--)
2567 *s++ = *str++;
2568 *s = '\0';
2569 num++;
2570 }
2571 continue;
2572 case 'o':
2573 base = 8;
2574 break;
2575 case 'x':
2576 case 'X':
2577 base = 16;
2578 break;
2579 case 'i':
2580 base = 0;
2581 case 'd':
2582 is_sign = true;
2583 case 'u':
2584 break;
2585 case '%':
2586 /* looking for '%' in str */
2587 if (*str++ != '%')
2588 return num;
2589 continue;
2590 default:
2591 /* invalid format; stop here */
2592 return num;
2593 }
2594
2595 /* have some sort of integer conversion.
2596 * first, skip white space in buffer.
2597 */
2598 str = skip_spaces(str);
2599
2600 digit = *str;
2601 if (is_sign && digit == '-')
2602 digit = *(str + 1);
2603
2604 if (!digit
2605 || (base == 16 && !isxdigit(digit))
2606 || (base == 10 && !isdigit(digit))
2607 || (base == 8 && (!isdigit(digit) || digit > '7'))
2608 || (base == 0 && !isdigit(digit)))
2609 break;
2610
2611 if (is_sign)
2612 val.s = qualifier != 'L' ?
2613 simple_strtol(str, &next, base) :
2614 simple_strtoll(str, &next, base);
2615 else
2616 val.u = qualifier != 'L' ?
2617 simple_strtoul(str, &next, base) :
2618 simple_strtoull(str, &next, base);
2619
2620 if (field_width > 0 && next - str > field_width) {
2621 if (base == 0)
2622 _parse_integer_fixup_radix(str, &base);
2623 while (next - str > field_width) {
2624 if (is_sign)
2625 val.s = div_s64(val.s, base);
2626 else
2627 val.u = div_u64(val.u, base);
2628 --next;
2629 }
2630 }
2631
2632 switch (qualifier) {
2633 case 'H': /* that's 'hh' in format */
2634 if (is_sign)
2635 *va_arg(args, signed char *) = val.s;
2636 else
2637 *va_arg(args, unsigned char *) = val.u;
2638 break;
2639 case 'h':
2640 if (is_sign)
2641 *va_arg(args, short *) = val.s;
2642 else
2643 *va_arg(args, unsigned short *) = val.u;
2644 break;
2645 case 'l':
2646 if (is_sign)
2647 *va_arg(args, long *) = val.s;
2648 else
2649 *va_arg(args, unsigned long *) = val.u;
2650 break;
2651 case 'L':
2652 if (is_sign)
2653 *va_arg(args, long long *) = val.s;
2654 else
2655 *va_arg(args, unsigned long long *) = val.u;
2656 break;
2657 case 'Z':
2658 case 'z':
2659 *va_arg(args, size_t *) = val.u;
2660 break;
2661 default:
2662 if (is_sign)
2663 *va_arg(args, int *) = val.s;
2664 else
2665 *va_arg(args, unsigned int *) = val.u;
2666 break;
2667 }
2668 num++;
2669
2670 if (!next)
2671 break;
2672 str = next;
2673 }
2674
2675 return num;
2676 }
2677 EXPORT_SYMBOL(vsscanf);
2678
2679 /**
2680 * sscanf - Unformat a buffer into a list of arguments
2681 * @buf: input buffer
2682 * @fmt: formatting of buffer
2683 * @...: resulting arguments
2684 */
sscanf(const char * buf,const char * fmt,...)2685 int sscanf(const char *buf, const char *fmt, ...)
2686 {
2687 va_list args;
2688 int i;
2689
2690 va_start(args, fmt);
2691 i = vsscanf(buf, fmt, args);
2692 va_end(args);
2693
2694 return i;
2695 }
2696 EXPORT_SYMBOL(sscanf);
2697