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