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