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