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