xref: /freebsd/stand/libsa/printf.c (revision d8a0fe102c0cfdfcd5b818f850eff09d8536c9bc)
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 
59 typedef void (kvprintf_fn_t)(int, void *);
60 
61 static char	*ksprintn (char *buf, uintmax_t num, int base, int *len, int upper);
62 static int	kvprintf(char const *fmt, kvprintf_fn_t *func, void *arg, int radix, va_list ap);
63 
64 static void
65 putchar_wrapper(int cc, void *arg)
66 {
67 
68 	putchar(cc);
69 }
70 
71 int
72 printf(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 
83 void
84 vprintf(const char *fmt, va_list ap)
85 {
86 
87 	kvprintf(fmt, putchar_wrapper, NULL, 10, ap);
88 }
89 
90 int
91 sprintf(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 
103 struct print_buf {
104 	char *buf;
105 	size_t size;
106 };
107 
108 static void
109 snprint_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 
124 int
125 snprintf(char *buf, size_t size, const char *cfmt, ...)
126 {
127 	int retval;
128 	va_list ap;
129 	struct print_buf arg;
130 
131 	arg.buf = buf;
132 	arg.size = size;
133 
134 	va_start(ap, cfmt);
135 	retval = kvprintf(cfmt, &snprint_func, &arg, 10, ap);
136 	va_end(ap);
137 
138 	if (arg.size >= 1)
139 		*(arg.buf)++ = 0;
140 	return retval;
141 }
142 
143 void
144 vsprintf(char *buf, const char *cfmt, va_list ap)
145 {
146 	int	retval;
147 
148 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
149 	buf[retval] = '\0';
150 }
151 
152 /*
153  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
154  * order; return an optional length and a pointer to the last character
155  * written in the buffer (i.e., the first character of the string).
156  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
157  */
158 static char *
159 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
160 {
161 	char *p, c;
162 
163 	p = nbuf;
164 	*p = '\0';
165 	do {
166 		c = hex2ascii(num % base);
167 		*++p = upper ? toupper(c) : c;
168 	} while (num /= base);
169 	if (lenp)
170 		*lenp = p - nbuf;
171 	return (p);
172 }
173 
174 /*
175  * Scaled down version of printf(3).
176  *
177  * Two additional formats:
178  *
179  * The format %b is supported to decode error registers.
180  * Its usage is:
181  *
182  *	printf("reg=%b\n", regval, "<base><arg>*");
183  *
184  * where <base> is the output base expressed as a control character, e.g.
185  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
186  * the first of which gives the bit number to be inspected (origin 1), and
187  * the next characters (up to a control character, i.e. a character <= 32),
188  * give the name of the register.  Thus:
189  *
190  *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
191  *
192  * would produce output:
193  *
194  *	reg=3<BITTWO,BITONE>
195  *
196  * XXX:  %D  -- Hexdump, takes pointer and separator string:
197  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
198  *		("%*D", len, ptr, " " -> XX XX XX XX ...
199  */
200 static int
201 kvprintf(char const *fmt, kvprintf_fn_t *func, void *arg, int radix, va_list ap)
202 {
203 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc, arg); else *d++ = cc; retval++; }
204 	char nbuf[MAXNBUF];
205 	char *d;
206 	const char *p, *percent, *q;
207 	uint16_t *S;
208 	u_char *up;
209 	int ch, n;
210 	uintmax_t num;
211 	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
212 	int cflag, hflag, jflag, tflag, zflag;
213 	int dwidth, upper;
214 	char padc;
215 	int stop = 0, retval = 0;
216 
217 	num = 0;
218 	if (!func)
219 		d = (char *) arg;
220 	else
221 		d = NULL;
222 
223 	if (fmt == NULL)
224 		fmt = "(fmt null)\n";
225 
226 	if (radix < 2 || radix > 36)
227 		radix = 10;
228 
229 	for (;;) {
230 		padc = ' ';
231 		width = 0;
232 		while ((ch = (u_char)*fmt++) != '%' || stop) {
233 			if (ch == '\0')
234 				return (retval);
235 			PCHAR(ch);
236 		}
237 		percent = fmt - 1;
238 		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
239 		sign = 0; dot = 0; dwidth = 0; upper = 0;
240 		cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
241 reswitch:	switch (ch = (u_char)*fmt++) {
242 		case '.':
243 			dot = 1;
244 			goto reswitch;
245 		case '#':
246 			sharpflag = 1;
247 			goto reswitch;
248 		case '+':
249 			sign = 1;
250 			goto reswitch;
251 		case '-':
252 			ladjust = 1;
253 			goto reswitch;
254 		case '%':
255 			PCHAR(ch);
256 			break;
257 		case '*':
258 			if (!dot) {
259 				width = va_arg(ap, int);
260 				if (width < 0) {
261 					ladjust = !ladjust;
262 					width = -width;
263 				}
264 			} else {
265 				dwidth = va_arg(ap, int);
266 			}
267 			goto reswitch;
268 		case '0':
269 			if (!dot) {
270 				padc = '0';
271 				goto reswitch;
272 			}
273 		case '1': case '2': case '3': case '4':
274 		case '5': case '6': case '7': case '8': case '9':
275 				for (n = 0;; ++fmt) {
276 					n = n * 10 + ch - '0';
277 					ch = *fmt;
278 					if (ch < '0' || ch > '9')
279 						break;
280 				}
281 			if (dot)
282 				dwidth = n;
283 			else
284 				width = n;
285 			goto reswitch;
286 		case 'b':
287 			num = (u_int)va_arg(ap, int);
288 			p = va_arg(ap, char *);
289 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
290 				PCHAR(*q--);
291 
292 			if (num == 0)
293 				break;
294 
295 			for (tmp = 0; *p;) {
296 				n = *p++;
297 				if (num & (1 << (n - 1))) {
298 					PCHAR(tmp ? ',' : '<');
299 					for (; (n = *p) > ' '; ++p)
300 						PCHAR(n);
301 					tmp = 1;
302 				} else
303 					for (; *p > ' '; ++p)
304 						continue;
305 			}
306 			if (tmp)
307 				PCHAR('>');
308 			break;
309 		case 'c':
310 			PCHAR(va_arg(ap, int));
311 			break;
312 		case 'D':
313 			up = va_arg(ap, u_char *);
314 			p = va_arg(ap, char *);
315 			if (!width)
316 				width = 16;
317 			while(width--) {
318 				PCHAR(hex2ascii(*up >> 4));
319 				PCHAR(hex2ascii(*up & 0x0f));
320 				up++;
321 				if (width)
322 					for (q=p;*q;q++)
323 						PCHAR(*q);
324 			}
325 			break;
326 		case 'd':
327 		case 'i':
328 			base = 10;
329 			sign = 1;
330 			goto handle_sign;
331 		case 'h':
332 			if (hflag) {
333 				hflag = 0;
334 				cflag = 1;
335 			} else
336 				hflag = 1;
337 			goto reswitch;
338 		case 'j':
339 			jflag = 1;
340 			goto reswitch;
341 		case 'l':
342 			if (lflag) {
343 				lflag = 0;
344 				qflag = 1;
345 			} else
346 				lflag = 1;
347 			goto reswitch;
348 		case 'n':
349 			if (jflag)
350 				*(va_arg(ap, intmax_t *)) = retval;
351 			else if (qflag)
352 				*(va_arg(ap, quad_t *)) = retval;
353 			else if (lflag)
354 				*(va_arg(ap, long *)) = retval;
355 			else if (zflag)
356 				*(va_arg(ap, size_t *)) = retval;
357 			else if (hflag)
358 				*(va_arg(ap, short *)) = retval;
359 			else if (cflag)
360 				*(va_arg(ap, char *)) = retval;
361 			else
362 				*(va_arg(ap, int *)) = retval;
363 			break;
364 		case 'o':
365 			base = 8;
366 			goto handle_nosign;
367 		case 'p':
368 			base = 16;
369 			sharpflag = (width == 0);
370 			sign = 0;
371 			num = (uintptr_t)va_arg(ap, void *);
372 			goto number;
373 		case 'q':
374 			qflag = 1;
375 			goto reswitch;
376 		case 'r':
377 			base = radix;
378 			if (sign)
379 				goto handle_sign;
380 			goto handle_nosign;
381 		case 's':
382 			p = va_arg(ap, char *);
383 			if (p == NULL)
384 				p = "(null)";
385 			if (!dot)
386 				n = strlen (p);
387 			else
388 				for (n = 0; n < dwidth && p[n]; n++)
389 					continue;
390 
391 			width -= n;
392 
393 			if (!ladjust && width > 0)
394 				while (width--)
395 					PCHAR(padc);
396 			while (n--)
397 				PCHAR(*p++);
398 			if (ladjust && width > 0)
399 				while (width--)
400 					PCHAR(padc);
401 			break;
402 		case 'S':	/* Assume console can cope with wide chars */
403 			for (S = va_arg(ap, uint16_t *); *S != 0; S++)
404 				PCHAR(*S);
405  			break;
406 		case 't':
407 			tflag = 1;
408 			goto reswitch;
409 		case 'u':
410 			base = 10;
411 			goto handle_nosign;
412 		case 'X':
413 			upper = 1;
414 		case 'x':
415 			base = 16;
416 			goto handle_nosign;
417 		case 'y':
418 			base = 16;
419 			sign = 1;
420 			goto handle_sign;
421 		case 'z':
422 			zflag = 1;
423 			goto reswitch;
424 handle_nosign:
425 			sign = 0;
426 			if (jflag)
427 				num = va_arg(ap, uintmax_t);
428 			else if (qflag)
429 				num = va_arg(ap, u_quad_t);
430 			else if (tflag)
431 				num = va_arg(ap, ptrdiff_t);
432 			else if (lflag)
433 				num = va_arg(ap, u_long);
434 			else if (zflag)
435 				num = va_arg(ap, size_t);
436 			else if (hflag)
437 				num = (u_short)va_arg(ap, int);
438 			else if (cflag)
439 				num = (u_char)va_arg(ap, int);
440 			else
441 				num = va_arg(ap, u_int);
442 			goto number;
443 handle_sign:
444 			if (jflag)
445 				num = va_arg(ap, intmax_t);
446 			else if (qflag)
447 				num = va_arg(ap, quad_t);
448 			else if (tflag)
449 				num = va_arg(ap, ptrdiff_t);
450 			else if (lflag)
451 				num = va_arg(ap, long);
452 			else if (zflag)
453 				num = va_arg(ap, ssize_t);
454 			else if (hflag)
455 				num = (short)va_arg(ap, int);
456 			else if (cflag)
457 				num = (char)va_arg(ap, int);
458 			else
459 				num = va_arg(ap, int);
460 number:
461 			if (sign && (intmax_t)num < 0) {
462 				neg = 1;
463 				num = -(intmax_t)num;
464 			}
465 			p = ksprintn(nbuf, num, base, &n, upper);
466 			tmp = 0;
467 			if (sharpflag && num != 0) {
468 				if (base == 8)
469 					tmp++;
470 				else if (base == 16)
471 					tmp += 2;
472 			}
473 			if (neg)
474 				tmp++;
475 
476 			if (!ladjust && padc == '0')
477 				dwidth = width - tmp;
478 			width -= tmp + imax(dwidth, n);
479 			dwidth -= n;
480 			if (!ladjust)
481 				while (width-- > 0)
482 					PCHAR(' ');
483 			if (neg)
484 				PCHAR('-');
485 			if (sharpflag && num != 0) {
486 				if (base == 8) {
487 					PCHAR('0');
488 				} else if (base == 16) {
489 					PCHAR('0');
490 					PCHAR('x');
491 				}
492 			}
493 			while (dwidth-- > 0)
494 				PCHAR('0');
495 
496 			while (*p)
497 				PCHAR(*p--);
498 
499 			if (ladjust)
500 				while (width-- > 0)
501 					PCHAR(' ');
502 
503 			break;
504 		default:
505 			while (percent < fmt)
506 				PCHAR(*percent++);
507 			/*
508 			 * Since we ignore a formatting argument it is no
509 			 * longer safe to obey the remaining formatting
510 			 * arguments as the arguments will no longer match
511 			 * the format specs.
512 			 */
513 			stop = 1;
514 			break;
515 		}
516 	}
517 #undef PCHAR
518 }
519