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
simple_strntoull(const char * startp,size_t max_chars,char ** endp,unsigned int base)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 */
simple_strtoull(const char * cp,char ** endp,unsigned int base)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 */
simple_strtoul(const char * cp,char ** endp,unsigned int base)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 */
simple_strtol(const char * cp,char ** endp,unsigned int base)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
simple_strntoll(const char * cp,size_t max_chars,char ** endp,unsigned int base)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 */
simple_strtoll(const char * cp,char ** endp,unsigned int base)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
skip_atoi(const char ** s)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
put_dec_trunc8(char * buf,unsigned r)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
put_dec_full8(char * buf,unsigned r)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
put_dec(char * buf,unsigned long long n)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
put_dec_full4(char * buf,unsigned r)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
put_dec_helper4(char * buf,unsigned x)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
put_dec(char * buf,unsigned long long n)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 */
num_to_str(char * buf,int size,unsigned long long num,unsigned int width)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
number(char * buf,char * end,unsigned long long num,struct printf_spec spec)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
special_hex_number(char * buf,char * end,unsigned long long num,int size)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
move_right(char * buf,char * end,unsigned len,unsigned spaces)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
widen_string(char * buf,int n,char * end,struct printf_spec spec)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. */
string_nocheck(char * buf,char * end,const char * s,struct printf_spec spec)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. */
error_string(char * buf,char * end,const char * s,struct printf_spec spec)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 */
check_pointer_msg(const void * ptr)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
check_pointer(char ** buf,char * end,const void * ptr,struct printf_spec spec)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
string(char * buf,char * end,const char * s,struct printf_spec spec)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
pointer_string(char * buf,char * end,const void * ptr,struct printf_spec spec)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
debug_boot_weak_hash_enable(char * str)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
enable_ptr_key_workfn(struct work_struct * work)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(¬_filled_random_ptr_key);
730 }
731
732 static DECLARE_WORK(enable_ptr_key_work, enable_ptr_key_workfn);
733
fill_random_ptr_key(struct notifier_block * nb,unsigned long action,void * data)734 static int fill_random_ptr_key(struct notifier_block *nb,
735 unsigned long action, void *data)
736 {
737 /* This may be in an interrupt handler. */
738 queue_work(system_unbound_wq, &enable_ptr_key_work);
739 return 0;
740 }
741
742 static struct notifier_block random_ready = {
743 .notifier_call = fill_random_ptr_key
744 };
745
initialize_ptr_random(void)746 static int __init initialize_ptr_random(void)
747 {
748 int key_size = sizeof(ptr_key);
749 int ret;
750
751 /* Use hw RNG if available. */
752 if (get_random_bytes_arch(&ptr_key, key_size) == key_size) {
753 static_branch_disable(¬_filled_random_ptr_key);
754 return 0;
755 }
756
757 ret = register_random_ready_notifier(&random_ready);
758 if (!ret) {
759 return 0;
760 } else if (ret == -EALREADY) {
761 /* This is in preemptible context */
762 enable_ptr_key_workfn(&enable_ptr_key_work);
763 return 0;
764 }
765
766 return ret;
767 }
768 early_initcall(initialize_ptr_random);
769
__ptr_to_hashval(const void * ptr,unsigned long * hashval_out)770 static inline int __ptr_to_hashval(const void *ptr, unsigned long *hashval_out)
771 {
772 unsigned long hashval;
773
774 if (static_branch_unlikely(¬_filled_random_ptr_key))
775 return -EAGAIN;
776
777 #ifdef CONFIG_64BIT
778 hashval = (unsigned long)siphash_1u64((u64)ptr, &ptr_key);
779 /*
780 * Mask off the first 32 bits, this makes explicit that we have
781 * modified the address (and 32 bits is plenty for a unique ID).
782 */
783 hashval = hashval & 0xffffffff;
784 #else
785 hashval = (unsigned long)siphash_1u32((u32)ptr, &ptr_key);
786 #endif
787 *hashval_out = hashval;
788 return 0;
789 }
790
ptr_to_hashval(const void * ptr,unsigned long * hashval_out)791 int ptr_to_hashval(const void *ptr, unsigned long *hashval_out)
792 {
793 return __ptr_to_hashval(ptr, hashval_out);
794 }
795
796 /* Maps a pointer to a 32 bit unique identifier. */
ptr_to_id(char * buf,char * end,const void * ptr,struct printf_spec spec)797 static char *ptr_to_id(char *buf, char *end, const void *ptr,
798 struct printf_spec spec)
799 {
800 const char *str = sizeof(ptr) == 8 ? "(____ptrval____)" : "(ptrval)";
801 unsigned long hashval;
802 int ret;
803
804 /*
805 * Print the real pointer value for NULL and error pointers,
806 * as they are not actual addresses.
807 */
808 if (IS_ERR_OR_NULL(ptr))
809 return pointer_string(buf, end, ptr, spec);
810
811 /* When debugging early boot use non-cryptographically secure hash. */
812 if (unlikely(debug_boot_weak_hash)) {
813 hashval = hash_long((unsigned long)ptr, 32);
814 return pointer_string(buf, end, (const void *)hashval, spec);
815 }
816
817 ret = __ptr_to_hashval(ptr, &hashval);
818 if (ret) {
819 spec.field_width = 2 * sizeof(ptr);
820 /* string length must be less than default_width */
821 return error_string(buf, end, str, spec);
822 }
823
824 return pointer_string(buf, end, (const void *)hashval, spec);
825 }
826
827 int kptr_restrict __read_mostly;
828
829 static noinline_for_stack
restricted_pointer(char * buf,char * end,const void * ptr,struct printf_spec spec)830 char *restricted_pointer(char *buf, char *end, const void *ptr,
831 struct printf_spec spec)
832 {
833 switch (kptr_restrict) {
834 case 0:
835 /* Handle as %p, hash and do _not_ leak addresses. */
836 return ptr_to_id(buf, end, ptr, spec);
837 case 1: {
838 const struct cred *cred;
839
840 /*
841 * kptr_restrict==1 cannot be used in IRQ context
842 * because its test for CAP_SYSLOG would be meaningless.
843 */
844 if (in_irq() || in_serving_softirq() || in_nmi()) {
845 if (spec.field_width == -1)
846 spec.field_width = 2 * sizeof(ptr);
847 return error_string(buf, end, "pK-error", spec);
848 }
849
850 /*
851 * Only print the real pointer value if the current
852 * process has CAP_SYSLOG and is running with the
853 * same credentials it started with. This is because
854 * access to files is checked at open() time, but %pK
855 * checks permission at read() time. We don't want to
856 * leak pointer values if a binary opens a file using
857 * %pK and then elevates privileges before reading it.
858 */
859 cred = current_cred();
860 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
861 !uid_eq(cred->euid, cred->uid) ||
862 !gid_eq(cred->egid, cred->gid))
863 ptr = NULL;
864 break;
865 }
866 case 2:
867 default:
868 /* Always print 0's for %pK */
869 ptr = NULL;
870 break;
871 }
872
873 return pointer_string(buf, end, ptr, spec);
874 }
875
876 static noinline_for_stack
dentry_name(char * buf,char * end,const struct dentry * d,struct printf_spec spec,const char * fmt)877 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
878 const char *fmt)
879 {
880 const char *array[4], *s;
881 const struct dentry *p;
882 int depth;
883 int i, n;
884
885 switch (fmt[1]) {
886 case '2': case '3': case '4':
887 depth = fmt[1] - '0';
888 break;
889 default:
890 depth = 1;
891 }
892
893 rcu_read_lock();
894 for (i = 0; i < depth; i++, d = p) {
895 if (check_pointer(&buf, end, d, spec)) {
896 rcu_read_unlock();
897 return buf;
898 }
899
900 p = READ_ONCE(d->d_parent);
901 array[i] = READ_ONCE(d->d_name.name);
902 if (p == d) {
903 if (i)
904 array[i] = "";
905 i++;
906 break;
907 }
908 }
909 s = array[--i];
910 for (n = 0; n != spec.precision; n++, buf++) {
911 char c = *s++;
912 if (!c) {
913 if (!i)
914 break;
915 c = '/';
916 s = array[--i];
917 }
918 if (buf < end)
919 *buf = c;
920 }
921 rcu_read_unlock();
922 return widen_string(buf, n, end, spec);
923 }
924
925 static noinline_for_stack
file_dentry_name(char * buf,char * end,const struct file * f,struct printf_spec spec,const char * fmt)926 char *file_dentry_name(char *buf, char *end, const struct file *f,
927 struct printf_spec spec, const char *fmt)
928 {
929 if (check_pointer(&buf, end, f, spec))
930 return buf;
931
932 return dentry_name(buf, end, f->f_path.dentry, spec, fmt);
933 }
934 #ifdef CONFIG_BLOCK
935 static noinline_for_stack
bdev_name(char * buf,char * end,struct block_device * bdev,struct printf_spec spec,const char * fmt)936 char *bdev_name(char *buf, char *end, struct block_device *bdev,
937 struct printf_spec spec, const char *fmt)
938 {
939 struct gendisk *hd;
940
941 if (check_pointer(&buf, end, bdev, spec))
942 return buf;
943
944 hd = bdev->bd_disk;
945 buf = string(buf, end, hd->disk_name, spec);
946 if (bdev->bd_part->partno) {
947 if (isdigit(hd->disk_name[strlen(hd->disk_name)-1])) {
948 if (buf < end)
949 *buf = 'p';
950 buf++;
951 }
952 buf = number(buf, end, bdev->bd_part->partno, spec);
953 }
954 return buf;
955 }
956 #endif
957
958 static noinline_for_stack
symbol_string(char * buf,char * end,void * ptr,struct printf_spec spec,const char * fmt)959 char *symbol_string(char *buf, char *end, void *ptr,
960 struct printf_spec spec, const char *fmt)
961 {
962 unsigned long value;
963 #ifdef CONFIG_KALLSYMS
964 char sym[KSYM_SYMBOL_LEN];
965 #endif
966
967 if (fmt[1] == 'R')
968 ptr = __builtin_extract_return_addr(ptr);
969 value = (unsigned long)ptr;
970
971 #ifdef CONFIG_KALLSYMS
972 if (*fmt == 'B')
973 sprint_backtrace(sym, value);
974 else if (*fmt != 'f' && *fmt != 's')
975 sprint_symbol(sym, value);
976 else
977 sprint_symbol_no_offset(sym, value);
978
979 return string_nocheck(buf, end, sym, spec);
980 #else
981 return special_hex_number(buf, end, value, sizeof(void *));
982 #endif
983 }
984
985 static const struct printf_spec default_str_spec = {
986 .field_width = -1,
987 .precision = -1,
988 };
989
990 static const struct printf_spec default_flag_spec = {
991 .base = 16,
992 .precision = -1,
993 .flags = SPECIAL | SMALL,
994 };
995
996 static const struct printf_spec default_dec_spec = {
997 .base = 10,
998 .precision = -1,
999 };
1000
1001 static const struct printf_spec default_dec02_spec = {
1002 .base = 10,
1003 .field_width = 2,
1004 .precision = -1,
1005 .flags = ZEROPAD,
1006 };
1007
1008 static const struct printf_spec default_dec04_spec = {
1009 .base = 10,
1010 .field_width = 4,
1011 .precision = -1,
1012 .flags = ZEROPAD,
1013 };
1014
1015 static noinline_for_stack
resource_string(char * buf,char * end,struct resource * res,struct printf_spec spec,const char * fmt)1016 char *resource_string(char *buf, char *end, struct resource *res,
1017 struct printf_spec spec, const char *fmt)
1018 {
1019 #ifndef IO_RSRC_PRINTK_SIZE
1020 #define IO_RSRC_PRINTK_SIZE 6
1021 #endif
1022
1023 #ifndef MEM_RSRC_PRINTK_SIZE
1024 #define MEM_RSRC_PRINTK_SIZE 10
1025 #endif
1026 static const struct printf_spec io_spec = {
1027 .base = 16,
1028 .field_width = IO_RSRC_PRINTK_SIZE,
1029 .precision = -1,
1030 .flags = SPECIAL | SMALL | ZEROPAD,
1031 };
1032 static const struct printf_spec mem_spec = {
1033 .base = 16,
1034 .field_width = MEM_RSRC_PRINTK_SIZE,
1035 .precision = -1,
1036 .flags = SPECIAL | SMALL | ZEROPAD,
1037 };
1038 static const struct printf_spec bus_spec = {
1039 .base = 16,
1040 .field_width = 2,
1041 .precision = -1,
1042 .flags = SMALL | ZEROPAD,
1043 };
1044 static const struct printf_spec str_spec = {
1045 .field_width = -1,
1046 .precision = 10,
1047 .flags = LEFT,
1048 };
1049
1050 /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
1051 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
1052 #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
1053 #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
1054 #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
1055 #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
1056 char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
1057 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
1058
1059 char *p = sym, *pend = sym + sizeof(sym);
1060 int decode = (fmt[0] == 'R') ? 1 : 0;
1061 const struct printf_spec *specp;
1062
1063 if (check_pointer(&buf, end, res, spec))
1064 return buf;
1065
1066 *p++ = '[';
1067 if (res->flags & IORESOURCE_IO) {
1068 p = string_nocheck(p, pend, "io ", str_spec);
1069 specp = &io_spec;
1070 } else if (res->flags & IORESOURCE_MEM) {
1071 p = string_nocheck(p, pend, "mem ", str_spec);
1072 specp = &mem_spec;
1073 } else if (res->flags & IORESOURCE_IRQ) {
1074 p = string_nocheck(p, pend, "irq ", str_spec);
1075 specp = &default_dec_spec;
1076 } else if (res->flags & IORESOURCE_DMA) {
1077 p = string_nocheck(p, pend, "dma ", str_spec);
1078 specp = &default_dec_spec;
1079 } else if (res->flags & IORESOURCE_BUS) {
1080 p = string_nocheck(p, pend, "bus ", str_spec);
1081 specp = &bus_spec;
1082 } else {
1083 p = string_nocheck(p, pend, "??? ", str_spec);
1084 specp = &mem_spec;
1085 decode = 0;
1086 }
1087 if (decode && res->flags & IORESOURCE_UNSET) {
1088 p = string_nocheck(p, pend, "size ", str_spec);
1089 p = number(p, pend, resource_size(res), *specp);
1090 } else {
1091 p = number(p, pend, res->start, *specp);
1092 if (res->start != res->end) {
1093 *p++ = '-';
1094 p = number(p, pend, res->end, *specp);
1095 }
1096 }
1097 if (decode) {
1098 if (res->flags & IORESOURCE_MEM_64)
1099 p = string_nocheck(p, pend, " 64bit", str_spec);
1100 if (res->flags & IORESOURCE_PREFETCH)
1101 p = string_nocheck(p, pend, " pref", str_spec);
1102 if (res->flags & IORESOURCE_WINDOW)
1103 p = string_nocheck(p, pend, " window", str_spec);
1104 if (res->flags & IORESOURCE_DISABLED)
1105 p = string_nocheck(p, pend, " disabled", str_spec);
1106 } else {
1107 p = string_nocheck(p, pend, " flags ", str_spec);
1108 p = number(p, pend, res->flags, default_flag_spec);
1109 }
1110 *p++ = ']';
1111 *p = '\0';
1112
1113 return string_nocheck(buf, end, sym, spec);
1114 }
1115
1116 static noinline_for_stack
hex_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)1117 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1118 const char *fmt)
1119 {
1120 int i, len = 1; /* if we pass '%ph[CDN]', field width remains
1121 negative value, fallback to the default */
1122 char separator;
1123
1124 if (spec.field_width == 0)
1125 /* nothing to print */
1126 return buf;
1127
1128 if (check_pointer(&buf, end, addr, spec))
1129 return buf;
1130
1131 switch (fmt[1]) {
1132 case 'C':
1133 separator = ':';
1134 break;
1135 case 'D':
1136 separator = '-';
1137 break;
1138 case 'N':
1139 separator = 0;
1140 break;
1141 default:
1142 separator = ' ';
1143 break;
1144 }
1145
1146 if (spec.field_width > 0)
1147 len = min_t(int, spec.field_width, 64);
1148
1149 for (i = 0; i < len; ++i) {
1150 if (buf < end)
1151 *buf = hex_asc_hi(addr[i]);
1152 ++buf;
1153 if (buf < end)
1154 *buf = hex_asc_lo(addr[i]);
1155 ++buf;
1156
1157 if (separator && i != len - 1) {
1158 if (buf < end)
1159 *buf = separator;
1160 ++buf;
1161 }
1162 }
1163
1164 return buf;
1165 }
1166
1167 static noinline_for_stack
bitmap_string(char * buf,char * end,unsigned long * bitmap,struct printf_spec spec,const char * fmt)1168 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
1169 struct printf_spec spec, const char *fmt)
1170 {
1171 const int CHUNKSZ = 32;
1172 int nr_bits = max_t(int, spec.field_width, 0);
1173 int i, chunksz;
1174 bool first = true;
1175
1176 if (check_pointer(&buf, end, bitmap, spec))
1177 return buf;
1178
1179 /* reused to print numbers */
1180 spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
1181
1182 chunksz = nr_bits & (CHUNKSZ - 1);
1183 if (chunksz == 0)
1184 chunksz = CHUNKSZ;
1185
1186 i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
1187 for (; i >= 0; i -= CHUNKSZ) {
1188 u32 chunkmask, val;
1189 int word, bit;
1190
1191 chunkmask = ((1ULL << chunksz) - 1);
1192 word = i / BITS_PER_LONG;
1193 bit = i % BITS_PER_LONG;
1194 val = (bitmap[word] >> bit) & chunkmask;
1195
1196 if (!first) {
1197 if (buf < end)
1198 *buf = ',';
1199 buf++;
1200 }
1201 first = false;
1202
1203 spec.field_width = DIV_ROUND_UP(chunksz, 4);
1204 buf = number(buf, end, val, spec);
1205
1206 chunksz = CHUNKSZ;
1207 }
1208 return buf;
1209 }
1210
1211 static noinline_for_stack
bitmap_list_string(char * buf,char * end,unsigned long * bitmap,struct printf_spec spec,const char * fmt)1212 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
1213 struct printf_spec spec, const char *fmt)
1214 {
1215 int nr_bits = max_t(int, spec.field_width, 0);
1216 /* current bit is 'cur', most recently seen range is [rbot, rtop] */
1217 int cur, rbot, rtop;
1218 bool first = true;
1219
1220 if (check_pointer(&buf, end, bitmap, spec))
1221 return buf;
1222
1223 rbot = cur = find_first_bit(bitmap, nr_bits);
1224 while (cur < nr_bits) {
1225 rtop = cur;
1226 cur = find_next_bit(bitmap, nr_bits, cur + 1);
1227 if (cur < nr_bits && cur <= rtop + 1)
1228 continue;
1229
1230 if (!first) {
1231 if (buf < end)
1232 *buf = ',';
1233 buf++;
1234 }
1235 first = false;
1236
1237 buf = number(buf, end, rbot, default_dec_spec);
1238 if (rbot < rtop) {
1239 if (buf < end)
1240 *buf = '-';
1241 buf++;
1242
1243 buf = number(buf, end, rtop, default_dec_spec);
1244 }
1245
1246 rbot = cur;
1247 }
1248 return buf;
1249 }
1250
1251 static noinline_for_stack
mac_address_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)1252 char *mac_address_string(char *buf, char *end, u8 *addr,
1253 struct printf_spec spec, const char *fmt)
1254 {
1255 char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
1256 char *p = mac_addr;
1257 int i;
1258 char separator;
1259 bool reversed = false;
1260
1261 if (check_pointer(&buf, end, addr, spec))
1262 return buf;
1263
1264 switch (fmt[1]) {
1265 case 'F':
1266 separator = '-';
1267 break;
1268
1269 case 'R':
1270 reversed = true;
1271 /* fall through */
1272
1273 default:
1274 separator = ':';
1275 break;
1276 }
1277
1278 for (i = 0; i < 6; i++) {
1279 if (reversed)
1280 p = hex_byte_pack(p, addr[5 - i]);
1281 else
1282 p = hex_byte_pack(p, addr[i]);
1283
1284 if (fmt[0] == 'M' && i != 5)
1285 *p++ = separator;
1286 }
1287 *p = '\0';
1288
1289 return string_nocheck(buf, end, mac_addr, spec);
1290 }
1291
1292 static noinline_for_stack
ip4_string(char * p,const u8 * addr,const char * fmt)1293 char *ip4_string(char *p, const u8 *addr, const char *fmt)
1294 {
1295 int i;
1296 bool leading_zeros = (fmt[0] == 'i');
1297 int index;
1298 int step;
1299
1300 switch (fmt[2]) {
1301 case 'h':
1302 #ifdef __BIG_ENDIAN
1303 index = 0;
1304 step = 1;
1305 #else
1306 index = 3;
1307 step = -1;
1308 #endif
1309 break;
1310 case 'l':
1311 index = 3;
1312 step = -1;
1313 break;
1314 case 'n':
1315 case 'b':
1316 default:
1317 index = 0;
1318 step = 1;
1319 break;
1320 }
1321 for (i = 0; i < 4; i++) {
1322 char temp[4] __aligned(2); /* hold each IP quad in reverse order */
1323 int digits = put_dec_trunc8(temp, addr[index]) - temp;
1324 if (leading_zeros) {
1325 if (digits < 3)
1326 *p++ = '0';
1327 if (digits < 2)
1328 *p++ = '0';
1329 }
1330 /* reverse the digits in the quad */
1331 while (digits--)
1332 *p++ = temp[digits];
1333 if (i < 3)
1334 *p++ = '.';
1335 index += step;
1336 }
1337 *p = '\0';
1338
1339 return p;
1340 }
1341
1342 static noinline_for_stack
ip6_compressed_string(char * p,const char * addr)1343 char *ip6_compressed_string(char *p, const char *addr)
1344 {
1345 int i, j, range;
1346 unsigned char zerolength[8];
1347 int longest = 1;
1348 int colonpos = -1;
1349 u16 word;
1350 u8 hi, lo;
1351 bool needcolon = false;
1352 bool useIPv4;
1353 struct in6_addr in6;
1354
1355 memcpy(&in6, addr, sizeof(struct in6_addr));
1356
1357 useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
1358
1359 memset(zerolength, 0, sizeof(zerolength));
1360
1361 if (useIPv4)
1362 range = 6;
1363 else
1364 range = 8;
1365
1366 /* find position of longest 0 run */
1367 for (i = 0; i < range; i++) {
1368 for (j = i; j < range; j++) {
1369 if (in6.s6_addr16[j] != 0)
1370 break;
1371 zerolength[i]++;
1372 }
1373 }
1374 for (i = 0; i < range; i++) {
1375 if (zerolength[i] > longest) {
1376 longest = zerolength[i];
1377 colonpos = i;
1378 }
1379 }
1380 if (longest == 1) /* don't compress a single 0 */
1381 colonpos = -1;
1382
1383 /* emit address */
1384 for (i = 0; i < range; i++) {
1385 if (i == colonpos) {
1386 if (needcolon || i == 0)
1387 *p++ = ':';
1388 *p++ = ':';
1389 needcolon = false;
1390 i += longest - 1;
1391 continue;
1392 }
1393 if (needcolon) {
1394 *p++ = ':';
1395 needcolon = false;
1396 }
1397 /* hex u16 without leading 0s */
1398 word = ntohs(in6.s6_addr16[i]);
1399 hi = word >> 8;
1400 lo = word & 0xff;
1401 if (hi) {
1402 if (hi > 0x0f)
1403 p = hex_byte_pack(p, hi);
1404 else
1405 *p++ = hex_asc_lo(hi);
1406 p = hex_byte_pack(p, lo);
1407 }
1408 else if (lo > 0x0f)
1409 p = hex_byte_pack(p, lo);
1410 else
1411 *p++ = hex_asc_lo(lo);
1412 needcolon = true;
1413 }
1414
1415 if (useIPv4) {
1416 if (needcolon)
1417 *p++ = ':';
1418 p = ip4_string(p, &in6.s6_addr[12], "I4");
1419 }
1420 *p = '\0';
1421
1422 return p;
1423 }
1424
1425 static noinline_for_stack
ip6_string(char * p,const char * addr,const char * fmt)1426 char *ip6_string(char *p, const char *addr, const char *fmt)
1427 {
1428 int i;
1429
1430 for (i = 0; i < 8; i++) {
1431 p = hex_byte_pack(p, *addr++);
1432 p = hex_byte_pack(p, *addr++);
1433 if (fmt[0] == 'I' && i != 7)
1434 *p++ = ':';
1435 }
1436 *p = '\0';
1437
1438 return p;
1439 }
1440
1441 static noinline_for_stack
ip6_addr_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1442 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1443 struct printf_spec spec, const char *fmt)
1444 {
1445 char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1446
1447 if (fmt[0] == 'I' && fmt[2] == 'c')
1448 ip6_compressed_string(ip6_addr, addr);
1449 else
1450 ip6_string(ip6_addr, addr, fmt);
1451
1452 return string_nocheck(buf, end, ip6_addr, spec);
1453 }
1454
1455 static noinline_for_stack
ip4_addr_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1456 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1457 struct printf_spec spec, const char *fmt)
1458 {
1459 char ip4_addr[sizeof("255.255.255.255")];
1460
1461 ip4_string(ip4_addr, addr, fmt);
1462
1463 return string_nocheck(buf, end, ip4_addr, spec);
1464 }
1465
1466 static noinline_for_stack
ip6_addr_string_sa(char * buf,char * end,const struct sockaddr_in6 * sa,struct printf_spec spec,const char * fmt)1467 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1468 struct printf_spec spec, const char *fmt)
1469 {
1470 bool have_p = false, have_s = false, have_f = false, have_c = false;
1471 char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1472 sizeof(":12345") + sizeof("/123456789") +
1473 sizeof("%1234567890")];
1474 char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1475 const u8 *addr = (const u8 *) &sa->sin6_addr;
1476 char fmt6[2] = { fmt[0], '6' };
1477 u8 off = 0;
1478
1479 fmt++;
1480 while (isalpha(*++fmt)) {
1481 switch (*fmt) {
1482 case 'p':
1483 have_p = true;
1484 break;
1485 case 'f':
1486 have_f = true;
1487 break;
1488 case 's':
1489 have_s = true;
1490 break;
1491 case 'c':
1492 have_c = true;
1493 break;
1494 }
1495 }
1496
1497 if (have_p || have_s || have_f) {
1498 *p = '[';
1499 off = 1;
1500 }
1501
1502 if (fmt6[0] == 'I' && have_c)
1503 p = ip6_compressed_string(ip6_addr + off, addr);
1504 else
1505 p = ip6_string(ip6_addr + off, addr, fmt6);
1506
1507 if (have_p || have_s || have_f)
1508 *p++ = ']';
1509
1510 if (have_p) {
1511 *p++ = ':';
1512 p = number(p, pend, ntohs(sa->sin6_port), spec);
1513 }
1514 if (have_f) {
1515 *p++ = '/';
1516 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1517 IPV6_FLOWINFO_MASK), spec);
1518 }
1519 if (have_s) {
1520 *p++ = '%';
1521 p = number(p, pend, sa->sin6_scope_id, spec);
1522 }
1523 *p = '\0';
1524
1525 return string_nocheck(buf, end, ip6_addr, spec);
1526 }
1527
1528 static noinline_for_stack
ip4_addr_string_sa(char * buf,char * end,const struct sockaddr_in * sa,struct printf_spec spec,const char * fmt)1529 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1530 struct printf_spec spec, const char *fmt)
1531 {
1532 bool have_p = false;
1533 char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1534 char *pend = ip4_addr + sizeof(ip4_addr);
1535 const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1536 char fmt4[3] = { fmt[0], '4', 0 };
1537
1538 fmt++;
1539 while (isalpha(*++fmt)) {
1540 switch (*fmt) {
1541 case 'p':
1542 have_p = true;
1543 break;
1544 case 'h':
1545 case 'l':
1546 case 'n':
1547 case 'b':
1548 fmt4[2] = *fmt;
1549 break;
1550 }
1551 }
1552
1553 p = ip4_string(ip4_addr, addr, fmt4);
1554 if (have_p) {
1555 *p++ = ':';
1556 p = number(p, pend, ntohs(sa->sin_port), spec);
1557 }
1558 *p = '\0';
1559
1560 return string_nocheck(buf, end, ip4_addr, spec);
1561 }
1562
1563 static noinline_for_stack
ip_addr_string(char * buf,char * end,const void * ptr,struct printf_spec spec,const char * fmt)1564 char *ip_addr_string(char *buf, char *end, const void *ptr,
1565 struct printf_spec spec, const char *fmt)
1566 {
1567 char *err_fmt_msg;
1568
1569 if (check_pointer(&buf, end, ptr, spec))
1570 return buf;
1571
1572 switch (fmt[1]) {
1573 case '6':
1574 return ip6_addr_string(buf, end, ptr, spec, fmt);
1575 case '4':
1576 return ip4_addr_string(buf, end, ptr, spec, fmt);
1577 case 'S': {
1578 const union {
1579 struct sockaddr raw;
1580 struct sockaddr_in v4;
1581 struct sockaddr_in6 v6;
1582 } *sa = ptr;
1583
1584 switch (sa->raw.sa_family) {
1585 case AF_INET:
1586 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1587 case AF_INET6:
1588 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1589 default:
1590 return error_string(buf, end, "(einval)", spec);
1591 }}
1592 }
1593
1594 err_fmt_msg = fmt[0] == 'i' ? "(%pi?)" : "(%pI?)";
1595 return error_string(buf, end, err_fmt_msg, spec);
1596 }
1597
1598 static noinline_for_stack
escaped_string(char * buf,char * end,u8 * addr,struct printf_spec spec,const char * fmt)1599 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1600 const char *fmt)
1601 {
1602 bool found = true;
1603 int count = 1;
1604 unsigned int flags = 0;
1605 int len;
1606
1607 if (spec.field_width == 0)
1608 return buf; /* nothing to print */
1609
1610 if (check_pointer(&buf, end, addr, spec))
1611 return buf;
1612
1613 do {
1614 switch (fmt[count++]) {
1615 case 'a':
1616 flags |= ESCAPE_ANY;
1617 break;
1618 case 'c':
1619 flags |= ESCAPE_SPECIAL;
1620 break;
1621 case 'h':
1622 flags |= ESCAPE_HEX;
1623 break;
1624 case 'n':
1625 flags |= ESCAPE_NULL;
1626 break;
1627 case 'o':
1628 flags |= ESCAPE_OCTAL;
1629 break;
1630 case 'p':
1631 flags |= ESCAPE_NP;
1632 break;
1633 case 's':
1634 flags |= ESCAPE_SPACE;
1635 break;
1636 default:
1637 found = false;
1638 break;
1639 }
1640 } while (found);
1641
1642 if (!flags)
1643 flags = ESCAPE_ANY_NP;
1644
1645 len = spec.field_width < 0 ? 1 : spec.field_width;
1646
1647 /*
1648 * string_escape_mem() writes as many characters as it can to
1649 * the given buffer, and returns the total size of the output
1650 * had the buffer been big enough.
1651 */
1652 buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1653
1654 return buf;
1655 }
1656
va_format(char * buf,char * end,struct va_format * va_fmt,struct printf_spec spec,const char * fmt)1657 static char *va_format(char *buf, char *end, struct va_format *va_fmt,
1658 struct printf_spec spec, const char *fmt)
1659 {
1660 va_list va;
1661
1662 if (check_pointer(&buf, end, va_fmt, spec))
1663 return buf;
1664
1665 va_copy(va, *va_fmt->va);
1666 buf += vsnprintf(buf, end > buf ? end - buf : 0, va_fmt->fmt, va);
1667 va_end(va);
1668
1669 return buf;
1670 }
1671
1672 static noinline_for_stack
uuid_string(char * buf,char * end,const u8 * addr,struct printf_spec spec,const char * fmt)1673 char *uuid_string(char *buf, char *end, const u8 *addr,
1674 struct printf_spec spec, const char *fmt)
1675 {
1676 char uuid[UUID_STRING_LEN + 1];
1677 char *p = uuid;
1678 int i;
1679 const u8 *index = uuid_index;
1680 bool uc = false;
1681
1682 if (check_pointer(&buf, end, addr, spec))
1683 return buf;
1684
1685 switch (*(++fmt)) {
1686 case 'L':
1687 uc = true; /* fall-through */
1688 case 'l':
1689 index = guid_index;
1690 break;
1691 case 'B':
1692 uc = true;
1693 break;
1694 }
1695
1696 for (i = 0; i < 16; i++) {
1697 if (uc)
1698 p = hex_byte_pack_upper(p, addr[index[i]]);
1699 else
1700 p = hex_byte_pack(p, addr[index[i]]);
1701 switch (i) {
1702 case 3:
1703 case 5:
1704 case 7:
1705 case 9:
1706 *p++ = '-';
1707 break;
1708 }
1709 }
1710
1711 *p = 0;
1712
1713 return string_nocheck(buf, end, uuid, spec);
1714 }
1715
1716 static noinline_for_stack
netdev_bits(char * buf,char * end,const void * addr,struct printf_spec spec,const char * fmt)1717 char *netdev_bits(char *buf, char *end, const void *addr,
1718 struct printf_spec spec, const char *fmt)
1719 {
1720 unsigned long long num;
1721 int size;
1722
1723 if (check_pointer(&buf, end, addr, spec))
1724 return buf;
1725
1726 switch (fmt[1]) {
1727 case 'F':
1728 num = *(const netdev_features_t *)addr;
1729 size = sizeof(netdev_features_t);
1730 break;
1731 default:
1732 return error_string(buf, end, "(%pN?)", spec);
1733 }
1734
1735 return special_hex_number(buf, end, num, size);
1736 }
1737
1738 static noinline_for_stack
address_val(char * buf,char * end,const void * addr,struct printf_spec spec,const char * fmt)1739 char *address_val(char *buf, char *end, const void *addr,
1740 struct printf_spec spec, const char *fmt)
1741 {
1742 unsigned long long num;
1743 int size;
1744
1745 if (check_pointer(&buf, end, addr, spec))
1746 return buf;
1747
1748 switch (fmt[1]) {
1749 case 'd':
1750 num = *(const dma_addr_t *)addr;
1751 size = sizeof(dma_addr_t);
1752 break;
1753 case 'p':
1754 default:
1755 num = *(const phys_addr_t *)addr;
1756 size = sizeof(phys_addr_t);
1757 break;
1758 }
1759
1760 return special_hex_number(buf, end, num, size);
1761 }
1762
1763 static noinline_for_stack
date_str(char * buf,char * end,const struct rtc_time * tm,bool r)1764 char *date_str(char *buf, char *end, const struct rtc_time *tm, bool r)
1765 {
1766 int year = tm->tm_year + (r ? 0 : 1900);
1767 int mon = tm->tm_mon + (r ? 0 : 1);
1768
1769 buf = number(buf, end, year, default_dec04_spec);
1770 if (buf < end)
1771 *buf = '-';
1772 buf++;
1773
1774 buf = number(buf, end, mon, default_dec02_spec);
1775 if (buf < end)
1776 *buf = '-';
1777 buf++;
1778
1779 return number(buf, end, tm->tm_mday, default_dec02_spec);
1780 }
1781
1782 static noinline_for_stack
time_str(char * buf,char * end,const struct rtc_time * tm,bool r)1783 char *time_str(char *buf, char *end, const struct rtc_time *tm, bool r)
1784 {
1785 buf = number(buf, end, tm->tm_hour, default_dec02_spec);
1786 if (buf < end)
1787 *buf = ':';
1788 buf++;
1789
1790 buf = number(buf, end, tm->tm_min, default_dec02_spec);
1791 if (buf < end)
1792 *buf = ':';
1793 buf++;
1794
1795 return number(buf, end, tm->tm_sec, default_dec02_spec);
1796 }
1797
1798 static noinline_for_stack
rtc_str(char * buf,char * end,const struct rtc_time * tm,struct printf_spec spec,const char * fmt)1799 char *rtc_str(char *buf, char *end, const struct rtc_time *tm,
1800 struct printf_spec spec, const char *fmt)
1801 {
1802 bool have_t = true, have_d = true;
1803 bool raw = false;
1804 int count = 2;
1805
1806 if (check_pointer(&buf, end, tm, spec))
1807 return buf;
1808
1809 switch (fmt[count]) {
1810 case 'd':
1811 have_t = false;
1812 count++;
1813 break;
1814 case 't':
1815 have_d = false;
1816 count++;
1817 break;
1818 }
1819
1820 raw = fmt[count] == 'r';
1821
1822 if (have_d)
1823 buf = date_str(buf, end, tm, raw);
1824 if (have_d && have_t) {
1825 /* Respect ISO 8601 */
1826 if (buf < end)
1827 *buf = 'T';
1828 buf++;
1829 }
1830 if (have_t)
1831 buf = time_str(buf, end, tm, raw);
1832
1833 return buf;
1834 }
1835
1836 static noinline_for_stack
time_and_date(char * buf,char * end,void * ptr,struct printf_spec spec,const char * fmt)1837 char *time_and_date(char *buf, char *end, void *ptr, struct printf_spec spec,
1838 const char *fmt)
1839 {
1840 switch (fmt[1]) {
1841 case 'R':
1842 return rtc_str(buf, end, (const struct rtc_time *)ptr, spec, fmt);
1843 default:
1844 return error_string(buf, end, "(%ptR?)", spec);
1845 }
1846 }
1847
1848 static noinline_for_stack
clock(char * buf,char * end,struct clk * clk,struct printf_spec spec,const char * fmt)1849 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1850 const char *fmt)
1851 {
1852 if (!IS_ENABLED(CONFIG_HAVE_CLK))
1853 return error_string(buf, end, "(%pC?)", spec);
1854
1855 if (check_pointer(&buf, end, clk, spec))
1856 return buf;
1857
1858 switch (fmt[1]) {
1859 case 'n':
1860 default:
1861 #ifdef CONFIG_COMMON_CLK
1862 return string(buf, end, __clk_get_name(clk), spec);
1863 #else
1864 return ptr_to_id(buf, end, clk, spec);
1865 #endif
1866 }
1867 }
1868
1869 static
format_flags(char * buf,char * end,unsigned long flags,const struct trace_print_flags * names)1870 char *format_flags(char *buf, char *end, unsigned long flags,
1871 const struct trace_print_flags *names)
1872 {
1873 unsigned long mask;
1874
1875 for ( ; flags && names->name; names++) {
1876 mask = names->mask;
1877 if ((flags & mask) != mask)
1878 continue;
1879
1880 buf = string(buf, end, names->name, default_str_spec);
1881
1882 flags &= ~mask;
1883 if (flags) {
1884 if (buf < end)
1885 *buf = '|';
1886 buf++;
1887 }
1888 }
1889
1890 if (flags)
1891 buf = number(buf, end, flags, default_flag_spec);
1892
1893 return buf;
1894 }
1895
1896 static noinline_for_stack
flags_string(char * buf,char * end,void * flags_ptr,struct printf_spec spec,const char * fmt)1897 char *flags_string(char *buf, char *end, void *flags_ptr,
1898 struct printf_spec spec, const char *fmt)
1899 {
1900 unsigned long flags;
1901 const struct trace_print_flags *names;
1902
1903 if (check_pointer(&buf, end, flags_ptr, spec))
1904 return buf;
1905
1906 switch (fmt[1]) {
1907 case 'p':
1908 flags = *(unsigned long *)flags_ptr;
1909 /* Remove zone id */
1910 flags &= (1UL << NR_PAGEFLAGS) - 1;
1911 names = pageflag_names;
1912 break;
1913 case 'v':
1914 flags = *(unsigned long *)flags_ptr;
1915 names = vmaflag_names;
1916 break;
1917 case 'g':
1918 flags = *(gfp_t *)flags_ptr;
1919 names = gfpflag_names;
1920 break;
1921 default:
1922 return error_string(buf, end, "(%pG?)", spec);
1923 }
1924
1925 return format_flags(buf, end, flags, names);
1926 }
1927
device_node_name_for_depth(const struct device_node * np,int depth)1928 static const char *device_node_name_for_depth(const struct device_node *np, int depth)
1929 {
1930 for ( ; np && depth; depth--)
1931 np = np->parent;
1932
1933 return kbasename(np->full_name);
1934 }
1935
1936 static noinline_for_stack
device_node_gen_full_name(const struct device_node * np,char * buf,char * end)1937 char *device_node_gen_full_name(const struct device_node *np, char *buf, char *end)
1938 {
1939 int depth;
1940 const struct device_node *parent = np->parent;
1941
1942 /* special case for root node */
1943 if (!parent)
1944 return string_nocheck(buf, end, "/", default_str_spec);
1945
1946 for (depth = 0; parent->parent; depth++)
1947 parent = parent->parent;
1948
1949 for ( ; depth >= 0; depth--) {
1950 buf = string_nocheck(buf, end, "/", default_str_spec);
1951 buf = string(buf, end, device_node_name_for_depth(np, depth),
1952 default_str_spec);
1953 }
1954 return buf;
1955 }
1956
1957 static noinline_for_stack
device_node_string(char * buf,char * end,struct device_node * dn,struct printf_spec spec,const char * fmt)1958 char *device_node_string(char *buf, char *end, struct device_node *dn,
1959 struct printf_spec spec, const char *fmt)
1960 {
1961 char tbuf[sizeof("xxxx") + 1];
1962 const char *p;
1963 int ret;
1964 char *buf_start = buf;
1965 struct property *prop;
1966 bool has_mult, pass;
1967 static const struct printf_spec num_spec = {
1968 .flags = SMALL,
1969 .field_width = -1,
1970 .precision = -1,
1971 .base = 10,
1972 };
1973
1974 struct printf_spec str_spec = spec;
1975 str_spec.field_width = -1;
1976
1977 if (!IS_ENABLED(CONFIG_OF))
1978 return error_string(buf, end, "(%pOF?)", spec);
1979
1980 if (check_pointer(&buf, end, dn, spec))
1981 return buf;
1982
1983 /* simple case without anything any more format specifiers */
1984 fmt++;
1985 if (fmt[0] == '\0' || strcspn(fmt,"fnpPFcC") > 0)
1986 fmt = "f";
1987
1988 for (pass = false; strspn(fmt,"fnpPFcC"); fmt++, pass = true) {
1989 int precision;
1990 if (pass) {
1991 if (buf < end)
1992 *buf = ':';
1993 buf++;
1994 }
1995
1996 switch (*fmt) {
1997 case 'f': /* full_name */
1998 buf = device_node_gen_full_name(dn, buf, end);
1999 break;
2000 case 'n': /* name */
2001 p = kbasename(of_node_full_name(dn));
2002 precision = str_spec.precision;
2003 str_spec.precision = strchrnul(p, '@') - p;
2004 buf = string(buf, end, p, str_spec);
2005 str_spec.precision = precision;
2006 break;
2007 case 'p': /* phandle */
2008 buf = number(buf, end, (unsigned int)dn->phandle, num_spec);
2009 break;
2010 case 'P': /* path-spec */
2011 p = kbasename(of_node_full_name(dn));
2012 if (!p[1])
2013 p = "/";
2014 buf = string(buf, end, p, str_spec);
2015 break;
2016 case 'F': /* flags */
2017 tbuf[0] = of_node_check_flag(dn, OF_DYNAMIC) ? 'D' : '-';
2018 tbuf[1] = of_node_check_flag(dn, OF_DETACHED) ? 'd' : '-';
2019 tbuf[2] = of_node_check_flag(dn, OF_POPULATED) ? 'P' : '-';
2020 tbuf[3] = of_node_check_flag(dn, OF_POPULATED_BUS) ? 'B' : '-';
2021 tbuf[4] = 0;
2022 buf = string_nocheck(buf, end, tbuf, str_spec);
2023 break;
2024 case 'c': /* major compatible string */
2025 ret = of_property_read_string(dn, "compatible", &p);
2026 if (!ret)
2027 buf = string(buf, end, p, str_spec);
2028 break;
2029 case 'C': /* full compatible string */
2030 has_mult = false;
2031 of_property_for_each_string(dn, "compatible", prop, p) {
2032 if (has_mult)
2033 buf = string_nocheck(buf, end, ",", str_spec);
2034 buf = string_nocheck(buf, end, "\"", str_spec);
2035 buf = string(buf, end, p, str_spec);
2036 buf = string_nocheck(buf, end, "\"", str_spec);
2037
2038 has_mult = true;
2039 }
2040 break;
2041 default:
2042 break;
2043 }
2044 }
2045
2046 return widen_string(buf, buf - buf_start, end, spec);
2047 }
2048
kobject_string(char * buf,char * end,void * ptr,struct printf_spec spec,const char * fmt)2049 static char *kobject_string(char *buf, char *end, void *ptr,
2050 struct printf_spec spec, const char *fmt)
2051 {
2052 switch (fmt[1]) {
2053 case 'F':
2054 return device_node_string(buf, end, ptr, spec, fmt + 1);
2055 }
2056
2057 return error_string(buf, end, "(%pO?)", spec);
2058 }
2059
2060 /*
2061 * Show a '%p' thing. A kernel extension is that the '%p' is followed
2062 * by an extra set of alphanumeric characters that are extended format
2063 * specifiers.
2064 *
2065 * Please update scripts/checkpatch.pl when adding/removing conversion
2066 * characters. (Search for "check for vsprintf extension").
2067 *
2068 * Right now we handle:
2069 *
2070 * - 'S' For symbolic direct pointers (or function descriptors) with offset
2071 * - 's' For symbolic direct pointers (or function descriptors) without offset
2072 * - 'F' Same as 'S'
2073 * - 'f' Same as 's'
2074 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
2075 * - 'B' For backtraced symbolic direct pointers with offset
2076 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
2077 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
2078 * - 'b[l]' For a bitmap, the number of bits is determined by the field
2079 * width which must be explicitly specified either as part of the
2080 * format string '%32b[l]' or through '%*b[l]', [l] selects
2081 * range-list format instead of hex format
2082 * - 'M' For a 6-byte MAC address, it prints the address in the
2083 * usual colon-separated hex notation
2084 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
2085 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
2086 * with a dash-separated hex notation
2087 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
2088 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
2089 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
2090 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
2091 * [S][pfs]
2092 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
2093 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
2094 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
2095 * IPv6 omits the colons (01020304...0f)
2096 * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
2097 * [S][pfs]
2098 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
2099 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
2100 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
2101 * - 'I[6S]c' for IPv6 addresses printed as specified by
2102 * http://tools.ietf.org/html/rfc5952
2103 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
2104 * of the following flags (see string_escape_mem() for the
2105 * details):
2106 * a - ESCAPE_ANY
2107 * c - ESCAPE_SPECIAL
2108 * h - ESCAPE_HEX
2109 * n - ESCAPE_NULL
2110 * o - ESCAPE_OCTAL
2111 * p - ESCAPE_NP
2112 * s - ESCAPE_SPACE
2113 * By default ESCAPE_ANY_NP is used.
2114 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
2115 * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
2116 * Options for %pU are:
2117 * b big endian lower case hex (default)
2118 * B big endian UPPER case hex
2119 * l little endian lower case hex
2120 * L little endian UPPER case hex
2121 * big endian output byte order is:
2122 * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
2123 * little endian output byte order is:
2124 * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
2125 * - 'V' For a struct va_format which contains a format string * and va_list *,
2126 * call vsnprintf(->format, *->va_list).
2127 * Implements a "recursive vsnprintf".
2128 * Do not use this feature without some mechanism to verify the
2129 * correctness of the format string and va_list arguments.
2130 * - 'K' For a kernel pointer that should be hidden from unprivileged users
2131 * - 'NF' For a netdev_features_t
2132 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
2133 * a certain separator (' ' by default):
2134 * C colon
2135 * D dash
2136 * N no separator
2137 * The maximum supported length is 64 bytes of the input. Consider
2138 * to use print_hex_dump() for the larger input.
2139 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
2140 * (default assumed to be phys_addr_t, passed by reference)
2141 * - 'd[234]' For a dentry name (optionally 2-4 last components)
2142 * - 'D[234]' Same as 'd' but for a struct file
2143 * - 'g' For block_device name (gendisk + partition number)
2144 * - 't[R][dt][r]' For time and date as represented:
2145 * R struct rtc_time
2146 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
2147 * (legacy clock framework) of the clock
2148 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
2149 * (legacy clock framework) of the clock
2150 * - 'G' For flags to be printed as a collection of symbolic strings that would
2151 * construct the specific value. Supported flags given by option:
2152 * p page flags (see struct page) given as pointer to unsigned long
2153 * g gfp flags (GFP_* and __GFP_*) given as pointer to gfp_t
2154 * v vma flags (VM_*) given as pointer to unsigned long
2155 * - 'OF[fnpPcCF]' For a device tree object
2156 * Without any optional arguments prints the full_name
2157 * f device node full_name
2158 * n device node name
2159 * p device node phandle
2160 * P device node path spec (name + @unit)
2161 * F device node flags
2162 * c major compatible string
2163 * C full compatible string
2164 * - 'x' For printing the address. Equivalent to "%lx".
2165 *
2166 * ** When making changes please also update:
2167 * Documentation/core-api/printk-formats.rst
2168 *
2169 * Note: The default behaviour (unadorned %p) is to hash the address,
2170 * rendering it useful as a unique identifier.
2171 */
2172 static noinline_for_stack
pointer(const char * fmt,char * buf,char * end,void * ptr,struct printf_spec spec)2173 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
2174 struct printf_spec spec)
2175 {
2176 switch (*fmt) {
2177 case 'F':
2178 case 'f':
2179 case 'S':
2180 case 's':
2181 ptr = dereference_symbol_descriptor(ptr);
2182 /* Fallthrough */
2183 case 'B':
2184 return symbol_string(buf, end, ptr, spec, fmt);
2185 case 'R':
2186 case 'r':
2187 return resource_string(buf, end, ptr, spec, fmt);
2188 case 'h':
2189 return hex_string(buf, end, ptr, spec, fmt);
2190 case 'b':
2191 switch (fmt[1]) {
2192 case 'l':
2193 return bitmap_list_string(buf, end, ptr, spec, fmt);
2194 default:
2195 return bitmap_string(buf, end, ptr, spec, fmt);
2196 }
2197 case 'M': /* Colon separated: 00:01:02:03:04:05 */
2198 case 'm': /* Contiguous: 000102030405 */
2199 /* [mM]F (FDDI) */
2200 /* [mM]R (Reverse order; Bluetooth) */
2201 return mac_address_string(buf, end, ptr, spec, fmt);
2202 case 'I': /* Formatted IP supported
2203 * 4: 1.2.3.4
2204 * 6: 0001:0203:...:0708
2205 * 6c: 1::708 or 1::1.2.3.4
2206 */
2207 case 'i': /* Contiguous:
2208 * 4: 001.002.003.004
2209 * 6: 000102...0f
2210 */
2211 return ip_addr_string(buf, end, ptr, spec, fmt);
2212 case 'E':
2213 return escaped_string(buf, end, ptr, spec, fmt);
2214 case 'U':
2215 return uuid_string(buf, end, ptr, spec, fmt);
2216 case 'V':
2217 return va_format(buf, end, ptr, spec, fmt);
2218 case 'K':
2219 return restricted_pointer(buf, end, ptr, spec);
2220 case 'N':
2221 return netdev_bits(buf, end, ptr, spec, fmt);
2222 case 'a':
2223 return address_val(buf, end, ptr, spec, fmt);
2224 case 'd':
2225 return dentry_name(buf, end, ptr, spec, fmt);
2226 case 't':
2227 return time_and_date(buf, end, ptr, spec, fmt);
2228 case 'C':
2229 return clock(buf, end, ptr, spec, fmt);
2230 case 'D':
2231 return file_dentry_name(buf, end, ptr, spec, fmt);
2232 #ifdef CONFIG_BLOCK
2233 case 'g':
2234 return bdev_name(buf, end, ptr, spec, fmt);
2235 #endif
2236
2237 case 'G':
2238 return flags_string(buf, end, ptr, spec, fmt);
2239 case 'O':
2240 return kobject_string(buf, end, ptr, spec, fmt);
2241 case 'x':
2242 return pointer_string(buf, end, ptr, spec);
2243 }
2244
2245 /* default is to _not_ leak addresses, hash before printing */
2246 return ptr_to_id(buf, end, ptr, spec);
2247 }
2248
2249 /*
2250 * Helper function to decode printf style format.
2251 * Each call decode a token from the format and return the
2252 * number of characters read (or likely the delta where it wants
2253 * to go on the next call).
2254 * The decoded token is returned through the parameters
2255 *
2256 * 'h', 'l', or 'L' for integer fields
2257 * 'z' support added 23/7/1999 S.H.
2258 * 'z' changed to 'Z' --davidm 1/25/99
2259 * 'Z' changed to 'z' --adobriyan 2017-01-25
2260 * 't' added for ptrdiff_t
2261 *
2262 * @fmt: the format string
2263 * @type of the token returned
2264 * @flags: various flags such as +, -, # tokens..
2265 * @field_width: overwritten width
2266 * @base: base of the number (octal, hex, ...)
2267 * @precision: precision of a number
2268 * @qualifier: qualifier of a number (long, size_t, ...)
2269 */
2270 static noinline_for_stack
format_decode(const char * fmt,struct printf_spec * spec)2271 int format_decode(const char *fmt, struct printf_spec *spec)
2272 {
2273 const char *start = fmt;
2274 char qualifier;
2275
2276 /* we finished early by reading the field width */
2277 if (spec->type == FORMAT_TYPE_WIDTH) {
2278 if (spec->field_width < 0) {
2279 spec->field_width = -spec->field_width;
2280 spec->flags |= LEFT;
2281 }
2282 spec->type = FORMAT_TYPE_NONE;
2283 goto precision;
2284 }
2285
2286 /* we finished early by reading the precision */
2287 if (spec->type == FORMAT_TYPE_PRECISION) {
2288 if (spec->precision < 0)
2289 spec->precision = 0;
2290
2291 spec->type = FORMAT_TYPE_NONE;
2292 goto qualifier;
2293 }
2294
2295 /* By default */
2296 spec->type = FORMAT_TYPE_NONE;
2297
2298 for (; *fmt ; ++fmt) {
2299 if (*fmt == '%')
2300 break;
2301 }
2302
2303 /* Return the current non-format string */
2304 if (fmt != start || !*fmt)
2305 return fmt - start;
2306
2307 /* Process flags */
2308 spec->flags = 0;
2309
2310 while (1) { /* this also skips first '%' */
2311 bool found = true;
2312
2313 ++fmt;
2314
2315 switch (*fmt) {
2316 case '-': spec->flags |= LEFT; break;
2317 case '+': spec->flags |= PLUS; break;
2318 case ' ': spec->flags |= SPACE; break;
2319 case '#': spec->flags |= SPECIAL; break;
2320 case '0': spec->flags |= ZEROPAD; break;
2321 default: found = false;
2322 }
2323
2324 if (!found)
2325 break;
2326 }
2327
2328 /* get field width */
2329 spec->field_width = -1;
2330
2331 if (isdigit(*fmt))
2332 spec->field_width = skip_atoi(&fmt);
2333 else if (*fmt == '*') {
2334 /* it's the next argument */
2335 spec->type = FORMAT_TYPE_WIDTH;
2336 return ++fmt - start;
2337 }
2338
2339 precision:
2340 /* get the precision */
2341 spec->precision = -1;
2342 if (*fmt == '.') {
2343 ++fmt;
2344 if (isdigit(*fmt)) {
2345 spec->precision = skip_atoi(&fmt);
2346 if (spec->precision < 0)
2347 spec->precision = 0;
2348 } else if (*fmt == '*') {
2349 /* it's the next argument */
2350 spec->type = FORMAT_TYPE_PRECISION;
2351 return ++fmt - start;
2352 }
2353 }
2354
2355 qualifier:
2356 /* get the conversion qualifier */
2357 qualifier = 0;
2358 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2359 *fmt == 'z' || *fmt == 't') {
2360 qualifier = *fmt++;
2361 if (unlikely(qualifier == *fmt)) {
2362 if (qualifier == 'l') {
2363 qualifier = 'L';
2364 ++fmt;
2365 } else if (qualifier == 'h') {
2366 qualifier = 'H';
2367 ++fmt;
2368 }
2369 }
2370 }
2371
2372 /* default base */
2373 spec->base = 10;
2374 switch (*fmt) {
2375 case 'c':
2376 spec->type = FORMAT_TYPE_CHAR;
2377 return ++fmt - start;
2378
2379 case 's':
2380 spec->type = FORMAT_TYPE_STR;
2381 return ++fmt - start;
2382
2383 case 'p':
2384 spec->type = FORMAT_TYPE_PTR;
2385 return ++fmt - start;
2386
2387 case '%':
2388 spec->type = FORMAT_TYPE_PERCENT_CHAR;
2389 return ++fmt - start;
2390
2391 /* integer number formats - set up the flags and "break" */
2392 case 'o':
2393 spec->base = 8;
2394 break;
2395
2396 case 'x':
2397 spec->flags |= SMALL;
2398 /* fall through */
2399
2400 case 'X':
2401 spec->base = 16;
2402 break;
2403
2404 case 'd':
2405 case 'i':
2406 spec->flags |= SIGN;
2407 case 'u':
2408 break;
2409
2410 case 'n':
2411 /*
2412 * Since %n poses a greater security risk than
2413 * utility, treat it as any other invalid or
2414 * unsupported format specifier.
2415 */
2416 /* Fall-through */
2417
2418 default:
2419 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
2420 spec->type = FORMAT_TYPE_INVALID;
2421 return fmt - start;
2422 }
2423
2424 if (qualifier == 'L')
2425 spec->type = FORMAT_TYPE_LONG_LONG;
2426 else if (qualifier == 'l') {
2427 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
2428 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
2429 } else if (qualifier == 'z') {
2430 spec->type = FORMAT_TYPE_SIZE_T;
2431 } else if (qualifier == 't') {
2432 spec->type = FORMAT_TYPE_PTRDIFF;
2433 } else if (qualifier == 'H') {
2434 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
2435 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
2436 } else if (qualifier == 'h') {
2437 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
2438 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
2439 } else {
2440 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
2441 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
2442 }
2443
2444 return ++fmt - start;
2445 }
2446
2447 static void
set_field_width(struct printf_spec * spec,int width)2448 set_field_width(struct printf_spec *spec, int width)
2449 {
2450 spec->field_width = width;
2451 if (WARN_ONCE(spec->field_width != width, "field width %d too large", width)) {
2452 spec->field_width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
2453 }
2454 }
2455
2456 static void
set_precision(struct printf_spec * spec,int prec)2457 set_precision(struct printf_spec *spec, int prec)
2458 {
2459 spec->precision = prec;
2460 if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
2461 spec->precision = clamp(prec, 0, PRECISION_MAX);
2462 }
2463 }
2464
2465 /**
2466 * vsnprintf - Format a string and place it in a buffer
2467 * @buf: The buffer to place the result into
2468 * @size: The size of the buffer, including the trailing null space
2469 * @fmt: The format string to use
2470 * @args: Arguments for the format string
2471 *
2472 * This function generally follows C99 vsnprintf, but has some
2473 * extensions and a few limitations:
2474 *
2475 * - ``%n`` is unsupported
2476 * - ``%p*`` is handled by pointer()
2477 *
2478 * See pointer() or Documentation/core-api/printk-formats.rst for more
2479 * extensive description.
2480 *
2481 * **Please update the documentation in both places when making changes**
2482 *
2483 * The return value is the number of characters which would
2484 * be generated for the given input, excluding the trailing
2485 * '\0', as per ISO C99. If you want to have the exact
2486 * number of characters written into @buf as return value
2487 * (not including the trailing '\0'), use vscnprintf(). If the
2488 * return is greater than or equal to @size, the resulting
2489 * string is truncated.
2490 *
2491 * If you're not already dealing with a va_list consider using snprintf().
2492 */
vsnprintf(char * buf,size_t size,const char * fmt,va_list args)2493 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
2494 {
2495 unsigned long long num;
2496 char *str, *end;
2497 struct printf_spec spec = {0};
2498
2499 /* Reject out-of-range values early. Large positive sizes are
2500 used for unknown buffer sizes. */
2501 if (WARN_ON_ONCE(size > INT_MAX))
2502 return 0;
2503
2504 str = buf;
2505 end = buf + size;
2506
2507 /* Make sure end is always >= buf */
2508 if (end < buf) {
2509 end = ((void *)-1);
2510 size = end - buf;
2511 }
2512
2513 while (*fmt) {
2514 const char *old_fmt = fmt;
2515 int read = format_decode(fmt, &spec);
2516
2517 fmt += read;
2518
2519 switch (spec.type) {
2520 case FORMAT_TYPE_NONE: {
2521 int copy = read;
2522 if (str < end) {
2523 if (copy > end - str)
2524 copy = end - str;
2525 memcpy(str, old_fmt, copy);
2526 }
2527 str += read;
2528 break;
2529 }
2530
2531 case FORMAT_TYPE_WIDTH:
2532 set_field_width(&spec, va_arg(args, int));
2533 break;
2534
2535 case FORMAT_TYPE_PRECISION:
2536 set_precision(&spec, va_arg(args, int));
2537 break;
2538
2539 case FORMAT_TYPE_CHAR: {
2540 char c;
2541
2542 if (!(spec.flags & LEFT)) {
2543 while (--spec.field_width > 0) {
2544 if (str < end)
2545 *str = ' ';
2546 ++str;
2547
2548 }
2549 }
2550 c = (unsigned char) va_arg(args, int);
2551 if (str < end)
2552 *str = c;
2553 ++str;
2554 while (--spec.field_width > 0) {
2555 if (str < end)
2556 *str = ' ';
2557 ++str;
2558 }
2559 break;
2560 }
2561
2562 case FORMAT_TYPE_STR:
2563 str = string(str, end, va_arg(args, char *), spec);
2564 break;
2565
2566 case FORMAT_TYPE_PTR:
2567 str = pointer(fmt, str, end, va_arg(args, void *),
2568 spec);
2569 while (isalnum(*fmt))
2570 fmt++;
2571 break;
2572
2573 case FORMAT_TYPE_PERCENT_CHAR:
2574 if (str < end)
2575 *str = '%';
2576 ++str;
2577 break;
2578
2579 case FORMAT_TYPE_INVALID:
2580 /*
2581 * Presumably the arguments passed gcc's type
2582 * checking, but there is no safe or sane way
2583 * for us to continue parsing the format and
2584 * fetching from the va_list; the remaining
2585 * specifiers and arguments would be out of
2586 * sync.
2587 */
2588 goto out;
2589
2590 default:
2591 switch (spec.type) {
2592 case FORMAT_TYPE_LONG_LONG:
2593 num = va_arg(args, long long);
2594 break;
2595 case FORMAT_TYPE_ULONG:
2596 num = va_arg(args, unsigned long);
2597 break;
2598 case FORMAT_TYPE_LONG:
2599 num = va_arg(args, long);
2600 break;
2601 case FORMAT_TYPE_SIZE_T:
2602 if (spec.flags & SIGN)
2603 num = va_arg(args, ssize_t);
2604 else
2605 num = va_arg(args, size_t);
2606 break;
2607 case FORMAT_TYPE_PTRDIFF:
2608 num = va_arg(args, ptrdiff_t);
2609 break;
2610 case FORMAT_TYPE_UBYTE:
2611 num = (unsigned char) va_arg(args, int);
2612 break;
2613 case FORMAT_TYPE_BYTE:
2614 num = (signed char) va_arg(args, int);
2615 break;
2616 case FORMAT_TYPE_USHORT:
2617 num = (unsigned short) va_arg(args, int);
2618 break;
2619 case FORMAT_TYPE_SHORT:
2620 num = (short) va_arg(args, int);
2621 break;
2622 case FORMAT_TYPE_INT:
2623 num = (int) va_arg(args, int);
2624 break;
2625 default:
2626 num = va_arg(args, unsigned int);
2627 }
2628
2629 str = number(str, end, num, spec);
2630 }
2631 }
2632
2633 out:
2634 if (size > 0) {
2635 if (str < end)
2636 *str = '\0';
2637 else
2638 end[-1] = '\0';
2639 }
2640
2641 /* the trailing null byte doesn't count towards the total */
2642 return str-buf;
2643
2644 }
2645 EXPORT_SYMBOL(vsnprintf);
2646
2647 /**
2648 * vscnprintf - Format a string and place it in a buffer
2649 * @buf: The buffer to place the result into
2650 * @size: The size of the buffer, including the trailing null space
2651 * @fmt: The format string to use
2652 * @args: Arguments for the format string
2653 *
2654 * The return value is the number of characters which have been written into
2655 * the @buf not including the trailing '\0'. If @size is == 0 the function
2656 * returns 0.
2657 *
2658 * If you're not already dealing with a va_list consider using scnprintf().
2659 *
2660 * See the vsnprintf() documentation for format string extensions over C99.
2661 */
vscnprintf(char * buf,size_t size,const char * fmt,va_list args)2662 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2663 {
2664 int i;
2665
2666 i = vsnprintf(buf, size, fmt, args);
2667
2668 if (likely(i < size))
2669 return i;
2670 if (size != 0)
2671 return size - 1;
2672 return 0;
2673 }
2674 EXPORT_SYMBOL(vscnprintf);
2675
2676 /**
2677 * snprintf - Format a string and place it in a buffer
2678 * @buf: The buffer to place the result into
2679 * @size: The size of the buffer, including the trailing null space
2680 * @fmt: The format string to use
2681 * @...: Arguments for the format string
2682 *
2683 * The return value is the number of characters which would be
2684 * generated for the given input, excluding the trailing null,
2685 * as per ISO C99. If the return is greater than or equal to
2686 * @size, the resulting string is truncated.
2687 *
2688 * See the vsnprintf() documentation for format string extensions over C99.
2689 */
snprintf(char * buf,size_t size,const char * fmt,...)2690 int snprintf(char *buf, size_t size, const char *fmt, ...)
2691 {
2692 va_list args;
2693 int i;
2694
2695 va_start(args, fmt);
2696 i = vsnprintf(buf, size, fmt, args);
2697 va_end(args);
2698
2699 return i;
2700 }
2701 EXPORT_SYMBOL(snprintf);
2702
2703 /**
2704 * scnprintf - Format a string and place it in a buffer
2705 * @buf: The buffer to place the result into
2706 * @size: The size of the buffer, including the trailing null space
2707 * @fmt: The format string to use
2708 * @...: Arguments for the format string
2709 *
2710 * The return value is the number of characters written into @buf not including
2711 * the trailing '\0'. If @size is == 0 the function returns 0.
2712 */
2713
scnprintf(char * buf,size_t size,const char * fmt,...)2714 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2715 {
2716 va_list args;
2717 int i;
2718
2719 va_start(args, fmt);
2720 i = vscnprintf(buf, size, fmt, args);
2721 va_end(args);
2722
2723 return i;
2724 }
2725 EXPORT_SYMBOL(scnprintf);
2726
2727 /**
2728 * vsprintf - Format a string and place it in a buffer
2729 * @buf: The buffer to place the result into
2730 * @fmt: The format string to use
2731 * @args: Arguments for the format string
2732 *
2733 * The function returns the number of characters written
2734 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2735 * buffer overflows.
2736 *
2737 * If you're not already dealing with a va_list consider using sprintf().
2738 *
2739 * See the vsnprintf() documentation for format string extensions over C99.
2740 */
vsprintf(char * buf,const char * fmt,va_list args)2741 int vsprintf(char *buf, const char *fmt, va_list args)
2742 {
2743 return vsnprintf(buf, INT_MAX, fmt, args);
2744 }
2745 EXPORT_SYMBOL(vsprintf);
2746
2747 /**
2748 * sprintf - Format a string and place it in a buffer
2749 * @buf: The buffer to place the result into
2750 * @fmt: The format string to use
2751 * @...: Arguments for the format string
2752 *
2753 * The function returns the number of characters written
2754 * into @buf. Use snprintf() or scnprintf() in order to avoid
2755 * buffer overflows.
2756 *
2757 * See the vsnprintf() documentation for format string extensions over C99.
2758 */
sprintf(char * buf,const char * fmt,...)2759 int sprintf(char *buf, const char *fmt, ...)
2760 {
2761 va_list args;
2762 int i;
2763
2764 va_start(args, fmt);
2765 i = vsnprintf(buf, INT_MAX, fmt, args);
2766 va_end(args);
2767
2768 return i;
2769 }
2770 EXPORT_SYMBOL(sprintf);
2771
2772 #ifdef CONFIG_BINARY_PRINTF
2773 /*
2774 * bprintf service:
2775 * vbin_printf() - VA arguments to binary data
2776 * bstr_printf() - Binary data to text string
2777 */
2778
2779 /**
2780 * vbin_printf - Parse a format string and place args' binary value in a buffer
2781 * @bin_buf: The buffer to place args' binary value
2782 * @size: The size of the buffer(by words(32bits), not characters)
2783 * @fmt: The format string to use
2784 * @args: Arguments for the format string
2785 *
2786 * The format follows C99 vsnprintf, except %n is ignored, and its argument
2787 * is skipped.
2788 *
2789 * The return value is the number of words(32bits) which would be generated for
2790 * the given input.
2791 *
2792 * NOTE:
2793 * If the return value is greater than @size, the resulting bin_buf is NOT
2794 * valid for bstr_printf().
2795 */
vbin_printf(u32 * bin_buf,size_t size,const char * fmt,va_list args)2796 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2797 {
2798 struct printf_spec spec = {0};
2799 char *str, *end;
2800 int width;
2801
2802 str = (char *)bin_buf;
2803 end = (char *)(bin_buf + size);
2804
2805 #define save_arg(type) \
2806 ({ \
2807 unsigned long long value; \
2808 if (sizeof(type) == 8) { \
2809 unsigned long long val8; \
2810 str = PTR_ALIGN(str, sizeof(u32)); \
2811 val8 = va_arg(args, unsigned long long); \
2812 if (str + sizeof(type) <= end) { \
2813 *(u32 *)str = *(u32 *)&val8; \
2814 *(u32 *)(str + 4) = *((u32 *)&val8 + 1); \
2815 } \
2816 value = val8; \
2817 } else { \
2818 unsigned int val4; \
2819 str = PTR_ALIGN(str, sizeof(type)); \
2820 val4 = va_arg(args, int); \
2821 if (str + sizeof(type) <= end) \
2822 *(typeof(type) *)str = (type)(long)val4; \
2823 value = (unsigned long long)val4; \
2824 } \
2825 str += sizeof(type); \
2826 value; \
2827 })
2828
2829 while (*fmt) {
2830 int read = format_decode(fmt, &spec);
2831
2832 fmt += read;
2833
2834 switch (spec.type) {
2835 case FORMAT_TYPE_NONE:
2836 case FORMAT_TYPE_PERCENT_CHAR:
2837 break;
2838 case FORMAT_TYPE_INVALID:
2839 goto out;
2840
2841 case FORMAT_TYPE_WIDTH:
2842 case FORMAT_TYPE_PRECISION:
2843 width = (int)save_arg(int);
2844 /* Pointers may require the width */
2845 if (*fmt == 'p')
2846 set_field_width(&spec, width);
2847 break;
2848
2849 case FORMAT_TYPE_CHAR:
2850 save_arg(char);
2851 break;
2852
2853 case FORMAT_TYPE_STR: {
2854 const char *save_str = va_arg(args, char *);
2855 const char *err_msg;
2856 size_t len;
2857
2858 err_msg = check_pointer_msg(save_str);
2859 if (err_msg)
2860 save_str = err_msg;
2861
2862 len = strlen(save_str) + 1;
2863 if (str + len < end)
2864 memcpy(str, save_str, len);
2865 str += len;
2866 break;
2867 }
2868
2869 case FORMAT_TYPE_PTR:
2870 /* Dereferenced pointers must be done now */
2871 switch (*fmt) {
2872 /* Dereference of functions is still OK */
2873 case 'S':
2874 case 's':
2875 case 'F':
2876 case 'f':
2877 case 'x':
2878 case 'K':
2879 save_arg(void *);
2880 break;
2881 default:
2882 if (!isalnum(*fmt)) {
2883 save_arg(void *);
2884 break;
2885 }
2886 str = pointer(fmt, str, end, va_arg(args, void *),
2887 spec);
2888 if (str + 1 < end)
2889 *str++ = '\0';
2890 else
2891 end[-1] = '\0'; /* Must be nul terminated */
2892 }
2893 /* skip all alphanumeric pointer suffixes */
2894 while (isalnum(*fmt))
2895 fmt++;
2896 break;
2897
2898 default:
2899 switch (spec.type) {
2900
2901 case FORMAT_TYPE_LONG_LONG:
2902 save_arg(long long);
2903 break;
2904 case FORMAT_TYPE_ULONG:
2905 case FORMAT_TYPE_LONG:
2906 save_arg(unsigned long);
2907 break;
2908 case FORMAT_TYPE_SIZE_T:
2909 save_arg(size_t);
2910 break;
2911 case FORMAT_TYPE_PTRDIFF:
2912 save_arg(ptrdiff_t);
2913 break;
2914 case FORMAT_TYPE_UBYTE:
2915 case FORMAT_TYPE_BYTE:
2916 save_arg(char);
2917 break;
2918 case FORMAT_TYPE_USHORT:
2919 case FORMAT_TYPE_SHORT:
2920 save_arg(short);
2921 break;
2922 default:
2923 save_arg(int);
2924 }
2925 }
2926 }
2927
2928 out:
2929 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2930 #undef save_arg
2931 }
2932 EXPORT_SYMBOL_GPL(vbin_printf);
2933
2934 /**
2935 * bstr_printf - Format a string from binary arguments and place it in a buffer
2936 * @buf: The buffer to place the result into
2937 * @size: The size of the buffer, including the trailing null space
2938 * @fmt: The format string to use
2939 * @bin_buf: Binary arguments for the format string
2940 *
2941 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2942 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2943 * a binary buffer that generated by vbin_printf.
2944 *
2945 * The format follows C99 vsnprintf, but has some extensions:
2946 * see vsnprintf comment for details.
2947 *
2948 * The return value is the number of characters which would
2949 * be generated for the given input, excluding the trailing
2950 * '\0', as per ISO C99. If you want to have the exact
2951 * number of characters written into @buf as return value
2952 * (not including the trailing '\0'), use vscnprintf(). If the
2953 * return is greater than or equal to @size, the resulting
2954 * string is truncated.
2955 */
bstr_printf(char * buf,size_t size,const char * fmt,const u32 * bin_buf)2956 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2957 {
2958 struct printf_spec spec = {0};
2959 char *str, *end;
2960 const char *args = (const char *)bin_buf;
2961
2962 if (WARN_ON_ONCE(size > INT_MAX))
2963 return 0;
2964
2965 str = buf;
2966 end = buf + size;
2967
2968 #define get_arg(type) \
2969 ({ \
2970 typeof(type) value; \
2971 if (sizeof(type) == 8) { \
2972 args = PTR_ALIGN(args, sizeof(u32)); \
2973 *(u32 *)&value = *(u32 *)args; \
2974 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
2975 } else { \
2976 args = PTR_ALIGN(args, sizeof(type)); \
2977 value = *(typeof(type) *)args; \
2978 } \
2979 args += sizeof(type); \
2980 value; \
2981 })
2982
2983 /* Make sure end is always >= buf */
2984 if (end < buf) {
2985 end = ((void *)-1);
2986 size = end - buf;
2987 }
2988
2989 while (*fmt) {
2990 const char *old_fmt = fmt;
2991 int read = format_decode(fmt, &spec);
2992
2993 fmt += read;
2994
2995 switch (spec.type) {
2996 case FORMAT_TYPE_NONE: {
2997 int copy = read;
2998 if (str < end) {
2999 if (copy > end - str)
3000 copy = end - str;
3001 memcpy(str, old_fmt, copy);
3002 }
3003 str += read;
3004 break;
3005 }
3006
3007 case FORMAT_TYPE_WIDTH:
3008 set_field_width(&spec, get_arg(int));
3009 break;
3010
3011 case FORMAT_TYPE_PRECISION:
3012 set_precision(&spec, get_arg(int));
3013 break;
3014
3015 case FORMAT_TYPE_CHAR: {
3016 char c;
3017
3018 if (!(spec.flags & LEFT)) {
3019 while (--spec.field_width > 0) {
3020 if (str < end)
3021 *str = ' ';
3022 ++str;
3023 }
3024 }
3025 c = (unsigned char) get_arg(char);
3026 if (str < end)
3027 *str = c;
3028 ++str;
3029 while (--spec.field_width > 0) {
3030 if (str < end)
3031 *str = ' ';
3032 ++str;
3033 }
3034 break;
3035 }
3036
3037 case FORMAT_TYPE_STR: {
3038 const char *str_arg = args;
3039 args += strlen(str_arg) + 1;
3040 str = string(str, end, (char *)str_arg, spec);
3041 break;
3042 }
3043
3044 case FORMAT_TYPE_PTR: {
3045 bool process = false;
3046 int copy, len;
3047 /* Non function dereferences were already done */
3048 switch (*fmt) {
3049 case 'S':
3050 case 's':
3051 case 'F':
3052 case 'f':
3053 case 'x':
3054 case 'K':
3055 process = true;
3056 break;
3057 default:
3058 if (!isalnum(*fmt)) {
3059 process = true;
3060 break;
3061 }
3062 /* Pointer dereference was already processed */
3063 if (str < end) {
3064 len = copy = strlen(args);
3065 if (copy > end - str)
3066 copy = end - str;
3067 memcpy(str, args, copy);
3068 str += len;
3069 args += len + 1;
3070 }
3071 }
3072 if (process)
3073 str = pointer(fmt, str, end, get_arg(void *), spec);
3074
3075 while (isalnum(*fmt))
3076 fmt++;
3077 break;
3078 }
3079
3080 case FORMAT_TYPE_PERCENT_CHAR:
3081 if (str < end)
3082 *str = '%';
3083 ++str;
3084 break;
3085
3086 case FORMAT_TYPE_INVALID:
3087 goto out;
3088
3089 default: {
3090 unsigned long long num;
3091
3092 switch (spec.type) {
3093
3094 case FORMAT_TYPE_LONG_LONG:
3095 num = get_arg(long long);
3096 break;
3097 case FORMAT_TYPE_ULONG:
3098 case FORMAT_TYPE_LONG:
3099 num = get_arg(unsigned long);
3100 break;
3101 case FORMAT_TYPE_SIZE_T:
3102 num = get_arg(size_t);
3103 break;
3104 case FORMAT_TYPE_PTRDIFF:
3105 num = get_arg(ptrdiff_t);
3106 break;
3107 case FORMAT_TYPE_UBYTE:
3108 num = get_arg(unsigned char);
3109 break;
3110 case FORMAT_TYPE_BYTE:
3111 num = get_arg(signed char);
3112 break;
3113 case FORMAT_TYPE_USHORT:
3114 num = get_arg(unsigned short);
3115 break;
3116 case FORMAT_TYPE_SHORT:
3117 num = get_arg(short);
3118 break;
3119 case FORMAT_TYPE_UINT:
3120 num = get_arg(unsigned int);
3121 break;
3122 default:
3123 num = get_arg(int);
3124 }
3125
3126 str = number(str, end, num, spec);
3127 } /* default: */
3128 } /* switch(spec.type) */
3129 } /* while(*fmt) */
3130
3131 out:
3132 if (size > 0) {
3133 if (str < end)
3134 *str = '\0';
3135 else
3136 end[-1] = '\0';
3137 }
3138
3139 #undef get_arg
3140
3141 /* the trailing null byte doesn't count towards the total */
3142 return str - buf;
3143 }
3144 EXPORT_SYMBOL_GPL(bstr_printf);
3145
3146 /**
3147 * bprintf - Parse a format string and place args' binary value in a buffer
3148 * @bin_buf: The buffer to place args' binary value
3149 * @size: The size of the buffer(by words(32bits), not characters)
3150 * @fmt: The format string to use
3151 * @...: Arguments for the format string
3152 *
3153 * The function returns the number of words(u32) written
3154 * into @bin_buf.
3155 */
bprintf(u32 * bin_buf,size_t size,const char * fmt,...)3156 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
3157 {
3158 va_list args;
3159 int ret;
3160
3161 va_start(args, fmt);
3162 ret = vbin_printf(bin_buf, size, fmt, args);
3163 va_end(args);
3164
3165 return ret;
3166 }
3167 EXPORT_SYMBOL_GPL(bprintf);
3168
3169 #endif /* CONFIG_BINARY_PRINTF */
3170
3171 /**
3172 * vsscanf - Unformat a buffer into a list of arguments
3173 * @buf: input buffer
3174 * @fmt: format of buffer
3175 * @args: arguments
3176 */
vsscanf(const char * buf,const char * fmt,va_list args)3177 int vsscanf(const char *buf, const char *fmt, va_list args)
3178 {
3179 const char *str = buf;
3180 char *next;
3181 char digit;
3182 int num = 0;
3183 u8 qualifier;
3184 unsigned int base;
3185 union {
3186 long long s;
3187 unsigned long long u;
3188 } val;
3189 s16 field_width;
3190 bool is_sign;
3191
3192 while (*fmt) {
3193 /* skip any white space in format */
3194 /* white space in format matchs any amount of
3195 * white space, including none, in the input.
3196 */
3197 if (isspace(*fmt)) {
3198 fmt = skip_spaces(++fmt);
3199 str = skip_spaces(str);
3200 }
3201
3202 /* anything that is not a conversion must match exactly */
3203 if (*fmt != '%' && *fmt) {
3204 if (*fmt++ != *str++)
3205 break;
3206 continue;
3207 }
3208
3209 if (!*fmt)
3210 break;
3211 ++fmt;
3212
3213 /* skip this conversion.
3214 * advance both strings to next white space
3215 */
3216 if (*fmt == '*') {
3217 if (!*str)
3218 break;
3219 while (!isspace(*fmt) && *fmt != '%' && *fmt) {
3220 /* '%*[' not yet supported, invalid format */
3221 if (*fmt == '[')
3222 return num;
3223 fmt++;
3224 }
3225 while (!isspace(*str) && *str)
3226 str++;
3227 continue;
3228 }
3229
3230 /* get field width */
3231 field_width = -1;
3232 if (isdigit(*fmt)) {
3233 field_width = skip_atoi(&fmt);
3234 if (field_width <= 0)
3235 break;
3236 }
3237
3238 /* get conversion qualifier */
3239 qualifier = -1;
3240 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
3241 *fmt == 'z') {
3242 qualifier = *fmt++;
3243 if (unlikely(qualifier == *fmt)) {
3244 if (qualifier == 'h') {
3245 qualifier = 'H';
3246 fmt++;
3247 } else if (qualifier == 'l') {
3248 qualifier = 'L';
3249 fmt++;
3250 }
3251 }
3252 }
3253
3254 if (!*fmt)
3255 break;
3256
3257 if (*fmt == 'n') {
3258 /* return number of characters read so far */
3259 *va_arg(args, int *) = str - buf;
3260 ++fmt;
3261 continue;
3262 }
3263
3264 if (!*str)
3265 break;
3266
3267 base = 10;
3268 is_sign = false;
3269
3270 switch (*fmt++) {
3271 case 'c':
3272 {
3273 char *s = (char *)va_arg(args, char*);
3274 if (field_width == -1)
3275 field_width = 1;
3276 do {
3277 *s++ = *str++;
3278 } while (--field_width > 0 && *str);
3279 num++;
3280 }
3281 continue;
3282 case 's':
3283 {
3284 char *s = (char *)va_arg(args, char *);
3285 if (field_width == -1)
3286 field_width = SHRT_MAX;
3287 /* first, skip leading white space in buffer */
3288 str = skip_spaces(str);
3289
3290 /* now copy until next white space */
3291 while (*str && !isspace(*str) && field_width--)
3292 *s++ = *str++;
3293 *s = '\0';
3294 num++;
3295 }
3296 continue;
3297 /*
3298 * Warning: This implementation of the '[' conversion specifier
3299 * deviates from its glibc counterpart in the following ways:
3300 * (1) It does NOT support ranges i.e. '-' is NOT a special
3301 * character
3302 * (2) It cannot match the closing bracket ']' itself
3303 * (3) A field width is required
3304 * (4) '%*[' (discard matching input) is currently not supported
3305 *
3306 * Example usage:
3307 * ret = sscanf("00:0a:95","%2[^:]:%2[^:]:%2[^:]",
3308 * buf1, buf2, buf3);
3309 * if (ret < 3)
3310 * // etc..
3311 */
3312 case '[':
3313 {
3314 char *s = (char *)va_arg(args, char *);
3315 DECLARE_BITMAP(set, 256) = {0};
3316 unsigned int len = 0;
3317 bool negate = (*fmt == '^');
3318
3319 /* field width is required */
3320 if (field_width == -1)
3321 return num;
3322
3323 if (negate)
3324 ++fmt;
3325
3326 for ( ; *fmt && *fmt != ']'; ++fmt, ++len)
3327 set_bit((u8)*fmt, set);
3328
3329 /* no ']' or no character set found */
3330 if (!*fmt || !len)
3331 return num;
3332 ++fmt;
3333
3334 if (negate) {
3335 bitmap_complement(set, set, 256);
3336 /* exclude null '\0' byte */
3337 clear_bit(0, set);
3338 }
3339
3340 /* match must be non-empty */
3341 if (!test_bit((u8)*str, set))
3342 return num;
3343
3344 while (test_bit((u8)*str, set) && field_width--)
3345 *s++ = *str++;
3346 *s = '\0';
3347 ++num;
3348 }
3349 continue;
3350 case 'o':
3351 base = 8;
3352 break;
3353 case 'x':
3354 case 'X':
3355 base = 16;
3356 break;
3357 case 'i':
3358 base = 0;
3359 /* fall through */
3360 case 'd':
3361 is_sign = true;
3362 /* fall through */
3363 case 'u':
3364 break;
3365 case '%':
3366 /* looking for '%' in str */
3367 if (*str++ != '%')
3368 return num;
3369 continue;
3370 default:
3371 /* invalid format; stop here */
3372 return num;
3373 }
3374
3375 /* have some sort of integer conversion.
3376 * first, skip white space in buffer.
3377 */
3378 str = skip_spaces(str);
3379
3380 digit = *str;
3381 if (is_sign && digit == '-')
3382 digit = *(str + 1);
3383
3384 if (!digit
3385 || (base == 16 && !isxdigit(digit))
3386 || (base == 10 && !isdigit(digit))
3387 || (base == 8 && (!isdigit(digit) || digit > '7'))
3388 || (base == 0 && !isdigit(digit)))
3389 break;
3390
3391 if (is_sign)
3392 val.s = simple_strntoll(str,
3393 field_width >= 0 ? field_width : INT_MAX,
3394 &next, base);
3395 else
3396 val.u = simple_strntoull(str,
3397 field_width >= 0 ? field_width : INT_MAX,
3398 &next, base);
3399
3400 switch (qualifier) {
3401 case 'H': /* that's 'hh' in format */
3402 if (is_sign)
3403 *va_arg(args, signed char *) = val.s;
3404 else
3405 *va_arg(args, unsigned char *) = val.u;
3406 break;
3407 case 'h':
3408 if (is_sign)
3409 *va_arg(args, short *) = val.s;
3410 else
3411 *va_arg(args, unsigned short *) = val.u;
3412 break;
3413 case 'l':
3414 if (is_sign)
3415 *va_arg(args, long *) = val.s;
3416 else
3417 *va_arg(args, unsigned long *) = val.u;
3418 break;
3419 case 'L':
3420 if (is_sign)
3421 *va_arg(args, long long *) = val.s;
3422 else
3423 *va_arg(args, unsigned long long *) = val.u;
3424 break;
3425 case 'z':
3426 *va_arg(args, size_t *) = val.u;
3427 break;
3428 default:
3429 if (is_sign)
3430 *va_arg(args, int *) = val.s;
3431 else
3432 *va_arg(args, unsigned int *) = val.u;
3433 break;
3434 }
3435 num++;
3436
3437 if (!next)
3438 break;
3439 str = next;
3440 }
3441
3442 return num;
3443 }
3444 EXPORT_SYMBOL(vsscanf);
3445
3446 /**
3447 * sscanf - Unformat a buffer into a list of arguments
3448 * @buf: input buffer
3449 * @fmt: formatting of buffer
3450 * @...: resulting arguments
3451 */
sscanf(const char * buf,const char * fmt,...)3452 int sscanf(const char *buf, const char *fmt, ...)
3453 {
3454 va_list args;
3455 int i;
3456
3457 va_start(args, fmt);
3458 i = vsscanf(buf, fmt, args);
3459 va_end(args);
3460
3461 return i;
3462 }
3463 EXPORT_SYMBOL(sscanf);
3464