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