Subversion Repositories Kolibri OS

Rev

Rev 6082 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1869 serge 1
/*
2
 *  linux/lib/vsprintf.c
3
 *
4
 *  Copyright (C) 1991, 1992  Linus Torvalds
5
 */
6
 
7
/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
8
/*
9
 * Wirzenius wrote this portably, Torvalds fucked it up :-)
10
 */
11
 
12
/*
13
 * Fri Jul 13 2001 Crutcher Dunnavant 
14
 * - changed to provide snprintf and vsnprintf functions
15
 * So Feb  1 16:51:32 CET 2004 Juergen Quade 
16
 * - scnprintf and vscnprintf
17
 */
18
 
19
#include 
5056 serge 20
#include 	/* for KSYM_SYMBOL_LEN */
1869 serge 21
#include 
22
#include 
23
#include 
24
#include 
5270 serge 25
 
6082 serge 26
#include 
1869 serge 27
#include 
3031 serge 28
#include 
1869 serge 29
 
30
#include 
5270 serge 31
#include 		/* for PAGE_SIZE */
1869 serge 32
 
5056 serge 33
#define ZERO_SIZE_PTR ((void *)16)
34
 
35
#define ZERO_OR_NULL_PTR(x) ((unsigned long)(x) <= \
36
                                (unsigned long)ZERO_SIZE_PTR)
37
 
1869 serge 38
#ifndef dereference_function_descriptor
39
#define dereference_function_descriptor(p) (p)
40
#endif
41
 
5056 serge 42
#define KSTRTOX_OVERFLOW        (1U << 31)
43
 
1869 serge 44
 
6293 serge 45
 
1869 serge 46
/* Works only for digits and letters, but small and fast */
47
#define TOLOWER(x) ((x) | 0x20)
48
 
49
 
5056 serge 50
char *skip_spaces(const char *str)
51
{
52
        while (isspace(*str))
53
                ++str;
54
        return (char *)str;
55
}
56
EXPORT_SYMBOL(skip_spaces);
57
 
58
const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
59
{
60
    if (*base == 0) {
61
        if (s[0] == '0') {
62
            if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
63
                *base = 16;
64
            else
65
                *base = 8;
66
        } else
67
            *base = 10;
68
    }
69
    if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
70
        s += 2;
71
    return s;
72
}
73
 
74
/*
75
 * Convert non-negative integer string representation in explicitly given radix
76
 * to an integer.
77
 * Return number of characters consumed maybe or-ed with overflow bit.
78
 * If overflow occurs, result integer (incorrect) is still returned.
79
 *
80
 * Don't you dare use this function.
81
 */
82
unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p)
83
{
84
    unsigned long long res;
85
    unsigned int rv;
86
    int overflow;
87
 
88
    res = 0;
89
    rv = 0;
90
    overflow = 0;
91
    while (*s) {
92
        unsigned int val;
93
 
94
        if ('0' <= *s && *s <= '9')
95
            val = *s - '0';
96
        else if ('a' <= _tolower(*s) && _tolower(*s) <= 'f')
97
            val = _tolower(*s) - 'a' + 10;
98
        else
99
            break;
100
 
101
        if (val >= base)
102
            break;
103
        /*
104
         * Check for overflow only if we are within range of
105
         * it in the max base we support (16)
106
         */
107
        if (unlikely(res & (~0ull << 60))) {
108
            if (res > div_u64(ULLONG_MAX - val, base))
109
                overflow = 1;
110
        }
111
        res = res * base + val;
112
        rv++;
113
        s++;
114
    }
115
    *p = res;
116
    if (overflow)
117
        rv |= KSTRTOX_OVERFLOW;
118
    return rv;
119
}
120
 
121
 
1869 serge 122
/**
123
 * simple_strtoull - convert a string to an unsigned long long
124
 * @cp: The start of the string
125
 * @endp: A pointer to the end of the parsed string will be placed here
126
 * @base: The number base to use
5056 serge 127
 *
128
 * This function is obsolete. Please use kstrtoull instead.
1869 serge 129
 */
130
unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
131
{
5056 serge 132
	unsigned long long result;
133
	unsigned int rv;
1869 serge 134
 
5056 serge 135
	cp = _parse_integer_fixup_radix(cp, &base);
136
	rv = _parse_integer(cp, base, &result);
137
	/* FIXME */
138
	cp += (rv & ~KSTRTOX_OVERFLOW);
1869 serge 139
 
140
	if (endp)
141
		*endp = (char *)cp;
142
 
143
	return result;
144
}
145
EXPORT_SYMBOL(simple_strtoull);
146
 
147
/**
148
 * simple_strtoul - convert a string to an unsigned long
149
 * @cp: The start of the string
150
 * @endp: A pointer to the end of the parsed string will be placed here
151
 * @base: The number base to use
5056 serge 152
 *
153
 * This function is obsolete. Please use kstrtoul instead.
1869 serge 154
 */
155
unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
156
{
157
	return simple_strtoull(cp, endp, base);
158
}
159
EXPORT_SYMBOL(simple_strtoul);
160
 
161
/**
162
 * simple_strtol - convert a string to a signed long
163
 * @cp: The start of the string
164
 * @endp: A pointer to the end of the parsed string will be placed here
165
 * @base: The number base to use
5056 serge 166
 *
167
 * This function is obsolete. Please use kstrtol instead.
1869 serge 168
 */
169
long simple_strtol(const char *cp, char **endp, unsigned int base)
170
{
171
	if (*cp == '-')
172
		return -simple_strtoul(cp + 1, endp, base);
173
 
174
	return simple_strtoul(cp, endp, base);
175
}
176
EXPORT_SYMBOL(simple_strtol);
177
 
178
/**
179
 * simple_strtoll - convert a string to a signed long long
180
 * @cp: The start of the string
181
 * @endp: A pointer to the end of the parsed string will be placed here
182
 * @base: The number base to use
5056 serge 183
 *
184
 * This function is obsolete. Please use kstrtoll instead.
1869 serge 185
 */
186
long long simple_strtoll(const char *cp, char **endp, unsigned int base)
187
{
188
	if (*cp == '-')
189
		return -simple_strtoull(cp + 1, endp, base);
190
 
191
	return simple_strtoull(cp, endp, base);
192
}
193
EXPORT_SYMBOL(simple_strtoll);
194
 
5056 serge 195
static noinline_for_stack
196
int skip_atoi(const char **s)
1869 serge 197
{
5056 serge 198
	int i = 0;
1869 serge 199
 
6082 serge 200
	do {
5056 serge 201
		i = i*10 + *((*s)++) - '0';
6082 serge 202
	} while (isdigit(**s));
1869 serge 203
 
5056 serge 204
	return i;
205
}
1869 serge 206
 
6082 serge 207
/*
208
 * Decimal conversion is by far the most typical, and is used for
209
 * /proc and /sys data. This directly impacts e.g. top performance
210
 * with many processes running. We optimize it for speed by emitting
211
 * two characters at a time, using a 200 byte lookup table. This
212
 * roughly halves the number of multiplications compared to computing
213
 * the digits one at a time. Implementation strongly inspired by the
214
 * previous version, which in turn used ideas described at
215
 *  (with permission
216
 * from the author, Douglas W. Jones).
217
 *
218
 * It turns out there is precisely one 26 bit fixed-point
219
 * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
220
 * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
221
 * range happens to be somewhat larger (x <= 1073741898), but that's
222
 * irrelevant for our purpose.
223
 *
224
 * For dividing a number in the range [10^4, 10^6-1] by 100, we still
225
 * need a 32x32->64 bit multiply, so we simply use the same constant.
226
 *
227
 * For dividing a number in the range [100, 10^4-1] by 100, there are
228
 * several options. The simplest is (x * 0x147b) >> 19, which is valid
229
 * for all x <= 43698.
5056 serge 230
 */
1869 serge 231
 
