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