xref: /openbmc/u-boot/lib/vsprintf.c (revision 44c6e659)
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 #include <stdarg.h>
13 #include <linux/types.h>
14 #include <linux/string.h>
15 #include <linux/ctype.h>
16 
17 #include <common.h>
18 #if !defined (CONFIG_PANIC_HANG)
19 #include <command.h>
20 #endif
21 
22 #include <div64.h>
23 # define NUM_TYPE long long
24 #define noinline __attribute__((noinline))
25 
26 const char hex_asc[] = "0123456789abcdef";
27 #define hex_asc_lo(x)   hex_asc[((x) & 0x0f)]
28 #define hex_asc_hi(x)   hex_asc[((x) & 0xf0) >> 4]
29 
30 static inline char *pack_hex_byte(char *buf, u8 byte)
31 {
32 	*buf++ = hex_asc_hi(byte);
33 	*buf++ = hex_asc_lo(byte);
34 	return buf;
35 }
36 
37 unsigned long simple_strtoul(const char *cp,char **endp,unsigned int base)
38 {
39 	unsigned long result = 0,value;
40 
41 	if (*cp == '0') {
42 		cp++;
43 		if ((*cp == 'x') && isxdigit(cp[1])) {
44 			base = 16;
45 			cp++;
46 		}
47 		if (!base) {
48 			base = 8;
49 		}
50 	}
51 	if (!base) {
52 		base = 10;
53 	}
54 	while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp)
55 	    ? toupper(*cp) : *cp)-'A'+10) < base) {
56 		result = result*base + value;
57 		cp++;
58 	}
59 	if (endp)
60 		*endp = (char *)cp;
61 	return result;
62 }
63 
64 long simple_strtol(const char *cp,char **endp,unsigned int base)
65 {
66 	if(*cp=='-')
67 		return -simple_strtoul(cp+1,endp,base);
68 	return simple_strtoul(cp,endp,base);
69 }
70 
71 int ustrtoul(const char *cp, char **endp, unsigned int base)
72 {
73 	unsigned long result = simple_strtoul(cp, endp, base);
74 	switch (**endp) {
75 	case 'G' :
76 		result *= 1024;
77 		/* fall through */
78 	case 'M':
79 		result *= 1024;
80 		/* fall through */
81 	case 'K':
82 	case 'k':
83 		result *= 1024;
84 		if ((*endp)[1] == 'i') {
85 			if ((*endp)[2] == 'B')
86 				(*endp) += 3;
87 			else
88 				(*endp) += 2;
89 		}
90 	}
91 	return result;
92 }
93 
94 unsigned long long simple_strtoull (const char *cp, char **endp, unsigned int base)
95 {
96 	unsigned long long result = 0, value;
97 
98 	if (*cp == '0') {
99 		cp++;
100 		if ((*cp == 'x') && isxdigit (cp[1])) {
101 			base = 16;
102 			cp++;
103 		}
104 		if (!base) {
105 			base = 8;
106 		}
107 	}
108 	if (!base) {
109 		base = 10;
110 	}
111 	while (isxdigit (*cp) && (value = isdigit (*cp)
112 				? *cp - '0'
113 				: (islower (*cp) ? toupper (*cp) : *cp) - 'A' + 10) < base) {
114 		result = result * base + value;
115 		cp++;
116 	}
117 	if (endp)
118 		*endp = (char *) cp;
119 	return result;
120 }
121 
122 /* we use this so that we can do without the ctype library */
123 #define is_digit(c)	((c) >= '0' && (c) <= '9')
124 
125 static int skip_atoi(const char **s)
126 {
127 	int i=0;
128 
129 	while (is_digit(**s))
130 		i = i*10 + *((*s)++) - '0';
131 	return i;
132 }
133 
134 /* Decimal conversion is by far the most typical, and is used
135  * for /proc and /sys data. This directly impacts e.g. top performance
136  * with many processes running. We optimize it for speed
137  * using code from
138  * http://www.cs.uiowa.edu/~jones/bcd/decimal.html
139  * (with permission from the author, Douglas W. Jones). */
140 
141 /* Formats correctly any integer in [0,99999].
142  * Outputs from one to five digits depending on input.
143  * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
144 static char* put_dec_trunc(char *buf, unsigned q)
145 {
146 	unsigned d3, d2, d1, d0;
147 	d1 = (q>>4) & 0xf;
148 	d2 = (q>>8) & 0xf;
149 	d3 = (q>>12);
150 
151 	d0 = 6*(d3 + d2 + d1) + (q & 0xf);
152 	q = (d0 * 0xcd) >> 11;
153 	d0 = d0 - 10*q;
154 	*buf++ = d0 + '0'; /* least significant digit */
155 	d1 = q + 9*d3 + 5*d2 + d1;
156 	if (d1 != 0) {
157 		q = (d1 * 0xcd) >> 11;
158 		d1 = d1 - 10*q;
159 		*buf++ = d1 + '0'; /* next digit */
160 
161 		d2 = q + 2*d2;
162 		if ((d2 != 0) || (d3 != 0)) {
163 			q = (d2 * 0xd) >> 7;
164 			d2 = d2 - 10*q;
165 			*buf++ = d2 + '0'; /* next digit */
166 
167 			d3 = q + 4*d3;
168 			if (d3 != 0) {
169 				q = (d3 * 0xcd) >> 11;
170 				d3 = d3 - 10*q;
171 				*buf++ = d3 + '0';  /* next digit */
172 				if (q != 0)
173 					*buf++ = q + '0';  /* most sign. digit */
174 			}
175 		}
176 	}
177 	return buf;
178 }
179 /* Same with if's removed. Always emits five digits */
180 static char* put_dec_full(char *buf, unsigned q)
181 {
182 	/* BTW, if q is in [0,9999], 8-bit ints will be enough, */
183 	/* but anyway, gcc produces better code with full-sized ints */
184 	unsigned d3, d2, d1, d0;
185 	d1 = (q>>4) & 0xf;
186 	d2 = (q>>8) & 0xf;
187 	d3 = (q>>12);
188 
189 	/*
190 	 * Possible ways to approx. divide by 10
191 	 * gcc -O2 replaces multiply with shifts and adds
192 	 * (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386)
193 	 * (x * 0x67) >> 10:  1100111
194 	 * (x * 0x34) >> 9:    110100 - same
195 	 * (x * 0x1a) >> 8:     11010 - same
196 	 * (x * 0x0d) >> 7:      1101 - same, shortest code (on i386)
197 	 */
198 
199 	d0 = 6*(d3 + d2 + d1) + (q & 0xf);
200 	q = (d0 * 0xcd) >> 11;
201 	d0 = d0 - 10*q;
202 	*buf++ = d0 + '0';
203 	d1 = q + 9*d3 + 5*d2 + d1;
204 		q = (d1 * 0xcd) >> 11;
205 		d1 = d1 - 10*q;
206 		*buf++ = d1 + '0';
207 
208 		d2 = q + 2*d2;
209 			q = (d2 * 0xd) >> 7;
210 			d2 = d2 - 10*q;
211 			*buf++ = d2 + '0';
212 
213 			d3 = q + 4*d3;
214 				q = (d3 * 0xcd) >> 11; /* - shorter code */
215 				/* q = (d3 * 0x67) >> 10; - would also work */
216 				d3 = d3 - 10*q;
217 				*buf++ = d3 + '0';
218 					*buf++ = q + '0';
219 	return buf;
220 }
221 /* No inlining helps gcc to use registers better */
222 static noinline char* put_dec(char *buf, unsigned NUM_TYPE num)
223 {
224 	while (1) {
225 		unsigned rem;
226 		if (num < 100000)
227 			return put_dec_trunc(buf, num);
228 		rem = do_div(num, 100000);
229 		buf = put_dec_full(buf, rem);
230 	}
231 }
232 
233 #define ZEROPAD	1		/* pad with zero */
234 #define SIGN	2		/* unsigned/signed long */
235 #define PLUS	4		/* show plus */
236 #define SPACE	8		/* space if plus */
237 #define LEFT	16		/* left justified */
238 #define SMALL	32		/* Must be 32 == 0x20 */
239 #define SPECIAL	64		/* 0x */
240 
241 static char *number(char *buf, unsigned NUM_TYPE num, int base, int size, int precision, int type)
242 {
243 	/* we are called with base 8, 10 or 16, only, thus don't need "G..."  */
244 	static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */
245 
246 	char tmp[66];
247 	char sign;
248 	char locase;
249 	int need_pfx = ((type & SPECIAL) && base != 10);
250 	int i;
251 
252 	/* locase = 0 or 0x20. ORing digits or letters with 'locase'
253 	 * produces same digits or (maybe lowercased) letters */
254 	locase = (type & SMALL);
255 	if (type & LEFT)
256 		type &= ~ZEROPAD;
257 	sign = 0;
258 	if (type & SIGN) {
259 		if ((signed NUM_TYPE) num < 0) {
260 			sign = '-';
261 			num = - (signed NUM_TYPE) num;
262 			size--;
263 		} else if (type & PLUS) {
264 			sign = '+';
265 			size--;
266 		} else if (type & SPACE) {
267 			sign = ' ';
268 			size--;
269 		}
270 	}
271 	if (need_pfx) {
272 		size--;
273 		if (base == 16)
274 			size--;
275 	}
276 
277 	/* generate full string in tmp[], in reverse order */
278 	i = 0;
279 	if (num == 0)
280 		tmp[i++] = '0';
281 	/* Generic code, for any base:
282 	else do {
283 		tmp[i++] = (digits[do_div(num,base)] | locase);
284 	} while (num != 0);
285 	*/
286 	else if (base != 10) { /* 8 or 16 */
287 		int mask = base - 1;
288 		int shift = 3;
289 		if (base == 16) shift = 4;
290 		do {
291 			tmp[i++] = (digits[((unsigned char)num) & mask] | locase);
292 			num >>= shift;
293 		} while (num);
294 	} else { /* base 10 */
295 		i = put_dec(tmp, num) - tmp;
296 	}
297 
298 	/* printing 100 using %2d gives "100", not "00" */
299 	if (i > precision)
300 		precision = i;
301 	/* leading space padding */
302 	size -= precision;
303 	if (!(type & (ZEROPAD+LEFT)))
304 		while(--size >= 0)
305 			*buf++ = ' ';
306 	/* sign */
307 	if (sign)
308 		*buf++ = sign;
309 	/* "0x" / "0" prefix */
310 	if (need_pfx) {
311 		*buf++ = '0';
312 		if (base == 16)
313 			*buf++ = ('X' | locase);
314 	}
315 	/* zero or space padding */
316 	if (!(type & LEFT)) {
317 		char c = (type & ZEROPAD) ? '0' : ' ';
318 		while (--size >= 0)
319 			*buf++ = c;
320 	}
321 	/* hmm even more zero padding? */
322 	while (i <= --precision)
323 		*buf++ = '0';
324 	/* actual digits of result */
325 	while (--i >= 0)
326 		*buf++ = tmp[i];
327 	/* trailing space padding */
328 	while (--size >= 0)
329 		*buf++ = ' ';
330 	return buf;
331 }
332 
333 static char *string(char *buf, char *s, int field_width, int precision, int flags)
334 {
335 	int len, i;
336 
337 	if (s == 0)
338 		s = "<NULL>";
339 
340 	len = strnlen(s, precision);
341 
342 	if (!(flags & LEFT))
343 		while (len < field_width--)
344 			*buf++ = ' ';
345 	for (i = 0; i < len; ++i)
346 		*buf++ = *s++;
347 	while (len < field_width--)
348 		*buf++ = ' ';
349 	return buf;
350 }
351 
352 #ifdef CONFIG_CMD_NET
353 static char *mac_address_string(char *buf, u8 *addr, int field_width,
354 				int precision, int flags)
355 {
356 	char mac_addr[6 * 3]; /* (6 * 2 hex digits), 5 colons and trailing zero */
357 	char *p = mac_addr;
358 	int i;
359 
360 	for (i = 0; i < 6; i++) {
361 		p = pack_hex_byte(p, addr[i]);
362 		if (!(flags & SPECIAL) && i != 5)
363 			*p++ = ':';
364 	}
365 	*p = '\0';
366 
367 	return string(buf, mac_addr, field_width, precision, flags & ~SPECIAL);
368 }
369 
370 static char *ip6_addr_string(char *buf, u8 *addr, int field_width,
371 			 int precision, int flags)
372 {
373 	char ip6_addr[8 * 5]; /* (8 * 4 hex digits), 7 colons and trailing zero */
374 	char *p = ip6_addr;
375 	int i;
376 
377 	for (i = 0; i < 8; i++) {
378 		p = pack_hex_byte(p, addr[2 * i]);
379 		p = pack_hex_byte(p, addr[2 * i + 1]);
380 		if (!(flags & SPECIAL) && i != 7)
381 			*p++ = ':';
382 	}
383 	*p = '\0';
384 
385 	return string(buf, ip6_addr, field_width, precision, flags & ~SPECIAL);
386 }
387 
388 static char *ip4_addr_string(char *buf, u8 *addr, int field_width,
389 			 int precision, int flags)
390 {
391 	char ip4_addr[4 * 4]; /* (4 * 3 decimal digits), 3 dots and trailing zero */
392 	char temp[3];	/* hold each IP quad in reverse order */
393 	char *p = ip4_addr;
394 	int i, digits;
395 
396 	for (i = 0; i < 4; i++) {
397 		digits = put_dec_trunc(temp, addr[i]) - temp;
398 		/* reverse the digits in the quad */
399 		while (digits--)
400 			*p++ = temp[digits];
401 		if (i != 3)
402 			*p++ = '.';
403 	}
404 	*p = '\0';
405 
406 	return string(buf, ip4_addr, field_width, precision, flags & ~SPECIAL);
407 }
408 #endif
409 
410 /*
411  * Show a '%p' thing.  A kernel extension is that the '%p' is followed
412  * by an extra set of alphanumeric characters that are extended format
413  * specifiers.
414  *
415  * Right now we handle:
416  *
417  * - 'M' For a 6-byte MAC address, it prints the address in the
418  *       usual colon-separated hex notation
419  * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way (dot-separated
420  *       decimal for v4 and colon separated network-order 16 bit hex for v6)
421  * - 'i' [46] for 'raw' IPv4/IPv6 addresses, IPv6 omits the colons, IPv4 is
422  *       currently the same
423  *
424  * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
425  * function pointers are really function descriptors, which contain a
426  * pointer to the real address.
427  */
428 static char *pointer(const char *fmt, char *buf, void *ptr, int field_width, int precision, int flags)
429 {
430 	if (!ptr)
431 		return string(buf, "(null)", field_width, precision, flags);
432 
433 #ifdef CONFIG_CMD_NET
434 	switch (*fmt) {
435 	case 'm':
436 		flags |= SPECIAL;
437 		/* Fallthrough */
438 	case 'M':
439 		return mac_address_string(buf, ptr, field_width, precision, flags);
440 	case 'i':
441 		flags |= SPECIAL;
442 		/* Fallthrough */
443 	case 'I':
444 		if (fmt[1] == '6')
445 			return ip6_addr_string(buf, ptr, field_width, precision, flags);
446 		if (fmt[1] == '4')
447 			return ip4_addr_string(buf, ptr, field_width, precision, flags);
448 		flags &= ~SPECIAL;
449 		break;
450 	}
451 #endif
452 	flags |= SMALL;
453 	if (field_width == -1) {
454 		field_width = 2*sizeof(void *);
455 		flags |= ZEROPAD;
456 	}
457 	return number(buf, (unsigned long) ptr, 16, field_width, precision, flags);
458 }
459 
460 /**
461  * vsprintf - Format a string and place it in a buffer
462  * @buf: The buffer to place the result into
463  * @fmt: The format string to use
464  * @args: Arguments for the format string
465  *
466  * This function follows C99 vsprintf, but has some extensions:
467  * %pS output the name of a text symbol
468  * %pF output the name of a function pointer
469  * %pR output the address range in a struct resource
470  *
471  * The function returns the number of characters written
472  * into @buf.
473  *
474  * Call this function if you are already dealing with a va_list.
475  * You probably want sprintf() instead.
476  */
477 int vsprintf(char *buf, const char *fmt, va_list args)
478 {
479 	unsigned NUM_TYPE num;
480 	int base;
481 	char *str;
482 
483 	int flags;		/* flags to number() */
484 
485 	int field_width;	/* width of output field */
486 	int precision;		/* min. # of digits for integers; max
487 				   number of chars for from string */
488 	int qualifier;		/* 'h', 'l', or 'L' for integer fields */
489 				/* 'z' support added 23/7/1999 S.H.    */
490 				/* 'z' changed to 'Z' --davidm 1/25/99 */
491 				/* 't' added for ptrdiff_t */
492 
493 	str = buf;
494 
495 	for (; *fmt ; ++fmt) {
496 		if (*fmt != '%') {
497 			*str++ = *fmt;
498 			continue;
499 		}
500 
501 		/* process flags */
502 		flags = 0;
503 		repeat:
504 			++fmt;		/* this also skips first '%' */
505 			switch (*fmt) {
506 				case '-': flags |= LEFT; goto repeat;
507 				case '+': flags |= PLUS; goto repeat;
508 				case ' ': flags |= SPACE; goto repeat;
509 				case '#': flags |= SPECIAL; goto repeat;
510 				case '0': flags |= ZEROPAD; goto repeat;
511 			}
512 
513 		/* get field width */
514 		field_width = -1;
515 		if (is_digit(*fmt))
516 			field_width = skip_atoi(&fmt);
517 		else if (*fmt == '*') {
518 			++fmt;
519 			/* it's the next argument */
520 			field_width = va_arg(args, int);
521 			if (field_width < 0) {
522 				field_width = -field_width;
523 				flags |= LEFT;
524 			}
525 		}
526 
527 		/* get the precision */
528 		precision = -1;
529 		if (*fmt == '.') {
530 			++fmt;
531 			if (is_digit(*fmt))
532 				precision = skip_atoi(&fmt);
533 			else if (*fmt == '*') {
534 				++fmt;
535 				/* it's the next argument */
536 				precision = va_arg(args, int);
537 			}
538 			if (precision < 0)
539 				precision = 0;
540 		}
541 
542 		/* get the conversion qualifier */
543 		qualifier = -1;
544 		if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' ||
545 		    *fmt == 'Z' || *fmt == 'z' || *fmt == 't') {
546 			qualifier = *fmt;
547 			++fmt;
548 			if (qualifier == 'l' && *fmt == 'l') {
549 				qualifier = 'L';
550 				++fmt;
551 			}
552 		}
553 
554 		/* default base */
555 		base = 10;
556 
557 		switch (*fmt) {
558 		case 'c':
559 			if (!(flags & LEFT))
560 				while (--field_width > 0)
561 					*str++ = ' ';
562 			*str++ = (unsigned char) va_arg(args, int);
563 			while (--field_width > 0)
564 				*str++ = ' ';
565 			continue;
566 
567 		case 's':
568 			str = string(str, va_arg(args, char *), field_width, precision, flags);
569 			continue;
570 
571 		case 'p':
572 			str = pointer(fmt+1, str,
573 					va_arg(args, void *),
574 					field_width, precision, flags);
575 			/* Skip all alphanumeric pointer suffixes */
576 			while (isalnum(fmt[1]))
577 				fmt++;
578 			continue;
579 
580 		case 'n':
581 			if (qualifier == 'l') {
582 				long * ip = va_arg(args, long *);
583 				*ip = (str - buf);
584 			} else {
585 				int * ip = va_arg(args, int *);
586 				*ip = (str - buf);
587 			}
588 			continue;
589 
590 		case '%':
591 			*str++ = '%';
592 			continue;
593 
594 		/* integer number formats - set up the flags and "break" */
595 		case 'o':
596 			base = 8;
597 			break;
598 
599 		case 'x':
600 			flags |= SMALL;
601 		case 'X':
602 			base = 16;
603 			break;
604 
605 		case 'd':
606 		case 'i':
607 			flags |= SIGN;
608 		case 'u':
609 			break;
610 
611 		default:
612 			*str++ = '%';
613 			if (*fmt)
614 				*str++ = *fmt;
615 			else
616 				--fmt;
617 			continue;
618 		}
619 		if (qualifier == 'L')  /* "quad" for 64 bit variables */
620 			num = va_arg(args, unsigned long long);
621 		else if (qualifier == 'l') {
622 			num = va_arg(args, unsigned long);
623 			if (flags & SIGN)
624 				num = (signed long) num;
625 		} else if (qualifier == 'Z' || qualifier == 'z') {
626 			num = va_arg(args, size_t);
627 		} else if (qualifier == 't') {
628 			num = va_arg(args, ptrdiff_t);
629 		} else if (qualifier == 'h') {
630 			num = (unsigned short) va_arg(args, int);
631 			if (flags & SIGN)
632 				num = (signed short) num;
633 		} else {
634 			num = va_arg(args, unsigned int);
635 			if (flags & SIGN)
636 				num = (signed int) num;
637 		}
638 		str = number(str, num, base, field_width, precision, flags);
639 	}
640 	*str = '\0';
641 	return str-buf;
642 }
643 
644 /**
645  * sprintf - Format a string and place it in a buffer
646  * @buf: The buffer to place the result into
647  * @fmt: The format string to use
648  * @...: Arguments for the format string
649  *
650  * The function returns the number of characters written
651  * into @buf.
652  *
653  * See the vsprintf() documentation for format string extensions over C99.
654  */
655 int sprintf(char * buf, const char *fmt, ...)
656 {
657 	va_list args;
658 	int i;
659 
660 	va_start(args, fmt);
661 	i=vsprintf(buf,fmt,args);
662 	va_end(args);
663 	return i;
664 }
665 
666 void panic(const char *fmt, ...)
667 {
668 	va_list	args;
669 	va_start(args, fmt);
670 	vprintf(fmt, args);
671 	putc('\n');
672 	va_end(args);
673 #if defined (CONFIG_PANIC_HANG)
674 	hang();
675 #else
676 	udelay (100000);	/* allow messages to go out */
677 	do_reset (NULL, 0, 0, NULL);
678 #endif
679 }
680