6082 serge 232
static const u16 decpair[100] = {
233
#define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
234
	_( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
235
	_(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
236
	_(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
237
	_(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
238
	_(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
239
	_(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
240
	_(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
241
	_(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
242
	_(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
243
	_(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
244
#undef _
245
};
246
 
247
/*
248
 * This will print a single '0' even if r == 0, since we would
249
 * immediately jump to out_r where two 0s would be written but only
250
 * one of them accounted for in buf. This is needed by ip4_string
251
 * below. All other callers pass a non-zero value of r.
252
*/
5056 serge 253
static noinline_for_stack
6082 serge 254
char *put_dec_trunc8(char *buf, unsigned r)
5056 serge 255
{
6082 serge 256
	unsigned q;
5056 serge 257
 
6082 serge 258
	/* 1 <= r < 10^8 */
259
	if (r < 100)
260
		goto out_r;
261
 
262
	/* 100 <= r < 10^8 */
263
	q = (r * (u64)0x28f5c29) >> 32;
264
	*((u16 *)buf) = decpair[r - 100*q];
265
	buf += 2;
266
 
267
	/* 1 <= q < 10^6 */
268
	if (q < 100)
269
		goto out_q;
270
 
271
	/*  100 <= q < 10^6 */
272
	r = (q * (u64)0x28f5c29) >> 32;
273
	*((u16 *)buf) = decpair[q - 100*r];
274
	buf += 2;
275
 
276
	/* 1 <= r < 10^4 */
277
	if (r < 100)
278
		goto out_r;
279
 
280
	/* 100 <= r < 10^4 */
281
	q = (r * 0x147b) >> 19;
282
	*((u16 *)buf) = decpair[r - 100*q];
283
	buf += 2;
284
out_q:
285
	/* 1 <= q < 100 */
286
	r = q;
287
out_r:
288
	/* 1 <= r < 100 */
289
	*((u16 *)buf) = decpair[r];
290
	buf += r < 10 ? 1 : 2;
5056 serge 291
	return buf;
1869 serge 292
}
293
 
6082 serge 294
#if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
5056 serge 295
static noinline_for_stack
6082 serge 296
char *put_dec_full8(char *buf, unsigned r)
1869 serge 297
{
5056 serge 298
	unsigned q;
299
 
6082 serge 300
	/* 0 <= r < 10^8 */
301
	q = (r * (u64)0x28f5c29) >> 32;
302
	*((u16 *)buf) = decpair[r - 100*q];
303
	buf += 2;
1869 serge 304
 
6082 serge 305
	/* 0 <= q < 10^6 */
306
	r = (q * (u64)0x28f5c29) >> 32;
307
	*((u16 *)buf) = decpair[q - 100*r];
308
	buf += 2;
309
 
310
	/* 0 <= r < 10^4 */
311
	q = (r * 0x147b) >> 19;
312
	*((u16 *)buf) = decpair[r - 100*q];
313
	buf += 2;
314
 
315
	/* 0 <= q < 100 */
316
	*((u16 *)buf) = decpair[q];
317
	buf += 2;
5056 serge 318
	return buf;
1869 serge 319
}
320
 
6082 serge 321
static noinline_for_stack
5056 serge 322
char *put_dec(char *buf, unsigned long long n)
323
{
324
		if (n >= 100*1000*1000)
6082 serge 325
		buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
326
	/* 1 <= n <= 1.6e11 */
327
	if (n >= 100*1000*1000)
328
		buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
329
	/* 1 <= n < 1e8 */
5056 serge 330
	return put_dec_trunc8(buf, n);
331
}
1869 serge 332
 
6082 serge 333
#elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
5056 serge 334
 
6082 serge 335
static void
336
put_dec_full4(char *buf, unsigned r)
337
{
338
	unsigned q;
5056 serge 339
 
6082 serge 340
	/* 0 <= r < 10^4 */
341
	q = (r * 0x147b) >> 19;
342
	*((u16 *)buf) = decpair[r - 100*q];
343
	buf += 2;
344
	/* 0 <= q < 100 */
345
	*((u16 *)buf) = decpair[q];
1869 serge 346
}
347
 
5056 serge 348
/*
349
 * Call put_dec_full4 on x % 10000, return x / 10000.
350
 * The approximation x/10000 == (x * 0x346DC5D7) >> 43
351
 * holds for all x < 1,128,869,999.  The largest value this
352
 * helper will ever be asked to convert is 1,125,520,955.
6082 serge 353
 * (second call in the put_dec code, assuming n is all-ones).
1869 serge 354
 */
6082 serge 355
static noinline_for_stack
5056 serge 356
unsigned put_dec_helper4(char *buf, unsigned x)
1869 serge 357
{
5056 serge 358
        uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
1869 serge 359
 
5056 serge 360
        put_dec_full4(buf, x - q * 10000);
361
        return q;
1869 serge 362
}
363
 
5056 serge 364
/* Based on code by Douglas W. Jones found at
365
 * 
366
 * (with permission from the author).
367
 * Performs no 64-bit division and hence should be fast on 32-bit machines.
368
 */
369
static
370
char *put_dec(char *buf, unsigned long long n)
1869 serge 371
{
5056 serge 372
	uint32_t d3, d2, d1, q, h;
1869 serge 373
 
5056 serge 374
	if (n < 100*1000*1000)
375
		return put_dec_trunc8(buf, n);
1869 serge 376
 
5056 serge 377
	d1  = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
378
	h   = (n >> 32);
379
	d2  = (h      ) & 0xffff;
380
	d3  = (h >> 16); /* implicit "& 0xffff" */
1869 serge 381
 
6082 serge 382
	/* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
383
	     = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
5056 serge 384
	q   = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
385
	q = put_dec_helper4(buf, q);
1869 serge 386
 
5056 serge 387
	q += 7671 * d3 + 9496 * d2 + 6 * d1;
388
	q = put_dec_helper4(buf+4, q);
1869 serge 389
 
5056 serge 390
	q += 4749 * d3 + 42 * d2;
391
	q = put_dec_helper4(buf+8, q);
1869 serge 392
 
5056 serge 393
	q += 281 * d3;
394
	buf += 12;
395
	if (q)
396
		buf = put_dec_trunc8(buf, q);
397
	else while (buf[-1] == '0')
398
		--buf;
1869 serge 399
 
400
	return buf;
401
}
402
 
5056 serge 403
#endif
1869 serge 404
 
5056 serge 405
/*
406
 * Convert passed number to decimal string.
407
 * Returns the length of string.  On buffer overflow, returns 0.
408
 *
409
 * If speed is not important, use snprintf(). It's easy to read the code.
410
 */
411
int num_to_str(char *buf, int size, unsigned long long num)
412
{
6082 serge 413
	/* put_dec requires 2-byte alignment of the buffer. */
414
	char tmp[sizeof(num) * 3] __aligned(2);
5056 serge 415
	int idx, len;
1869 serge 416
 
5056 serge 417
	/* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
418
	if (num <= 9) {
419
		tmp[0] = '0' + num;
420
		len = 1;
421
	} else {
422
		len = put_dec(tmp, num) - tmp;
423
	}
1869 serge 424
 
5056 serge 425
	if (len > size)
426
		return 0;
427
	for (idx = 0; idx < len; ++idx)
428
		buf[idx] = tmp[len - idx - 1];
429
	return len;
1869 serge 430
}
431
 
6082 serge 432
#define SIGN	1		/* unsigned/signed, must be 1 */
433
#define LEFT	2		/* left justified */
1869 serge 434
#define PLUS	4		/* show plus */
435
#define SPACE	8		/* space if plus */
6082 serge 436
#define ZEROPAD	16		/* pad with zero, must be 16 == '0' - ' ' */
1869 serge 437
#define SMALL	32		/* use lowercase in hex (must be 32 == 0x20) */
438
#define SPECIAL	64		/* prefix hex with "0x", octal with "0" */
439
 
440
enum format_type {
441
	FORMAT_TYPE_NONE, /* Just a string part */
442
	FORMAT_TYPE_WIDTH,
443
	FORMAT_TYPE_PRECISION,
444
	FORMAT_TYPE_CHAR,
445
	FORMAT_TYPE_STR,
446
	FORMAT_TYPE_PTR,
447
	FORMAT_TYPE_PERCENT_CHAR,
448
	FORMAT_TYPE_INVALID,
449
	FORMAT_TYPE_LONG_LONG,
450
	FORMAT_TYPE_ULONG,
451
	FORMAT_TYPE_LONG,
452
	FORMAT_TYPE_UBYTE,
453
	FORMAT_TYPE_BYTE,
454
	FORMAT_TYPE_USHORT,
455
	FORMAT_TYPE_SHORT,
456
	FORMAT_TYPE_UINT,
457
	FORMAT_TYPE_INT,
458
	FORMAT_TYPE_SIZE_T,
459
	FORMAT_TYPE_PTRDIFF
460
};
461
 
462
struct printf_spec {
463
	u8	type;		/* format_type enum */
464
	u8	flags;		/* flags to number() */
465
	u8	base;		/* number base, 8, 10 or 16 only */
466
	u8	qualifier;	/* number qualifier, one of 'hHlLtzZ' */
467
	s16	field_width;	/* width of output field */
468
	s16	precision;	/* # of digits/chars */
469
};
470
 
471
static noinline_for_stack
472
char *number(char *buf, char *end, unsigned long long num,
473
	     struct printf_spec spec)
474
{
6082 serge 475
	/* put_dec requires 2-byte alignment of the buffer. */
476
	char tmp[3 * sizeof(num)] __aligned(2);
1869 serge 477
	char sign;
478
	char locase;
479
	int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
480
	int i;
5056 serge 481
	bool is_zero = num == 0LL;
1869 serge 482
 
483
	/* locase = 0 or 0x20. ORing digits or letters with 'locase'
484
	 * produces same digits or (maybe lowercased) letters */
485
	locase = (spec.flags & SMALL);
486
	if (spec.flags & LEFT)
487
		spec.flags &= ~ZEROPAD;
488
	sign = 0;
489
	if (spec.flags & SIGN) {
490
		if ((signed long long)num < 0) {
491
			sign = '-';
492
			num = -(signed long long)num;
493
			spec.field_width--;
494
		} else if (spec.flags & PLUS) {
495
			sign = '+';
496
			spec.field_width--;
497
		} else if (spec.flags & SPACE) {
498
			sign = ' ';
499
			spec.field_width--;
500
		}
501
	}
502
	if (need_pfx) {
503
		if (spec.base == 16)
5056 serge 504
			spec.field_width -= 2;
505
		else if (!is_zero)
1869 serge 506
			spec.field_width--;
507
	}
508
 
509
	/* generate full string in tmp[], in reverse order */
510
	i = 0;
5056 serge 511
	if (num < spec.base)
6082 serge 512
		tmp[i++] = hex_asc_upper[num] | locase;
1869 serge 513
	else if (spec.base != 10) { /* 8 or 16 */
514
		int mask = spec.base - 1;
515
		int shift = 3;
516
 
517
		if (spec.base == 16)
518
			shift = 4;
519
		do {
6082 serge 520
			tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
1869 serge 521
			num >>= shift;
522
		} while (num);
523
	} else { /* base 10 */
524
		i = put_dec(tmp, num) - tmp;
525
	}
526
 
527
	/* printing 100 using %2d gives "100", not "00" */
528
	if (i > spec.precision)
529
		spec.precision = i;
530
	/* leading space padding */
531
	spec.field_width -= spec.precision;
6082 serge 532
	if (!(spec.flags & (ZEROPAD | LEFT))) {
1869 serge 533
		while (--spec.field_width >= 0) {
534
			if (buf < end)
535
				*buf = ' ';
536
			++buf;
537
		}
538
	}
539
	/* sign */
540
	if (sign) {
541
		if (buf < end)
542
			*buf = sign;
543
		++buf;
544
	}
545
	/* "0x" / "0" prefix */
546
	if (need_pfx) {
5056 serge 547
		if (spec.base == 16 || !is_zero) {
1869 serge 548
		if (buf < end)
549
			*buf = '0';
550
		++buf;
5056 serge 551
		}
1869 serge 552
		if (spec.base == 16) {
553
			if (buf < end)
554
				*buf = ('X' | locase);
555
			++buf;
556
		}
557
	}
558
	/* zero or space padding */
559
	if (!(spec.flags & LEFT)) {
6082 serge 560
		char c = ' ' + (spec.flags & ZEROPAD);
561
		BUILD_BUG_ON(' ' + ZEROPAD != '0');
1869 serge 562
		while (--spec.field_width >= 0) {
563
			if (buf < end)
564
				*buf = c;
565
			++buf;
566
		}
567
	}
568
	/* hmm even more zero padding? */
569
	while (i <= --spec.precision) {
570
		if (buf < end)
571
			*buf = '0';
572
		++buf;
573
	}
574
	/* actual digits of result */
575
	while (--i >= 0) {
576
		if (buf < end)
577
			*buf = tmp[i];
578
		++buf;
579
	}
580
	/* trailing space padding */
581
	while (--spec.field_width >= 0) {
582
		if (buf < end)
583
			*buf = ' ';
584
		++buf;
585
	}
586
 
587
	return buf;
588
}
589
 
590
static noinline_for_stack
591
char *string(char *buf, char *end, const char *s, struct printf_spec spec)
592
{
593
	int len, i;
594
 
5056 serge 595
	if ((unsigned long)s < PAGE_SIZE)
1869 serge 596
		s = "(null)";
597
 
598
	len = strnlen(s, spec.precision);
599
 
600
	if (!(spec.flags & LEFT)) {
601
		while (len < spec.field_width--) {
602
			if (buf < end)
603
				*buf = ' ';
604
			++buf;
605
		}
606
	}
607
	for (i = 0; i < len; ++i) {
608
		if (buf < end)
609
			*buf = *s;
610
		++buf; ++s;
611
	}
612
	while (len < spec.field_width--) {
613
		if (buf < end)
614
			*buf = ' ';
615
		++buf;
616
	}
617
 
618
	return buf;
619
}
620
 
621
static noinline_for_stack
622
char *symbol_string(char *buf, char *end, void *ptr,
5056 serge 623
		    struct printf_spec spec, const char *fmt)
1869 serge 624
{
5056 serge 625
	unsigned long value;
1869 serge 626
#ifdef CONFIG_KALLSYMS
627
	char sym[KSYM_SYMBOL_LEN];
5056 serge 628
#endif
629
 
630
	if (fmt[1] == 'R')
631
		ptr = __builtin_extract_return_addr(ptr);
632
	value = (unsigned long)ptr;
633
 
634
#ifdef CONFIG_KALLSYMS
635
	if (*fmt == 'B')
636
		sprint_backtrace(sym, value);
637
	else if (*fmt != 'f' && *fmt != 's')
1869 serge 638
		sprint_symbol(sym, value);
639
	else
5056 serge 640
		sprint_symbol_no_offset(sym, value);
1869 serge 641
 
642
	return string(buf, end, sym, spec);
643
#else
644
	spec.field_width = 2 * sizeof(void *);
645
	spec.flags |= SPECIAL | SMALL | ZEROPAD;
646
	spec.base = 16;
647
 
648
	return number(buf, end, value, spec);
649
#endif
650
}
651
 
652
static noinline_for_stack
653
char *resource_string(char *buf, char *end, struct resource *res,
654
		      struct printf_spec spec, const char *fmt)
655
{
656
#ifndef IO_RSRC_PRINTK_SIZE
657
#define IO_RSRC_PRINTK_SIZE	6
658
#endif
659
 
660
#ifndef MEM_RSRC_PRINTK_SIZE
661
#define MEM_RSRC_PRINTK_SIZE	10
662
#endif
663
	static const struct printf_spec io_spec = {
664
		.base = 16,
665
		.field_width = IO_RSRC_PRINTK_SIZE,
666
		.precision = -1,
667
		.flags = SPECIAL | SMALL | ZEROPAD,
668
	};
669
	static const struct printf_spec mem_spec = {
670
		.base = 16,
671
		.field_width = MEM_RSRC_PRINTK_SIZE,
672
		.precision = -1,
673
		.flags = SPECIAL | SMALL | ZEROPAD,
674
	};
675
	static const struct printf_spec bus_spec = {
676
		.base = 16,
677
		.field_width = 2,
678
		.precision = -1,
679
		.flags = SMALL | ZEROPAD,
680
	};
681
	static const struct printf_spec dec_spec = {
682
		.base = 10,
683
		.precision = -1,
684
		.flags = 0,
685
	};
686
	static const struct printf_spec str_spec = {
687
		.field_width = -1,
688
		.precision = 10,
689
		.flags = LEFT,
690
	};
691
	static const struct printf_spec flag_spec = {
692
		.base = 16,
693
		.precision = -1,
694
		.flags = SPECIAL | SMALL,
695
	};
696
 
697
	/* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
698
	 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
699
#define RSRC_BUF_SIZE		((2 * sizeof(resource_size_t)) + 4)
700
#define FLAG_BUF_SIZE		(2 * sizeof(res->flags))
701
#define DECODED_BUF_SIZE	sizeof("[mem - 64bit pref window disabled]")
702
#define RAW_BUF_SIZE		sizeof("[mem - flags 0x]")
703
	char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
704
		     2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
705
 
706
	char *p = sym, *pend = sym + sizeof(sym);
707
	int decode = (fmt[0] == 'R') ? 1 : 0;
708
	const struct printf_spec *specp;
709
 
710
	*p++ = '[';
711
	if (res->flags & IORESOURCE_IO) {
712
		p = string(p, pend, "io  ", str_spec);
713
		specp = &io_spec;
714
	} else if (res->flags & IORESOURCE_MEM) {
715
		p = string(p, pend, "mem ", str_spec);
716
		specp = &mem_spec;
717
	} else if (res->flags & IORESOURCE_IRQ) {
718
		p = string(p, pend, "irq ", str_spec);
719
		specp = &dec_spec;
720
	} else if (res->flags & IORESOURCE_DMA) {
721
		p = string(p, pend, "dma ", str_spec);
722
		specp = &dec_spec;
723
	} else if (res->flags & IORESOURCE_BUS) {
724
		p = string(p, pend, "bus ", str_spec);
725
		specp = &bus_spec;
726
	} else {
727
		p = string(p, pend, "??? ", str_spec);
728
		specp = &mem_spec;
729
		decode = 0;
730
	}
6082 serge 731
	if (decode && res->flags & IORESOURCE_UNSET) {
732
		p = string(p, pend, "size ", str_spec);
733
		p = number(p, pend, resource_size(res), *specp);
734
	} else {
1869 serge 735
	p = number(p, pend, res->start, *specp);
736
	if (res->start != res->end) {
737
		*p++ = '-';
738
		p = number(p, pend, res->end, *specp);
6082 serge 739
		}
1869 serge 740
	}
741
	if (decode) {
742
		if (res->flags & IORESOURCE_MEM_64)
743
			p = string(p, pend, " 64bit", str_spec);
744
		if (res->flags & IORESOURCE_PREFETCH)
745
			p = string(p, pend, " pref", str_spec);
746
		if (res->flags & IORESOURCE_WINDOW)
747
			p = string(p, pend, " window", str_spec);
748
		if (res->flags & IORESOURCE_DISABLED)
749
			p = string(p, pend, " disabled", str_spec);
750
	} else {
751
		p = string(p, pend, " flags ", str_spec);
752
		p = number(p, pend, res->flags, flag_spec);
753
	}
754
	*p++ = ']';
755
	*p = '\0';
756
 
757
	return string(buf, end, sym, spec);
758
}
759
 
760
static noinline_for_stack
5056 serge 761
char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
762
		 const char *fmt)
763
{
764
	int i, len = 1;		/* if we pass '%ph[CDN]', field width remains
765
				   negative value, fallback to the default */
766
	char separator;
767
 
768
	if (spec.field_width == 0)
769
		/* nothing to print */
770
		return buf;
771
 
772
	if (ZERO_OR_NULL_PTR(addr))
773
		/* NULL pointer */
774
		return string(buf, end, NULL, spec);
775
 
776
	switch (fmt[1]) {
777
	case 'C':
778
		separator = ':';
779
		break;
780
	case 'D':
781
		separator = '-';
782
		break;
783
	case 'N':
784
		separator = 0;
785
		break;
786
	default:
787
		separator = ' ';
788
		break;
789
	}
790
 
791
	if (spec.field_width > 0)
792
		len = min_t(int, spec.field_width, 64);
793
 
6082 serge 794
	for (i = 0; i < len; ++i) {
795
		if (buf < end)
796
			*buf = hex_asc_hi(addr[i]);
797
		++buf;
798
		if (buf < end)
799
			*buf = hex_asc_lo(addr[i]);
800
		++buf;
5056 serge 801
 
6082 serge 802
		if (separator && i != len - 1) {
803
			if (buf < end)
804
				*buf = separator;
805
			++buf;
806
		}
5056 serge 807
	}
808
 
809
	return buf;
810
}
811
 
812
static noinline_for_stack
6082 serge 813
char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
814
		    struct printf_spec spec, const char *fmt)
815
{
816
	const int CHUNKSZ = 32;
817
	int nr_bits = max_t(int, spec.field_width, 0);
818
	int i, chunksz;
819
	bool first = true;
820
 
821
	/* reused to print numbers */
822
	spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
823
 
824
	chunksz = nr_bits & (CHUNKSZ - 1);
825
	if (chunksz == 0)
826
		chunksz = CHUNKSZ;
827
 
828
	i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
829
	for (; i >= 0; i -= CHUNKSZ) {
830
		u32 chunkmask, val;
831
		int word, bit;
832
 
833
		chunkmask = ((1ULL << chunksz) - 1);
834
		word = i / BITS_PER_LONG;
835
		bit = i % BITS_PER_LONG;
836
		val = (bitmap[word] >> bit) & chunkmask;
837
 
838
		if (!first) {
839
			if (buf < end)
840
				*buf = ',';
841
			buf++;
842
		}
843
		first = false;
844
 
845
		spec.field_width = DIV_ROUND_UP(chunksz, 4);
846
		buf = number(buf, end, val, spec);
847
 
848
		chunksz = CHUNKSZ;
849
	}
850
	return buf;
851
}
852
 
853
static noinline_for_stack
854
char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
855
			 struct printf_spec spec, const char *fmt)
856
{
857
	int nr_bits = max_t(int, spec.field_width, 0);
858
	/* current bit is 'cur', most recently seen range is [rbot, rtop] */
859
	int cur, rbot, rtop;
860
	bool first = true;
861
 
862
	/* reused to print numbers */
863
	spec = (struct printf_spec){ .base = 10 };
864
 
865
	rbot = cur = find_first_bit(bitmap, nr_bits);
866
	while (cur < nr_bits) {
867
		rtop = cur;
868
		cur = find_next_bit(bitmap, nr_bits, cur + 1);
869
		if (cur < nr_bits && cur <= rtop + 1)
870
			continue;
871
 
872
		if (!first) {
873
			if (buf < end)
874
				*buf = ',';
875
			buf++;
876
		}
877
		first = false;
878
 
879
		buf = number(buf, end, rbot, spec);
880
		if (rbot < rtop) {
881
			if (buf < end)
882
				*buf = '-';
883
			buf++;
884
 
885
			buf = number(buf, end, rtop, spec);
886
	}
887
 
888
		rbot = cur;
889
	}
890
	return buf;
891
}
892
 
893
static noinline_for_stack
1869 serge 894
char *mac_address_string(char *buf, char *end, u8 *addr,
895
			 struct printf_spec spec, const char *fmt)
896
{
897
	char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
898
	char *p = mac_addr;
899
	int i;
900
	char separator;
5056 serge 901
	bool reversed = false;
1869 serge 902
 
5056 serge 903
	switch (fmt[1]) {
904
	case 'F':
1869 serge 905
		separator = '-';
5056 serge 906
		break;
907
 
908
	case 'R':
909
		reversed = true;
910
		/* fall through */
911
 
912
	default:
1869 serge 913
		separator = ':';
5056 serge 914
		break;
1869 serge 915
	}
916
 
917
	for (i = 0; i < 6; i++) {
5056 serge 918
		if (reversed)
919
			p = hex_byte_pack(p, addr[5 - i]);
920
		else
921
			p = hex_byte_pack(p, addr[i]);
922
 
1869 serge 923
		if (fmt[0] == 'M' && i != 5)
924
			*p++ = separator;
925
	}
926
	*p = '\0';
927
 
928
	return string(buf, end, mac_addr, spec);
929
}
930
 
931
static noinline_for_stack
932
char *ip4_string(char *p, const u8 *addr, const char *fmt)
933
{
934
	int i;
935
	bool leading_zeros = (fmt[0] == 'i');
936
	int index;
937
	int step;
938
 
939
	switch (fmt[2]) {
940
	case 'h':
941
#ifdef __BIG_ENDIAN
942
		index = 0;
943
		step = 1;
944
#else
945
		index = 3;
946
		step = -1;
947
#endif
948
		break;
949
	case 'l':
950
		index = 3;
951
		step = -1;
952
		break;
953
	case 'n':
954
	case 'b':
955
	default:
956
		index = 0;
957
		step = 1;
958
		break;
959
	}
960
	for (i = 0; i < 4; i++) {
6082 serge 961
		char temp[4] __aligned(2);	/* hold each IP quad in reverse order */
5056 serge 962
		int digits = put_dec_trunc8(temp, addr[index]) - temp;
1869 serge 963
		if (leading_zeros) {
964
			if (digits < 3)
965
				*p++ = '0';
966
			if (digits < 2)
967
				*p++ = '0';
968
		}
969
		/* reverse the digits in the quad */
970
		while (digits--)
971
			*p++ = temp[digits];
972
		if (i < 3)
973
			*p++ = '.';
974
		index += step;
975
	}
976
	*p = '\0';
977
 
978
	return p;
979
}
980
 
981
 
982
static noinline_for_stack
983
char *ip4_addr_string(char *buf, char *end, const u8 *addr,
984
		      struct printf_spec spec, const char *fmt)
985
{
986
	char ip4_addr[sizeof("255.255.255.255")];
987
 
988
	ip4_string(ip4_addr, addr, fmt);
989
 
990
	return string(buf, end, ip4_addr, spec);
991
}
992
 
993
 
994
int kptr_restrict = 1;
995
 
996
/*
997
 * Show a '%p' thing.  A kernel extension is that the '%p' is followed
998
 * by an extra set of alphanumeric characters that are extended format
999
 * specifiers.
1000
 *
1001
 * Right now we handle:
1002
 *
1003
 * - 'F' For symbolic function descriptor pointers with offset
1004
 * - 'f' For simple symbolic function names without offset
1005
 * - 'S' For symbolic direct pointers with offset
1006
 * - 's' For symbolic direct pointers without offset
5056 serge 1007
 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1008
 * - 'B' For backtraced symbolic direct pointers with offset
1869 serge 1009
 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1010
 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
6082 serge 1011
 * - 'b[l]' For a bitmap, the number of bits is determined by the field
1012
 *       width which must be explicitly specified either as part of the
1013
 *       format string '%32b[l]' or through '%*b[l]', [l] selects
1014
 *       range-list format instead of hex format
1869 serge 1015
 * - 'M' For a 6-byte MAC address, it prints the address in the
1016
 *       usual colon-separated hex notation
1017
 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1018
 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1019
 *       with a dash-separated hex notation
5056 serge 1020
 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1869 serge 1021
 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1022
 *       IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1023
 *       IPv6 uses colon separated network-order 16 bit hex with leading 0's
5056 serge 1024
 *       [S][pfs]
1025
 *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1026
 *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1869 serge 1027
 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1028
 *       IPv6 omits the colons (01020304...0f)
1029
 *       IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
5056 serge 1030
 *       [S][pfs]
1031
 *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1032
 *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1033
 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1034
 * - 'I[6S]c' for IPv6 addresses printed as specified by
1035
 *       http://tools.ietf.org/html/rfc5952
6082 serge 1036
 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1037
 *                of the following flags (see string_escape_mem() for the
1038
 *                details):
1039
 *                  a - ESCAPE_ANY
1040
 *                  c - ESCAPE_SPECIAL
1041
 *                  h - ESCAPE_HEX
1042
 *                  n - ESCAPE_NULL
1043
 *                  o - ESCAPE_OCTAL
1044
 *                  p - ESCAPE_NP
1045
 *                  s - ESCAPE_SPACE
1046
 *                By default ESCAPE_ANY_NP is used.
1869 serge 1047
 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1048
 *       "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1049
 *       Options for %pU are:
1050
 *         b big endian lower case hex (default)
1051
 *         B big endian UPPER case hex
1052
 *         l little endian lower case hex
1053
 *         L little endian UPPER case hex
1054
 *           big endian output byte order is:
1055
 *             [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1056
 *           little endian output byte order is:
1057
 *             [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1058
 * - 'V' For a struct va_format which contains a format string * and va_list *,
1059
 *       call vsnprintf(->format, *->va_list).
1060
 *       Implements a "recursive vsnprintf".
1061
 *       Do not use this feature without some mechanism to verify the
1062
 *       correctness of the format string and va_list arguments.
1063
 * - 'K' For a kernel pointer that should be hidden from unprivileged users
5056 serge 1064
 * - 'NF' For a netdev_features_t
1065
 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1066
 *            a certain separator (' ' by default):
1067
 *              C colon
1068
 *              D dash
1069
 *              N no separator
1070
 *            The maximum supported length is 64 bytes of the input. Consider
1071
 *            to use print_hex_dump() for the larger input.
1072
 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1073
 *           (default assumed to be phys_addr_t, passed by reference)
1074
 * - 'd[234]' For a dentry name (optionally 2-4 last components)
1075
 * - 'D[234]' Same as 'd' but for a struct file
6082 serge 1076
 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1077
 *       (legacy clock framework) of the clock
1078
 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1079
 *        (legacy clock framework) of the clock
1080
 * - 'Cr' For a clock, it prints the current rate of the clock
1869 serge 1081
 *
6293 serge 1082
 * ** Please update also Documentation/printk-formats.txt when making changes **
1083
 *
1869 serge 1084
 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1085
 * function pointers are really function descriptors, which contain a
1086
 * pointer to the real address.
1087
 */
1088
static noinline_for_stack
1089
char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1090
	      struct printf_spec spec)
1091
{
6293 serge 1092
	const int default_width = 2 * sizeof(void *);
5056 serge 1093
 
1094
	if (!ptr && *fmt != 'K') {
1869 serge 1095
		/*
1096
		 * Print (null) with the same width as a pointer so it makes
1097
		 * tabular output look nice.
1098
		 */
1099
		if (spec.field_width == -1)
5056 serge 1100
			spec.field_width = default_width;
1869 serge 1101
		return string(buf, end, "(null)", spec);
1102
	}
1103
 
1104
	switch (*fmt) {
1105
	case 'F':
1106
	case 'f':
1107
		ptr = dereference_function_descriptor(ptr);
1108
		/* Fallthrough */
1109
	case 'S':
1110
	case 's':
5056 serge 1111
	case 'B':
1112
		return symbol_string(buf, end, ptr, spec, fmt);
1869 serge 1113
	case 'R':
1114
	case 'r':
1115
		return resource_string(buf, end, ptr, spec, fmt);
5056 serge 1116
	case 'h':
1117
		return hex_string(buf, end, ptr, spec, fmt);
1869 serge 1118
	case 'M':			/* Colon separated: 00:01:02:03:04:05 */
1119
	case 'm':			/* Contiguous: 000102030405 */
5056 serge 1120
					/* [mM]F (FDDI) */
1121
					/* [mM]R (Reverse order; Bluetooth) */
1869 serge 1122
		return mac_address_string(buf, end, ptr, spec, fmt);
1123
	case 'I':			/* Formatted IP supported
1124
					 * 4:	1.2.3.4
1125
					 * 6:	0001:0203:...:0708
1126
					 * 6c:	1::708 or 1::1.2.3.4
1127
					 */
1128
	case 'i':			/* Contiguous:
1129
					 * 4:	001.002.003.004
1130
					 * 6:   000102...0f
1131
					 */
1132
		switch (fmt[1]) {
1133
		case '4':
1134
			return ip4_addr_string(buf, end, ptr, spec, fmt);
1135
		}
1136
		break;
1137
	case 'V':
5056 serge 1138
		{
1139
			va_list va;
1140
 
1141
			va_copy(va, *((struct va_format *)ptr)->va);
1142
			buf += vsnprintf(buf, end > buf ? end - buf : 0,
1143
					 ((struct va_format *)ptr)->fmt, va);
1144
			va_end(va);
1145
			return buf;
1146
		}
1147
 
1869 serge 1148
	}
1149
	spec.flags |= SMALL;
1150
	if (spec.field_width == -1) {
5056 serge 1151
		spec.field_width = default_width;
1869 serge 1152
		spec.flags |= ZEROPAD;
1153
	}
1154
	spec.base = 16;
1155
 
1156
	return number(buf, end, (unsigned long) ptr, spec);
1157
}
1158
 
1159
/*
1160
 * Helper function to decode printf style format.
1161
 * Each call decode a token from the format and return the
1162
 * number of characters read (or likely the delta where it wants
1163
 * to go on the next call).
1164
 * The decoded token is returned through the parameters
1165
 *
1166
 * 'h', 'l', or 'L' for integer fields
1167
 * 'z' support added 23/7/1999 S.H.
1168
 * 'z' changed to 'Z' --davidm 1/25/99
1169
 * 't' added for ptrdiff_t
1170
 *
1171
 * @fmt: the format string
1172
 * @type of the token returned
1173
 * @flags: various flags such as +, -, # tokens..
1174
 * @field_width: overwritten width
1175
 * @base: base of the number (octal, hex, ...)
1176
 * @precision: precision of a number
1177
 * @qualifier: qualifier of a number (long, size_t, ...)
1178
 */
1179
static noinline_for_stack
1180
int format_decode(const char *fmt, struct printf_spec *spec)
1181
{
1182
	const char *start = fmt;
1183
 
1184
	/* we finished early by reading the field width */
1185
	if (spec->type == FORMAT_TYPE_WIDTH) {
1186
		if (spec->field_width < 0) {
1187
			spec->field_width = -spec->field_width;
1188
			spec->flags |= LEFT;
1189
		}
1190
		spec->type = FORMAT_TYPE_NONE;
1191
		goto precision;
1192
	}
1193
 
1194
	/* we finished early by reading the precision */
1195
	if (spec->type == FORMAT_TYPE_PRECISION) {
1196
		if (spec->precision < 0)
1197
			spec->precision = 0;
1198
 
1199
		spec->type = FORMAT_TYPE_NONE;
1200
		goto qualifier;
1201
	}
1202
 
1203
	/* By default */
1204
	spec->type = FORMAT_TYPE_NONE;
1205
 
1206
	for (; *fmt ; ++fmt) {
1207
		if (*fmt == '%')
1208
			break;
1209
	}
1210
 
1211
	/* Return the current non-format string */
1212
	if (fmt != start || !*fmt)
1213
		return fmt - start;
1214
 
1215
	/* Process flags */
1216
	spec->flags = 0;
1217
 
1218
	while (1) { /* this also skips first '%' */
1219
		bool found = true;
1220
 
1221
		++fmt;
1222
 
1223
		switch (*fmt) {
1224
		case '-': spec->flags |= LEFT;    break;
1225
		case '+': spec->flags |= PLUS;    break;
1226
		case ' ': spec->flags |= SPACE;   break;
1227
		case '#': spec->flags |= SPECIAL; break;
1228
		case '0': spec->flags |= ZEROPAD; break;
1229
		default:  found = false;
1230
		}
1231
 
1232
		if (!found)
1233
			break;
1234
	}
1235
 
1236
	/* get field width */
1237
	spec->field_width = -1;
1238
 
1239
	if (isdigit(*fmt))
1240
		spec->field_width = skip_atoi(&fmt);
1241
	else if (*fmt == '*') {
1242
		/* it's the next argument */
1243
		spec->type = FORMAT_TYPE_WIDTH;
1244
		return ++fmt - start;
1245
	}
1246
 
1247
precision:
1248
	/* get the precision */
1249
	spec->precision = -1;
1250
	if (*fmt == '.') {
1251
		++fmt;
1252
		if (isdigit(*fmt)) {
1253
			spec->precision = skip_atoi(&fmt);
1254
			if (spec->precision < 0)
1255
				spec->precision = 0;
1256
		} else if (*fmt == '*') {
1257
			/* it's the next argument */
1258
			spec->type = FORMAT_TYPE_PRECISION;
1259
			return ++fmt - start;
1260
		}
1261
	}
1262
 
1263
qualifier:
1264
	/* get the conversion qualifier */
1265
	spec->qualifier = -1;
5056 serge 1266
	if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1267
	    _tolower(*fmt) == 'z' || *fmt == 't') {
1869 serge 1268
		spec->qualifier = *fmt++;
1269
		if (unlikely(spec->qualifier == *fmt)) {
1270
			if (spec->qualifier == 'l') {
1271
				spec->qualifier = 'L';
1272
				++fmt;
1273
			} else if (spec->qualifier == 'h') {
1274
				spec->qualifier = 'H';
1275
				++fmt;
1276
			}
1277
		}
1278
	}
1279
 
1280
	/* default base */
1281
	spec->base = 10;
1282
	switch (*fmt) {
1283
	case 'c':
1284
		spec->type = FORMAT_TYPE_CHAR;
1285
		return ++fmt - start;
1286
 
1287
	case 's':
1288
		spec->type = FORMAT_TYPE_STR;
1289
		return ++fmt - start;
1290
 
1291
	case 'p':
1292
		spec->type = FORMAT_TYPE_PTR;
6082 serge 1293
		return ++fmt - start;
1869 serge 1294
 
1295
	case '%':
1296
		spec->type = FORMAT_TYPE_PERCENT_CHAR;
1297
		return ++fmt - start;
1298
 
1299
	/* integer number formats - set up the flags and "break" */
1300
	case 'o':
1301
		spec->base = 8;
1302
		break;
1303
 
1304
	case 'x':
1305
		spec->flags |= SMALL;
1306
 
1307
	case 'X':
1308
		spec->base = 16;
1309
		break;
1310
 
1311
	case 'd':
1312
	case 'i':
1313
		spec->flags |= SIGN;
1314
	case 'u':
1315
		break;
1316
 
5056 serge 1317
	case 'n':
1318
		/*
6293 serge 1319
		 * Since %n poses a greater security risk than
1320
		 * utility, treat it as any other invalid or
1321
		 * unsupported format specifier.
5056 serge 1322
		 */
1323
		/* Fall-through */
1324
 
1869 serge 1325
	default:
1326
		spec->type = FORMAT_TYPE_INVALID;
1327
		return fmt - start;
1328
	}
1329
 
1330
	if (spec->qualifier == 'L')
1331
		spec->type = FORMAT_TYPE_LONG_LONG;
1332
	else if (spec->qualifier == 'l') {
6082 serge 1333
		BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
1334
		spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
5056 serge 1335
	} else if (_tolower(spec->qualifier) == 'z') {
1869 serge 1336
		spec->type = FORMAT_TYPE_SIZE_T;
1337
	} else if (spec->qualifier == 't') {
1338
		spec->type = FORMAT_TYPE_PTRDIFF;
1339
	} else if (spec->qualifier == 'H') {
6082 serge 1340
		BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
1341
		spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
1869 serge 1342
	} else if (spec->qualifier == 'h') {
6082 serge 1343
		BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
1344
		spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
1869 serge 1345
	} else {
6082 serge 1346
		BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
1347
		spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
1869 serge 1348
	}
1349
 
1350
	return ++fmt - start;
1351
}
1352
 
1353
/**
1354
 * vsnprintf - Format a string and place it in a buffer
1355
 * @buf: The buffer to place the result into
1356
 * @size: The size of the buffer, including the trailing null space
1357
 * @fmt: The format string to use
1358
 * @args: Arguments for the format string
1359
 *
6293 serge 1360
 * This function generally follows C99 vsnprintf, but has some
1361
 * extensions and a few limitations:
1869 serge 1362
 *
6293 serge 1363
 * %n is unsupported
1364
 * %p* is handled by pointer()
5056 serge 1365
 *
6293 serge 1366
 * See pointer() or Documentation/printk-formats.txt for more
1367
 * extensive description.
1368
 *
1369
 * ** Please update the documentation in both places when making changes **
1370
 *
1869 serge 1371
 * The return value is the number of characters which would
1372
 * be generated for the given input, excluding the trailing
1373
 * '\0', as per ISO C99. If you want to have the exact
1374
 * number of characters written into @buf as return value
1375
 * (not including the trailing '\0'), use vscnprintf(). If the
1376
 * return is greater than or equal to @size, the resulting
1377
 * string is truncated.
1378
 *
5056 serge 1379
 * If you're not already dealing with a va_list consider using snprintf().
1869 serge 1380
 */
1381
int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1382
{
1383
	unsigned long long num;
1384
	char *str, *end;
1385
	struct printf_spec spec = {0};
1386
 
1387
	/* Reject out-of-range values early.  Large positive sizes are
1388
	   used for unknown buffer sizes. */
6082 serge 1389
	if (WARN_ON_ONCE(size > INT_MAX))
1869 serge 1390
		return 0;
1391
 
1392
	str = buf;
1393
	end = buf + size;
1394
 
1395
	/* Make sure end is always >= buf */
1396
	if (end < buf) {
1397
		end = ((void *)-1);
1398
		size = end - buf;
1399
	}
1400
 
1401
	while (*fmt) {
1402
		const char *old_fmt = fmt;
1403
		int read = format_decode(fmt, &spec);
1404
 
1405
		fmt += read;
1406
 
1407
		switch (spec.type) {
1408
		case FORMAT_TYPE_NONE: {
1409
			int copy = read;
1410
			if (str < end) {
1411
				if (copy > end - str)
1412
					copy = end - str;
1413
				memcpy(str, old_fmt, copy);
1414
			}
1415
			str += read;
1416
			break;
1417
		}
1418
 
1419
		case FORMAT_TYPE_WIDTH:
1420
			spec.field_width = va_arg(args, int);
1421
			break;
1422
 
1423
		case FORMAT_TYPE_PRECISION:
1424
			spec.precision = va_arg(args, int);
1425
			break;
1426
 
1427
		case FORMAT_TYPE_CHAR: {
1428
			char c;
1429
 
1430
			if (!(spec.flags & LEFT)) {
1431
				while (--spec.field_width > 0) {
1432
					if (str < end)
1433
						*str = ' ';
1434
					++str;
1435
 
1436
				}
1437
			}
1438
			c = (unsigned char) va_arg(args, int);
1439
			if (str < end)
1440
				*str = c;
1441
			++str;
1442
			while (--spec.field_width > 0) {
1443
				if (str < end)
1444
					*str = ' ';
1445
				++str;
1446
			}
1447
			break;
1448
		}
1449
 
1450
		case FORMAT_TYPE_STR:
1451
			str = string(str, end, va_arg(args, char *), spec);
1452
			break;
1453
 
1454
		case FORMAT_TYPE_PTR:
6082 serge 1455
			str = pointer(fmt, str, end, va_arg(args, void *),
1869 serge 1456
				      spec);
1457
			while (isalnum(*fmt))
1458
				fmt++;
1459
			break;
1460
 
1461
		case FORMAT_TYPE_PERCENT_CHAR:
1462
			if (str < end)
1463
				*str = '%';
1464
			++str;
1465
			break;
1466
 
1467
		case FORMAT_TYPE_INVALID:
6293 serge 1468
			/*
1469
			 * Presumably the arguments passed gcc's type
1470
			 * checking, but there is no safe or sane way
1471
			 * for us to continue parsing the format and
1472
			 * fetching from the va_list; the remaining
1473
			 * specifiers and arguments would be out of
1474
			 * sync.
1475
			 */
1476
			goto out;
1869 serge 1477
 
1478
		default:
1479
			switch (spec.type) {
1480
			case FORMAT_TYPE_LONG_LONG:
1481
				num = va_arg(args, long long);
1482
				break;
1483
			case FORMAT_TYPE_ULONG:
1484
				num = va_arg(args, unsigned long);
1485
				break;
1486
			case FORMAT_TYPE_LONG:
1487
				num = va_arg(args, long);
1488
				break;
1489
			case FORMAT_TYPE_SIZE_T:
5056 serge 1490
				if (spec.flags & SIGN)
1491
					num = va_arg(args, ssize_t);
1492
				else
1869 serge 1493
				num = va_arg(args, size_t);
1494
				break;
1495
			case FORMAT_TYPE_PTRDIFF:
1496
				num = va_arg(args, ptrdiff_t);
1497
				break;
1498
			case FORMAT_TYPE_UBYTE:
1499
				num = (unsigned char) va_arg(args, int);
1500
				break;
1501
			case FORMAT_TYPE_BYTE:
1502
				num = (signed char) va_arg(args, int);
1503
				break;
1504
			case FORMAT_TYPE_USHORT:
1505
				num = (unsigned short) va_arg(args, int);
1506
				break;
1507
			case FORMAT_TYPE_SHORT:
1508
				num = (short) va_arg(args, int);
1509
				break;
1510
			case FORMAT_TYPE_INT:
1511
				num = (int) va_arg(args, int);
1512
				break;
1513
			default:
1514
				num = va_arg(args, unsigned int);
1515
			}
1516
 
1517
			str = number(str, end, num, spec);
1518
		}
1519
	}
1520
 
6293 serge 1521
out:
1869 serge 1522
	if (size > 0) {
1523
		if (str < end)
1524
			*str = '\0';
1525
		else
1526
			end[-1] = '\0';
1527
	}
1528
 
1529
	/* the trailing null byte doesn't count towards the total */
1530
	return str-buf;
1531
 
1532
}
1533
EXPORT_SYMBOL(vsnprintf);
1534
 
5056 serge 1535
/**
1536
 * vscnprintf - Format a string and place it in a buffer
1537
 * @buf: The buffer to place the result into
1538
 * @size: The size of the buffer, including the trailing null space
1539
 * @fmt: The format string to use
1540
 * @args: Arguments for the format string
1541
 *
1542
 * The return value is the number of characters which have been written into
1543
 * the @buf not including the trailing '\0'. If @size is == 0 the function
1544
 * returns 0.
1545
 *
1546
 * If you're not already dealing with a va_list consider using scnprintf().
1547
 *
1548
 * See the vsnprintf() documentation for format string extensions over C99.
1549
 */
1550
int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
1869 serge 1551
{
5056 serge 1552
	int i;
1553
 
1554
	i = vsnprintf(buf, size, fmt, args);
1555
 
1556
	if (likely(i < size))
1557
		return i;
1558
	if (size != 0)
1559
		return size - 1;
1560
	return 0;
1869 serge 1561
}
5056 serge 1562
EXPORT_SYMBOL(vscnprintf);
1869 serge 1563
 
1564
/**
1565
 * snprintf - Format a string and place it in a buffer
1566
 * @buf: The buffer to place the result into
1567
 * @size: The size of the buffer, including the trailing null space
1568
 * @fmt: The format string to use
1569
 * @...: Arguments for the format string
1570
 *
1571
 * The return value is the number of characters which would be
1572
 * generated for the given input, excluding the trailing null,
1573
 * as per ISO C99.  If the return is greater than or equal to
1574
 * @size, the resulting string is truncated.
1575
 *
1576
 * See the vsnprintf() documentation for format string extensions over C99.
1577
 */
1578
int snprintf(char *buf, size_t size, const char *fmt, ...)
1579
{
1580
	va_list args;
1581
	int i;
1582
 
1583
	va_start(args, fmt);
1584
	i = vsnprintf(buf, size, fmt, args);
1585
	va_end(args);
1586
 
1587
	return i;
1588
}
1589
EXPORT_SYMBOL(snprintf);
1590
 
5056 serge 1591
/**
1592
 * scnprintf - Format a string and place it in a buffer
1593
 * @buf: The buffer to place the result into
1594
 * @size: The size of the buffer, including the trailing null space
1595
 * @fmt: The format string to use
1596
 * @...: Arguments for the format string
1597
 *
1598
 * The return value is the number of characters written into @buf not including
1599
 * the trailing '\0'. If @size is == 0 the function returns 0.
1600
 */
1869 serge 1601
 
5056 serge 1602
int scnprintf(char *buf, size_t size, const char *fmt, ...)
1603
{
1604
	va_list args;
1605
	int i;
1606
 
1607
	va_start(args, fmt);
1608
	i = vscnprintf(buf, size, fmt, args);
1609
	va_end(args);
1610
 
1611
	return i;
1612
}
1613
EXPORT_SYMBOL(scnprintf);
1614
 
1869 serge 1615
/**
5056 serge 1616
 * vsprintf - Format a string and place it in a buffer
1617
 * @buf: The buffer to place the result into
1618
 * @fmt: The format string to use
1619
 * @args: Arguments for the format string
1620
 *
1621
 * The function returns the number of characters written
1622
 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
1623
 * buffer overflows.
1624
 *
1625
 * If you're not already dealing with a va_list consider using sprintf().
1626
 *
1627
 * See the vsnprintf() documentation for format string extensions over C99.
1628
 */
1629
int vsprintf(char *buf, const char *fmt, va_list args)
1630
{
1631
	return vsnprintf(buf, INT_MAX, fmt, args);
1632
}
1633
EXPORT_SYMBOL(vsprintf);
1634
 
1635
/**
1869 serge 1636
 * sprintf - Format a string and place it in a buffer
1637
 * @buf: The buffer to place the result into
1638
 * @fmt: The format string to use
1639
 * @...: Arguments for the format string
1640
 *
1641
 * The function returns the number of characters written
1642
 * into @buf. Use snprintf() or scnprintf() in order to avoid
1643
 * buffer overflows.
1644
 *
1645
 * See the vsnprintf() documentation for format string extensions over C99.
1646
 */
1647
int sprintf(char *buf, const char *fmt, ...)
1648
{
1649
	va_list args;
1650
	int i;
1651
 
1652
	va_start(args, fmt);
1653
	i = vsnprintf(buf, INT_MAX, fmt, args);
1654
	va_end(args);
1655
 
1656
	return i;
1657
}
5056 serge 1658
EXPORT_SYMBOL(sprintf);
1659
/**
1660
 * vsscanf - Unformat a buffer into a list of arguments
1661
 * @buf:	input buffer
1662
 * @fmt:	format of buffer
1663
 * @args:	arguments
1664
 */
1665
int vsscanf(const char *buf, const char *fmt, va_list args)
1666
{
1667
	const char *str = buf;
1668
	char *next;
1669
	char digit;
1670
	int num = 0;
1671
	u8 qualifier;
1672
	unsigned int base;
1673
	union {
1674
		long long s;
1675
		unsigned long long u;
1676
	} val;
1677
	s16 field_width;
1678
	bool is_sign;
1869 serge 1679
 
5056 serge 1680
	while (*fmt) {
1681
		/* skip any white space in format */
1682
		/* white space in format matchs any amount of
1683
		 * white space, including none, in the input.
1684
		 */
1685
		if (isspace(*fmt)) {
1686
			fmt = skip_spaces(++fmt);
1687
			str = skip_spaces(str);
1688
		}
1689
 
1690
		/* anything that is not a conversion must match exactly */
1691
		if (*fmt != '%' && *fmt) {
1692
			if (*fmt++ != *str++)
1693
				break;
1694
			continue;
1695
		}
1696
 
1697
		if (!*fmt)
1698
			break;
1699
		++fmt;
1700
 
1701
		/* skip this conversion.
1702
		 * advance both strings to next white space
1703
		 */
1704
		if (*fmt == '*') {
1705
			if (!*str)
1706
				break;
1707
			while (!isspace(*fmt) && *fmt != '%' && *fmt)
1708
				fmt++;
1709
			while (!isspace(*str) && *str)
1710
				str++;
1711
			continue;
1712
		}
1713
 
1714
		/* get field width */
1715
		field_width = -1;
1716
		if (isdigit(*fmt)) {
1717
			field_width = skip_atoi(&fmt);
1718
			if (field_width <= 0)
1719
				break;
1720
		}
1721
 
1722
		/* get conversion qualifier */
1723
		qualifier = -1;
1724
		if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1725
		    _tolower(*fmt) == 'z') {
1726
			qualifier = *fmt++;
1727
			if (unlikely(qualifier == *fmt)) {
1728
				if (qualifier == 'h') {
1729
					qualifier = 'H';
1730
					fmt++;
1731
				} else if (qualifier == 'l') {
1732
					qualifier = 'L';
1733
					fmt++;
1734
				}
1735
			}
1736
		}
1737
 
1738
		if (!*fmt)
1739
			break;
1740
 
1741
		if (*fmt == 'n') {
1742
			/* return number of characters read so far */
1743
			*va_arg(args, int *) = str - buf;
1744
			++fmt;
1745
			continue;
1746
		}
1747
 
1748
		if (!*str)
1749
			break;
1750
 
1751
		base = 10;
1752
		is_sign = false;
1753
 
1754
		switch (*fmt++) {
1755
		case 'c':
1756
		{
1757
			char *s = (char *)va_arg(args, char*);
1758
			if (field_width == -1)
1759
				field_width = 1;
1760
			do {
1761
				*s++ = *str++;
1762
			} while (--field_width > 0 && *str);
1763
			num++;
1764
		}
1765
		continue;
1766
		case 's':
1767
		{
1768
			char *s = (char *)va_arg(args, char *);
1769
			if (field_width == -1)
1770
				field_width = SHRT_MAX;
1771
			/* first, skip leading white space in buffer */
1772
			str = skip_spaces(str);
1773
 
1774
			/* now copy until next white space */
1775
			while (*str && !isspace(*str) && field_width--)
1776
				*s++ = *str++;
1777
			*s = '\0';
1778
			num++;
1779
		}
1780
		continue;
1781
		case 'o':
1782
			base = 8;
1783
			break;
1784
		case 'x':
1785
		case 'X':
1786
			base = 16;
1787
			break;
1788
		case 'i':
1789
			base = 0;
1790
		case 'd':
1791
			is_sign = true;
1792
		case 'u':
1793
			break;
1794
		case '%':
1795
			/* looking for '%' in str */
1796
			if (*str++ != '%')
1797
				return num;
1798
			continue;
1799
		default:
1800
			/* invalid format; stop here */
1801
			return num;
1802
		}
1803
 
1804
		/* have some sort of integer conversion.
1805
		 * first, skip white space in buffer.
1806
		 */
1807
		str = skip_spaces(str);
1808
 
1809
		digit = *str;
1810
		if (is_sign && digit == '-')
1811
			digit = *(str + 1);
1812
 
1813
		if (!digit
1814
		    || (base == 16 && !isxdigit(digit))
1815
		    || (base == 10 && !isdigit(digit))
1816
		    || (base == 8 && (!isdigit(digit) || digit > '7'))
1817
		    || (base == 0 && !isdigit(digit)))
1818
			break;
1819
 
1820
		if (is_sign)
1821
			val.s = qualifier != 'L' ?
1822
				simple_strtol(str, &next, base) :
1823
				simple_strtoll(str, &next, base);
1824
		else
1825
			val.u = qualifier != 'L' ?
1826
				simple_strtoul(str, &next, base) :
1827
				simple_strtoull(str, &next, base);
1828
 
1829
		if (field_width > 0 && next - str > field_width) {
1830
			if (base == 0)
1831
				_parse_integer_fixup_radix(str, &base);
1832
			while (next - str > field_width) {
1833
				if (is_sign)
1834
					val.s = div_s64(val.s, base);
1835
				else
1836
					val.u = div_u64(val.u, base);
1837
				--next;
1838
			}
1839
		}
1840
 
1841
		switch (qualifier) {
1842
		case 'H':	/* that's 'hh' in format */
1843
			if (is_sign)
1844
				*va_arg(args, signed char *) = val.s;
1845
			else
1846
				*va_arg(args, unsigned char *) = val.u;
1847
			break;
1848
		case 'h':
1849
			if (is_sign)
1850
				*va_arg(args, short *) = val.s;
1851
			else
1852
				*va_arg(args, unsigned short *) = val.u;
1853
			break;
1854
		case 'l':
1855
			if (is_sign)
1856
				*va_arg(args, long *) = val.s;
1857
			else
1858
				*va_arg(args, unsigned long *) = val.u;
1859
			break;
1860
		case 'L':
1861
			if (is_sign)
1862
				*va_arg(args, long long *) = val.s;
1863
			else
1864
				*va_arg(args, unsigned long long *) = val.u;
1865
			break;
1866
		case 'Z':
1867
		case 'z':
1868
			*va_arg(args, size_t *) = val.u;
1869
			break;
1870
		default:
1871
			if (is_sign)
1872
				*va_arg(args, int *) = val.s;
1873
			else
1874
				*va_arg(args, unsigned int *) = val.u;
1875
			break;
1876
		}
1877
		num++;
1878
 
1879
		if (!next)
1880
			break;
1881
		str = next;
1882
	}
1883
 
1884
	return num;
1885
}
1886
EXPORT_SYMBOL(vsscanf);
1887
 
1888
/**
1889
 * sscanf - Unformat a buffer into a list of arguments
1890
 * @buf:	input buffer
1891
 * @fmt:	formatting of buffer
1892
 * @...:	resulting arguments
1893
 */
1894
int sscanf(const char *buf, const char *fmt, ...)
1895
{
1896
	va_list args;
1897
	int i;
1898
 
1899
	va_start(args, fmt);
1900
	i = vsscanf(buf, fmt, args);
1901
	va_end(args);
1902
 
1903
	return i;
1904
}
1905
EXPORT_SYMBOL(sscanf);