libstand: Sync libstand's printf() with FreeBSD.
[dragonfly.git] / lib / libstand / printf.c
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
39  * $FreeBSD: src/lib/libstand/printf.c,v 1.14 2010/07/12 15:32:45 jkim Exp $
40  */
41
42 /*
43  * Standaloneified version of the FreeBSD kernel printf family.
44  */
45
46 #include <sys/types.h>
47 #include <sys/stdint.h>
48 #include <limits.h>
49 #include <string.h>
50 #include "stand.h"
51
52 /*
53  * Note that stdarg.h and the ANSI style va_start macro is used for both
54  * ANSI and traditional C compilers.
55  */
56 #include <stdarg.h>
57
58 struct snprintf_arg {
59         char    *buf;
60         size_t  remain;
61 };
62
63 #define MAXNBUF (sizeof(intmax_t) * CHAR_BIT + 1)
64
65 static char     *ksprintn (char *buf, uintmax_t num, int base, int *len, int upper);
66 static int      kvprintf(const char *, void (*)(int, void *), void *, int,
67                          va_list);
68 static void     putchar_wrapper(int, void *);
69 static void     snprintf_func(int, void *);
70
71 static void
72 putchar_wrapper(int ch, void *arg __unused)
73 {
74         putchar(ch);
75 }
76
77 int
78 printf(const char *fmt, ...)
79 {
80         va_list ap;
81         int retval;
82
83         va_start(ap, fmt);
84         retval = kvprintf(fmt, putchar_wrapper, NULL, 10, ap);
85         va_end(ap);
86         return retval;
87 }
88
89 void
90 vprintf(const char *fmt, va_list ap)
91 {
92
93         kvprintf(fmt, putchar_wrapper, NULL, 10, ap);
94 }
95
96 int
97 sprintf(char *buf, const char *cfmt, ...)
98 {
99         int retval;
100         va_list ap;
101
102         va_start(ap, cfmt);
103         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
104         buf[retval] = '\0';
105         va_end(ap);
106         return retval;
107 }
108
109 void
110 vsprintf(char *buf, const char *cfmt, va_list ap)
111 {
112         int     retval;
113         
114         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
115         buf[retval] = '\0';
116 }
117
118 int
119 snprintf(char *buf, size_t size, const char *cfmt, ...)
120 {
121         int retval;
122         va_list ap;
123
124         va_start(ap, cfmt);
125         retval = vsnprintf(buf, size, cfmt, ap);
126         __va_end(ap);
127         return(retval);
128 }
129
130 int
131 vsnprintf(char *buf, size_t size, const char *cfmt, va_list ap)
132 {
133         struct snprintf_arg info;
134         int retval;
135
136         info.buf = buf;
137         info.remain = size;
138         retval = kvprintf(cfmt, snprintf_func, &info, 10, ap);
139         if (info.remain >= 1)
140                 *info.buf++ = '\0';
141         return(retval);
142 }
143
144 static void
145 snprintf_func(int ch, void *arg)
146 {
147         struct snprintf_arg * const info = arg;
148
149         if (info->remain >= 2) {
150                 *info->buf++ = ch;
151                 info->remain--;
152         }
153 }
154
155 /*
156  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
157  * order; return an optional length and a pointer to the last character
158  * written in the buffer (i.e., the first character of the string).
159  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
160  */
161 static char *
162 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
163 {
164         char *p, c;
165
166         p = nbuf;
167         *p = '\0';
168         do {
169                 c = hex2ascii(num % base);
170                 *++p = upper ? toupper(c) : c;
171         } while (num /= base);
172         if (lenp)
173                 *lenp = p - nbuf;
174         return (p);
175 }
176
177 /*
178  * Scaled down version of printf(3).
179  *
180  * Two additional formats:
181  *
182  * The format %b is supported to decode error registers.
183  * Its usage is:
184  *
185  *      printf("reg=%b\n", regval, "<base><arg>*");
186  *
187  * where <base> is the output base expressed as a control character, e.g.
188  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
189  * the first of which gives the bit number to be inspected (origin 1), and
190  * the next characters (up to a control character, i.e. a character <= 32),
191  * give the name of the register.  Thus:
192  *
193  *      kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
194  *
195  * would produce output:
196  *
197  *      reg=3<BITTWO,BITONE>
198  *
199  * XXX:  %D  -- Hexdump, takes pointer and separator string:
200  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
201  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
202  */
203 static int
204 kvprintf(char const *fmt, void (*func)(int, void *), void *arg, int radix,
205          va_list ap)
206 {
207 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc, arg); else *d++ = cc; retval++; }
208         char nbuf[MAXNBUF];
209         char *d;
210         const char *p, *percent, *q;
211         u_char *up;
212         int ch, n;
213         uintmax_t num;
214         int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
215         int cflag, hflag, jflag, tflag, zflag;
216         int dwidth, upper;
217         char padc;
218         int stop = 0, retval = 0;
219
220         num = 0;
221         if (!func)
222                 d = (char *) arg;
223         else
224                 d = NULL;
225
226         if (fmt == NULL)
227                 fmt = "(fmt null)\n";
228
229         if (radix < 2 || radix > 36)
230                 radix = 10;
231
232         for (;;) {
233                 padc = ' ';
234                 width = 0;
235                 while ((ch = (u_char)*fmt++) != '%' || stop) {
236                         if (ch == '\0')
237                                 return (retval);
238                         PCHAR(ch);
239                 }
240                 percent = fmt - 1;
241                 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
242                 sign = 0; dot = 0; dwidth = 0; upper = 0;
243                 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
244 reswitch:       switch (ch = (u_char)*fmt++) {
245                 case '.':
246                         dot = 1;
247                         goto reswitch;
248                 case '#':
249                         sharpflag = 1;
250                         goto reswitch;
251                 case '+':
252                         sign = 1;
253                         goto reswitch;
254                 case '-':
255                         ladjust = 1;
256                         goto reswitch;
257                 case '%':
258                         PCHAR(ch);
259                         break;
260                 case '*':
261                         if (!dot) {
262                                 width = va_arg(ap, int);
263                                 if (width < 0) {
264                                         ladjust = !ladjust;
265                                         width = -width;
266                                 }
267                         } else {
268                                 dwidth = va_arg(ap, int);
269                         }
270                         goto reswitch;
271                 case '0':
272                         if (!dot) {
273                                 padc = '0';
274                                 goto reswitch;
275                         }
276                 case '1': case '2': case '3': case '4':
277                 case '5': case '6': case '7': case '8': case '9':
278                                 for (n = 0;; ++fmt) {
279                                         n = n * 10 + ch - '0';
280                                         ch = *fmt;
281                                         if (ch < '0' || ch > '9')
282                                                 break;
283                                 }
284                         if (dot)
285                                 dwidth = n;
286                         else
287                                 width = n;
288                         goto reswitch;
289                 case 'b':
290                         num = (u_int)va_arg(ap, int);
291                         p = va_arg(ap, char *);
292                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
293                                 PCHAR(*q--);
294
295                         if (num == 0)
296                                 break;
297
298                         for (tmp = 0; *p;) {
299                                 n = *p++;
300                                 if (num & (1 << (n - 1))) {
301                                         PCHAR(tmp ? ',' : '<');
302                                         for (; (n = *p) > ' '; ++p)
303                                                 PCHAR(n);
304                                         tmp = 1;
305                                 } else
306                                         for (; *p > ' '; ++p)
307                                                 continue;
308                         }
309                         if (tmp)
310                                 PCHAR('>');
311                         break;
312                 case 'c':
313                         PCHAR(va_arg(ap, int));
314                         break;
315                 case 'D':
316                         up = va_arg(ap, u_char *);
317                         p = va_arg(ap, char *);
318                         if (!width)
319                                 width = 16;
320                         while(width--) {
321                                 PCHAR(hex2ascii(*up >> 4));
322                                 PCHAR(hex2ascii(*up & 0x0f));
323                                 up++;
324                                 if (width)
325                                         for (q=p;*q;q++)
326                                                 PCHAR(*q);
327                         }
328                         break;
329                 case 'd':
330                 case 'i':
331                         base = 10;
332                         sign = 1;
333                         goto handle_sign;
334                 case 'h':
335                         if (hflag) {
336                                 hflag = 0;
337                                 cflag = 1;
338                         } else
339                                 hflag = 1;
340                         goto reswitch;
341                 case 'j':
342                         jflag = 1;
343                         goto reswitch;
344                 case 'l':
345                         if (lflag) {
346                                 lflag = 0;
347                                 qflag = 1;
348                         } else
349                                 lflag = 1;
350                         goto reswitch;
351                 case 'n':
352                         if (jflag)
353                                 *(va_arg(ap, intmax_t *)) = retval;
354                         else if (qflag)
355                                 *(va_arg(ap, quad_t *)) = retval;
356                         else if (lflag)
357                                 *(va_arg(ap, long *)) = retval;
358                         else if (zflag)
359                                 *(va_arg(ap, size_t *)) = retval;
360                         else if (hflag)
361                                 *(va_arg(ap, short *)) = retval;
362                         else if (cflag)
363                                 *(va_arg(ap, char *)) = retval;
364                         else
365                                 *(va_arg(ap, int *)) = retval;
366                         break;
367                 case 'o':
368                         base = 8;
369                         goto handle_nosign;
370                 case 'p':
371                         base = 16;
372                         sharpflag = (width == 0);
373                         sign = 0;
374                         num = (uintptr_t)va_arg(ap, void *);
375                         goto number;
376                 case 'q':
377                         qflag = 1;
378                         goto reswitch;
379                 case 'r':
380                         base = radix;
381                         if (sign)
382                                 goto handle_sign;
383                         goto handle_nosign;
384                 case 's':
385                         p = va_arg(ap, char *);
386                         if (p == NULL)
387                                 p = "(null)";
388                         if (!dot)
389                                 n = strlen (p);
390                         else
391                                 for (n = 0; n < dwidth && p[n]; n++)
392                                         continue;
393
394                         width -= n;
395
396                         if (!ladjust && width > 0)
397                                 while (width--)
398                                         PCHAR(padc);
399                         while (n--)
400                                 PCHAR(*p++);
401                         if (ladjust && width > 0)
402                                 while (width--)
403                                         PCHAR(padc);
404                         break;
405                 case 't':
406                         tflag = 1;
407                         goto reswitch;
408                 case 'u':
409                         base = 10;
410                         goto handle_nosign;
411                 case 'X':
412                         upper = 1;
413                 case 'x':
414                         base = 16;
415                         goto handle_nosign;
416                 case 'y':
417                         base = 16;
418                         sign = 1;
419                         goto handle_sign;
420                 case 'z':
421                         zflag = 1;
422                         goto reswitch;
423 handle_nosign:
424                         sign = 0;
425                         if (jflag)
426                                 num = va_arg(ap, uintmax_t);
427                         else if (qflag)
428                                 num = va_arg(ap, u_quad_t);
429                         else if (tflag)
430                                 num = va_arg(ap, ptrdiff_t);
431                         else if (lflag)
432                                 num = va_arg(ap, u_long);
433                         else if (zflag)
434                                 num = va_arg(ap, ssize_t);
435                         else if (hflag)
436                                 num = (u_short)va_arg(ap, int);
437                         else if (cflag)
438                                 num = (u_char)va_arg(ap, int);
439                         else
440                                 num = va_arg(ap, u_int);
441                         goto number;
442 handle_sign:
443                         if (jflag)
444                                 num = va_arg(ap, intmax_t);
445                         else if (qflag)
446                                 num = va_arg(ap, quad_t);
447                         else if (tflag)
448                                 num = va_arg(ap, ptrdiff_t);
449                         else if (lflag)
450                                 num = va_arg(ap, long);
451                         else if (zflag)
452                                 num = va_arg(ap, size_t);
453                         else if (hflag)
454                                 num = (short)va_arg(ap, int);
455                         else if (cflag)
456                                 num = (char)va_arg(ap, int);
457                         else
458                                 num = va_arg(ap, int);
459 number:
460                         if (sign && (intmax_t)num < 0) {
461                                 neg = 1;
462                                 num = -(intmax_t)num;
463                         }
464                         p = ksprintn(nbuf, num, base, &n, upper);
465                         tmp = 0;
466                         if (sharpflag && num != 0) {
467                                 if (base == 8)
468                                         tmp++;
469                                 else if (base == 16)
470                                         tmp += 2;
471                         }
472                         if (neg)
473                                 tmp++;
474
475                         if (!ladjust && padc == '0')
476                                 dwidth = width - tmp;
477                         width -= tmp + imax(dwidth, n);
478                         dwidth -= n;
479                         if (!ladjust)
480                                 while (width-- > 0)
481                                         PCHAR(' ');
482                         if (neg)
483                                 PCHAR('-');
484                         if (sharpflag && num != 0) {
485                                 if (base == 8) {
486                                         PCHAR('0');
487                                 } else if (base == 16) {
488                                         PCHAR('0');
489                                         PCHAR('x');
490                                 }
491                         }
492                         while (dwidth-- > 0)
493                                 PCHAR('0');
494
495                         while (*p)
496                                 PCHAR(*p--);
497
498                         if (ladjust)
499                                 while (width-- > 0)
500                                         PCHAR(' ');
501
502                         break;
503                 default:
504                         while (percent < fmt)
505                                 PCHAR(*percent++);
506                         /*
507                          * Since we ignore an formatting argument it is no
508                          * longer safe to obey the remaining formatting
509                          * arguments as the arguments will no longer match
510                          * the format specs.
511                          */
512                         stop = 1;
513                         break;
514                 }
515         }
516 #undef PCHAR
517 }