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