xref: /openbsd/lib/libc/stdio/vfprintf.c (revision eac10ac7)
1 /*	$OpenBSD: vfprintf.c,v 1.83 2024/07/14 13:31:50 millert Exp $	*/
2 /*-
3  * Copyright (c) 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Chris Torek.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Actual printf innards.
36  *
37  * This code is large and complicated...
38  */
39 
40 #include <sys/types.h>
41 #include <sys/mman.h>
42 
43 #include <errno.h>
44 #include <langinfo.h>
45 #include <limits.h>
46 #include <stdarg.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdint.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <syslog.h>
54 #include <wchar.h>
55 
56 #include "local.h"
57 #include "fvwrite.h"
58 
59 #define	PRINTF_PAGESIZE		(1 << _MAX_PAGE_SHIFT)
60 #define	PRINTF_PAGEMASK		(PRINTF_PAGESIZE - 1)
61 #define	PAGEROUND(x)		(((x) + (PRINTF_PAGEMASK)) & ~PRINTF_PAGEMASK)
62 
63 union arg {
64 	int			intarg;
65 	unsigned int		uintarg;
66 	long			longarg;
67 	unsigned long		ulongarg;
68 	long long		longlongarg;
69 	unsigned long long	ulonglongarg;
70 	ptrdiff_t		ptrdiffarg;
71 	size_t			sizearg;
72 	ssize_t			ssizearg;
73 	intmax_t		intmaxarg;
74 	uintmax_t		uintmaxarg;
75 	void			*pvoidarg;
76 	char			*pchararg;
77 	signed char		*pschararg;
78 	short			*pshortarg;
79 	int			*pintarg;
80 	long			*plongarg;
81 	long long		*plonglongarg;
82 	ptrdiff_t		*pptrdiffarg;
83 	ssize_t			*pssizearg;
84 	intmax_t		*pintmaxarg;
85 #ifdef FLOATING_POINT
86 	double			doublearg;
87 	long double		longdoublearg;
88 #endif
89 #ifdef PRINTF_WIDE_CHAR
90 	wint_t			wintarg;
91 	wchar_t			*pwchararg;
92 #endif
93 };
94 
95 static int __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
96     size_t *argtablesiz);
97 static int __grow_type_table(unsigned char **typetable, int *tablesize);
98 
99 /*
100  * Flush out all the vectors defined by the given uio,
101  * then reset it so that it can be reused.
102  */
103 static int
__sprint(FILE * fp,struct __suio * uio)104 __sprint(FILE *fp, struct __suio *uio)
105 {
106 	int err;
107 
108 	if (uio->uio_resid == 0) {
109 		uio->uio_iovcnt = 0;
110 		return (0);
111 	}
112 	err = __sfvwrite(fp, uio);
113 	uio->uio_resid = 0;
114 	uio->uio_iovcnt = 0;
115 	return (err);
116 }
117 
118 /*
119  * Helper function for `fprintf to unbuffered unix file': creates a
120  * temporary buffer.  We only work on write-only files; this avoids
121  * worries about ungetc buffers and so forth.
122  */
123 static int
__sbprintf(FILE * fp,const char * fmt,va_list ap)124 __sbprintf(FILE *fp, const char *fmt, va_list ap)
125 {
126 	int ret;
127 	FILE fake;
128 	struct __sfileext fakeext;
129 	unsigned char buf[BUFSIZ];
130 
131 	_FILEEXT_SETUP(&fake, &fakeext);
132 	/* copy the important variables */
133 	fake._flags = fp->_flags & ~__SNBF;
134 	fake._file = fp->_file;
135 	fake._cookie = fp->_cookie;
136 	fake._write = fp->_write;
137 
138 	/* set up the buffer */
139 	fake._bf._base = fake._p = buf;
140 	fake._bf._size = fake._w = sizeof(buf);
141 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
142 
143 	/* do the work, then copy any error status */
144 	ret = __vfprintf(&fake, fmt, ap);
145 	if (ret >= 0 && __sflush(&fake))
146 		ret = EOF;
147 	if (fake._flags & __SERR)
148 		fp->_flags |= __SERR;
149 	return (ret);
150 }
151 
152 #ifdef PRINTF_WIDE_CHAR
153 /*
154  * Convert a wide character string argument for the %ls format to a multibyte
155  * string representation. If not -1, prec specifies the maximum number of
156  * bytes to output, and also means that we can't assume that the wide char
157  * string is null-terminated.
158  */
159 static char *
__wcsconv(wchar_t * wcsarg,int prec,char ** convbufp,size_t * convbufsizp)160 __wcsconv(wchar_t *wcsarg, int prec, char **convbufp, size_t *convbufsizp)
161 {
162 	char *convbuf = *convbufp;
163 	size_t convbufsiz = *convbufsizp;
164 	mbstate_t mbs;
165 	char buf[MB_LEN_MAX];
166 	wchar_t *p;
167 	size_t clen, nbytes;
168 
169 	/* Allocate space for the maximum number of bytes we could output. */
170 	if (prec < 0) {
171 		memset(&mbs, 0, sizeof(mbs));
172 		p = wcsarg;
173 		nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
174 		if (nbytes == (size_t)-1)
175 			return (NULL);
176 	} else {
177 		/*
178 		 * Optimisation: if the output precision is small enough,
179 		 * just allocate enough memory for the maximum instead of
180 		 * scanning the string.
181 		 */
182 		if (prec < 128)
183 			nbytes = prec;
184 		else {
185 			nbytes = 0;
186 			p = wcsarg;
187 			memset(&mbs, 0, sizeof(mbs));
188 			for (;;) {
189 				clen = wcrtomb(buf, *p++, &mbs);
190 				if (clen == 0 || clen == (size_t)-1 ||
191 				    nbytes + clen > (size_t)prec)
192 					break;
193 				nbytes += clen;
194 			}
195 			if (clen == (size_t)-1)
196 				return (NULL);
197 		}
198 	}
199 	if (nbytes + 1 > convbufsiz) {
200 		if (convbuf != NULL)
201 			munmap(convbuf, convbufsiz);
202 		convbufsiz = PAGEROUND(nbytes + 1);
203 		convbuf = mmap(NULL, convbufsiz, PROT_WRITE|PROT_READ,
204 		    MAP_ANON|MAP_PRIVATE, -1, 0);
205 		if (convbuf == MAP_FAILED) {
206 			*convbufp = NULL;
207 			*convbufsizp = 0;
208 			return (NULL);
209 		}
210 		*convbufp = convbuf;
211 		*convbufsizp = convbufsiz;
212 	}
213 
214 	/* Fill the output buffer. */
215 	p = wcsarg;
216 	memset(&mbs, 0, sizeof(mbs));
217 	if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
218 	    nbytes, &mbs)) == (size_t)-1) {
219 		return (NULL);
220 	}
221 	convbuf[nbytes] = '\0';
222 	return (convbuf);
223 }
224 #endif
225 
226 #ifdef FLOATING_POINT
227 #include <float.h>
228 #include <locale.h>
229 #include <math.h>
230 #include "floatio.h"
231 #include "gdtoa.h"
232 
233 #define	DEFPREC		6
234 
235 static int exponent(char *, int, int);
236 #endif /* FLOATING_POINT */
237 
238 /*
239  * The size of the buffer we use as scratch space for integer
240  * conversions, among other things.  Technically, we would need the
241  * most space for base 10 conversions with thousands' grouping
242  * characters between each pair of digits.  100 bytes is a
243  * conservative overestimate even for a 128-bit uintmax_t.
244  */
245 #define BUF	100
246 
247 #define STATIC_ARG_TBL_SIZE 8	/* Size of static argument table. */
248 
249 
250 /*
251  * Macros for converting digits to letters and vice versa
252  */
253 #define	to_digit(c)	((c) - '0')
254 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
255 #define	to_char(n)	((n) + '0')
256 
257 /*
258  * Flags used during conversion.
259  */
260 #define	ALT		0x0001		/* alternate form */
261 #define	LADJUST		0x0004		/* left adjustment */
262 #define	LONGDBL		0x0008		/* long double */
263 #define	LONGINT		0x0010		/* long integer */
264 #define	LLONGINT	0x0020		/* long long integer */
265 #define	SHORTINT	0x0040		/* short integer */
266 #define	ZEROPAD		0x0080		/* zero (as opposed to blank) pad */
267 #define FPT		0x0100		/* Floating point number */
268 #define PTRINT		0x0200		/* (unsigned) ptrdiff_t */
269 #define SIZEINT		0x0400		/* (signed) size_t */
270 #define CHARINT		0x0800		/* 8 bit integer */
271 #define MAXINT		0x1000		/* largest integer size (intmax_t) */
272 
273 int
vfprintf(FILE * fp,const char * fmt0,__va_list ap)274 vfprintf(FILE *fp, const char *fmt0, __va_list ap)
275 {
276 	int ret;
277 
278 	FLOCKFILE(fp);
279 	ret = __vfprintf(fp, fmt0, ap);
280 	FUNLOCKFILE(fp);
281 	return (ret);
282 }
283 DEF_STRONG(vfprintf);
284 
285 int
__vfprintf(FILE * fp,const char * fmt0,__va_list ap)286 __vfprintf(FILE *fp, const char *fmt0, __va_list ap)
287 {
288 	char *fmt;		/* format string */
289 	int ch;			/* character from fmt */
290 	int n, n2;		/* handy integers (short term usage) */
291 	char *cp;		/* handy char pointer (short term usage) */
292 	struct __siov *iovp;	/* for PRINT macro */
293 	int flags;		/* flags as above */
294 	int ret;		/* return value accumulator */
295 	int width;		/* width from format (%8d), or 0 */
296 	int prec;		/* precision from format; <0 for N/A */
297 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
298 #ifdef FLOATING_POINT
299 	/*
300 	 * We can decompose the printed representation of floating
301 	 * point numbers into several parts, some of which may be empty:
302 	 *
303 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
304 	 *    A       B     ---C---      D       E   F
305 	 *
306 	 * A:	'sign' holds this value if present; '\0' otherwise
307 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
308 	 * C:	cp points to the string MMMNNN.  Leading and trailing
309 	 *	zeros are not in the string and must be added.
310 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
311 	 * F:	at least two digits for decimal, at least one digit for hex
312 	 */
313 	char *decimal_point = NULL;
314 	int signflag;		/* true if float is negative */
315 	union {			/* floating point arguments %[aAeEfFgG] */
316 		double dbl;
317 		long double ldbl;
318 	} fparg;
319 	int expt;		/* integer value of exponent */
320 	char expchar;		/* exponent character: [eEpP\0] */
321 	char *dtoaend;		/* pointer to end of converted digits */
322 	int expsize;		/* character count for expstr */
323 	int lead;		/* sig figs before decimal or group sep */
324 	int ndig;		/* actual number of digits returned by dtoa */
325 	char expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
326 	char *dtoaresult = NULL;
327 #endif
328 
329 	uintmax_t _umax;	/* integer arguments %[diouxX] */
330 	enum { OCT, DEC, HEX } base;	/* base for %[diouxX] conversion */
331 	int dprec;		/* a copy of prec if %[diouxX], 0 otherwise */
332 	int realsz;		/* field size expanded by dprec */
333 	int size;		/* size of converted field or string */
334 	const char *xdigs;	/* digits for %[xX] conversion */
335 #define NIOV 8
336 	struct __suio uio;	/* output information: summary */
337 	struct __siov iov[NIOV];/* ... and individual io vectors */
338 	char buf[BUF];		/* buffer with space for digits of uintmax_t */
339 	char ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
340 	union arg *argtable;	/* args, built due to positional arg */
341 	union arg statargtable[STATIC_ARG_TBL_SIZE];
342 	size_t argtablesiz;
343 	int nextarg;		/* 1-based argument index */
344 	va_list orgap;		/* original argument pointer */
345 #ifdef PRINTF_WIDE_CHAR
346 	char *convbuf;		/* buffer for wide to multi-byte conversion */
347 	size_t convbufsiz;	/* size of convbuf, for munmap() */
348 #endif
349 
350 	/*
351 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
352 	 * fields occur frequently, increase PADSIZE and make the initialisers
353 	 * below longer.
354 	 */
355 #define	PADSIZE	16		/* pad chunk size */
356 	static char blanks[PADSIZE] =
357 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
358 	static char zeroes[PADSIZE] =
359 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
360 
361 	static const char xdigs_lower[16] = "0123456789abcdef";
362 	static const char xdigs_upper[16] = "0123456789ABCDEF";
363 
364 	/*
365 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
366 	 */
367 #define	PRINT(ptr, len) do { \
368 	iovp->iov_base = (ptr); \
369 	iovp->iov_len = (len); \
370 	uio.uio_resid += (len); \
371 	iovp++; \
372 	if (++uio.uio_iovcnt >= NIOV) { \
373 		if (__sprint(fp, &uio)) \
374 			goto error; \
375 		iovp = iov; \
376 	} \
377 } while (0)
378 #define	PAD(howmany, with) do { \
379 	if ((n = (howmany)) > 0) { \
380 		while (n > PADSIZE) { \
381 			PRINT(with, PADSIZE); \
382 			n -= PADSIZE; \
383 		} \
384 		PRINT(with, n); \
385 	} \
386 } while (0)
387 #define	PRINTANDPAD(p, ep, len, with) do {	\
388 	n2 = (ep) - (p);       			\
389 	if (n2 > (len))				\
390 		n2 = (len);			\
391 	if (n2 > 0)				\
392 		PRINT((p), n2);			\
393 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
394 } while(0)
395 #define	FLUSH() do { \
396 	if (uio.uio_resid && __sprint(fp, &uio)) \
397 		goto error; \
398 	uio.uio_iovcnt = 0; \
399 	iovp = iov; \
400 } while (0)
401 
402 	/*
403 	 * To extend shorts properly, we need both signed and unsigned
404 	 * argument extraction methods.
405 	 */
406 #define	SARG() \
407 	((intmax_t)(flags&MAXINT ? GETARG(intmax_t) : \
408 	    flags&LLONGINT ? GETARG(long long) : \
409 	    flags&LONGINT ? GETARG(long) : \
410 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
411 	    flags&SIZEINT ? GETARG(ssize_t) : \
412 	    flags&SHORTINT ? (short)GETARG(int) : \
413 	    flags&CHARINT ? (signed char)GETARG(int) : \
414 	    GETARG(int)))
415 #define	UARG() \
416 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
417 	    flags&LLONGINT ? GETARG(unsigned long long) : \
418 	    flags&LONGINT ? GETARG(unsigned long) : \
419 	    flags&PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
420 	    flags&SIZEINT ? GETARG(size_t) : \
421 	    flags&SHORTINT ? (unsigned short)GETARG(int) : \
422 	    flags&CHARINT ? (unsigned char)GETARG(int) : \
423 	    GETARG(unsigned int)))
424 
425 	/*
426 	 * Append a digit to a value and check for overflow.
427 	 */
428 #define APPEND_DIGIT(val, dig) do { \
429 	if ((val) > INT_MAX / 10) \
430 		goto overflow; \
431 	(val) *= 10; \
432 	if ((val) > INT_MAX - to_digit((dig))) \
433 		goto overflow; \
434 	(val) += to_digit((dig)); \
435 } while (0)
436 
437 	 /*
438 	  * Get * arguments, including the form *nn$.  Preserve the nextarg
439 	  * that the argument can be gotten once the type is determined.
440 	  */
441 #define GETASTER(val) \
442 	n2 = 0; \
443 	cp = fmt; \
444 	while (is_digit(*cp)) { \
445 		APPEND_DIGIT(n2, *cp); \
446 		cp++; \
447 	} \
448 	if (*cp == '$') { \
449 		int hold = nextarg; \
450 		if (argtable == NULL) { \
451 			argtable = statargtable; \
452 			if (__find_arguments(fmt0, orgap, &argtable, \
453 			    &argtablesiz) == -1) { \
454 				ret = -1; \
455 				goto error; \
456 			} \
457 		} \
458 		nextarg = n2; \
459 		val = GETARG(int); \
460 		nextarg = hold; \
461 		fmt = ++cp; \
462 	} else { \
463 		val = GETARG(int); \
464 	}
465 
466 /*
467 * Get the argument indexed by nextarg.   If the argument table is
468 * built, use it to get the argument.  If its not, get the next
469 * argument (and arguments must be gotten sequentially).
470 */
471 #define GETARG(type) \
472 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
473 		(nextarg++, va_arg(ap, type)))
474 
475 	_SET_ORIENTATION(fp, -1);
476 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
477 	if (cantwrite(fp))
478 		return (EOF);
479 
480 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
481 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
482 	    fp->_file >= 0)
483 		return (__sbprintf(fp, fmt0, ap));
484 
485 	fmt = (char *)fmt0;
486 	argtable = NULL;
487 	nextarg = 1;
488 	va_copy(orgap, ap);
489 	uio.uio_iov = iovp = iov;
490 	uio.uio_resid = 0;
491 	uio.uio_iovcnt = 0;
492 	ret = 0;
493 #ifdef PRINTF_WIDE_CHAR
494 	convbuf = NULL;
495 	convbufsiz = 0;
496 #endif
497 
498 	/*
499 	 * Scan the format for conversions (`%' character).
500 	 */
501 	for (;;) {
502 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
503 			continue;
504 
505 		if (fmt != cp) {
506 			ptrdiff_t m = fmt - cp;
507 			if (m < 0 || m > INT_MAX - ret)
508 				goto overflow;
509 			PRINT(cp, m);
510 			ret += m;
511 		}
512 		if (ch == '\0')
513 			goto done;
514 		fmt++;		/* skip over '%' */
515 
516 		flags = 0;
517 		dprec = 0;
518 		width = 0;
519 		prec = -1;
520 		sign = '\0';
521 		ox[1] = '\0';
522 
523 rflag:		ch = *fmt++;
524 reswitch:	switch (ch) {
525 		case ' ':
526 			/*
527 			 * ``If the space and + flags both appear, the space
528 			 * flag will be ignored.''
529 			 *	-- ANSI X3J11
530 			 */
531 			if (!sign)
532 				sign = ' ';
533 			goto rflag;
534 		case '#':
535 			flags |= ALT;
536 			goto rflag;
537 		case '\'':
538 			/* grouping not implemented */
539 			goto rflag;
540 		case '*':
541 			/*
542 			 * ``A negative field width argument is taken as a
543 			 * - flag followed by a positive field width.''
544 			 *	-- ANSI X3J11
545 			 * They don't exclude field widths read from args.
546 			 */
547 			GETASTER(width);
548 			if (width >= 0)
549 				goto rflag;
550 			if (width == INT_MIN)
551 				goto overflow;
552 			width = -width;
553 			/* FALLTHROUGH */
554 		case '-':
555 			flags |= LADJUST;
556 			goto rflag;
557 		case '+':
558 			sign = '+';
559 			goto rflag;
560 		case '.':
561 			if ((ch = *fmt++) == '*') {
562 				GETASTER(n);
563 				prec = n < 0 ? -1 : n;
564 				goto rflag;
565 			}
566 			n = 0;
567 			while (is_digit(ch)) {
568 				APPEND_DIGIT(n, ch);
569 				ch = *fmt++;
570 			}
571 			if (ch == '$') {
572 				nextarg = n;
573 				if (argtable == NULL) {
574 					argtable = statargtable;
575 					if (__find_arguments(fmt0, orgap,
576 					    &argtable, &argtablesiz) == -1) {
577 						ret = -1;
578 						goto error;
579 					}
580 				}
581 				goto rflag;
582 			}
583 			prec = n;
584 			goto reswitch;
585 		case '0':
586 			/*
587 			 * ``Note that 0 is taken as a flag, not as the
588 			 * beginning of a field width.''
589 			 *	-- ANSI X3J11
590 			 */
591 			flags |= ZEROPAD;
592 			goto rflag;
593 		case '1': case '2': case '3': case '4':
594 		case '5': case '6': case '7': case '8': case '9':
595 			n = 0;
596 			do {
597 				APPEND_DIGIT(n, ch);
598 				ch = *fmt++;
599 			} while (is_digit(ch));
600 			if (ch == '$') {
601 				nextarg = n;
602 				if (argtable == NULL) {
603 					argtable = statargtable;
604 					if (__find_arguments(fmt0, orgap,
605 					    &argtable, &argtablesiz) == -1) {
606 						ret = -1;
607 						goto error;
608 					}
609 				}
610 				goto rflag;
611 			}
612 			width = n;
613 			goto reswitch;
614 #ifdef FLOATING_POINT
615 		case 'L':
616 			flags |= LONGDBL;
617 			goto rflag;
618 #endif
619 		case 'h':
620 			if (*fmt == 'h') {
621 				fmt++;
622 				flags |= CHARINT;
623 			} else {
624 				flags |= SHORTINT;
625 			}
626 			goto rflag;
627 		case 'j':
628 			flags |= MAXINT;
629 			goto rflag;
630 		case 'l':
631 			if (*fmt == 'l') {
632 				fmt++;
633 				flags |= LLONGINT;
634 			} else {
635 				flags |= LONGINT;
636 			}
637 			goto rflag;
638 		case 'q':
639 			flags |= LLONGINT;
640 			goto rflag;
641 		case 't':
642 			flags |= PTRINT;
643 			goto rflag;
644 		case 'z':
645 			flags |= SIZEINT;
646 			goto rflag;
647 		case 'c':
648 #ifdef PRINTF_WIDE_CHAR
649 			if (flags & LONGINT) {
650 				mbstate_t mbs;
651 				size_t mbseqlen;
652 
653 				memset(&mbs, 0, sizeof(mbs));
654 				mbseqlen = wcrtomb(buf,
655 				    (wchar_t)GETARG(wint_t), &mbs);
656 				if (mbseqlen == (size_t)-1) {
657 					ret = -1;
658 					goto error;
659 				}
660 				cp = buf;
661 				size = (int)mbseqlen;
662 			} else {
663 #endif
664 				*(cp = buf) = GETARG(int);
665 				size = 1;
666 #ifdef PRINTF_WIDE_CHAR
667 			}
668 #endif
669 			sign = '\0';
670 			break;
671 		case 'D':
672 			flags |= LONGINT;
673 			/*FALLTHROUGH*/
674 		case 'd':
675 		case 'i':
676 			_umax = SARG();
677 			if ((intmax_t)_umax < 0) {
678 				_umax = -_umax;
679 				sign = '-';
680 			}
681 			base = DEC;
682 			goto number;
683 #ifdef FLOATING_POINT
684 		case 'a':
685 		case 'A':
686 			if (ch == 'a') {
687 				ox[1] = 'x';
688 				xdigs = xdigs_lower;
689 				expchar = 'p';
690 			} else {
691 				ox[1] = 'X';
692 				xdigs = xdigs_upper;
693 				expchar = 'P';
694 			}
695 			if (prec >= 0)
696 				prec++;
697 			if (dtoaresult)
698 				__freedtoa(dtoaresult);
699 			if (flags & LONGDBL) {
700 				fparg.ldbl = GETARG(long double);
701 				dtoaresult = cp =
702 				    __hldtoa(fparg.ldbl, xdigs, prec,
703 				    &expt, &signflag, &dtoaend);
704 				if (dtoaresult == NULL) {
705 					errno = ENOMEM;
706 					goto error;
707 				}
708 			} else {
709 				fparg.dbl = GETARG(double);
710 				dtoaresult = cp =
711 				    __hdtoa(fparg.dbl, xdigs, prec,
712 				    &expt, &signflag, &dtoaend);
713 				if (dtoaresult == NULL) {
714 					errno = ENOMEM;
715 					goto error;
716 				}
717 			}
718 			if (prec < 0)
719 				prec = dtoaend - cp;
720 			if (expt == INT_MAX)
721 				ox[1] = '\0';
722 			goto fp_common;
723 		case 'e':
724 		case 'E':
725 			expchar = ch;
726 			if (prec < 0)	/* account for digit before decpt */
727 				prec = DEFPREC + 1;
728 			else
729 				prec++;
730 			goto fp_begin;
731 		case 'f':
732 		case 'F':
733 			expchar = '\0';
734 			goto fp_begin;
735 		case 'g':
736 		case 'G':
737 			expchar = ch - ('g' - 'e');
738  			if (prec == 0)
739  				prec = 1;
740 fp_begin:
741 			if (prec < 0)
742 				prec = DEFPREC;
743 			if (dtoaresult)
744 				__freedtoa(dtoaresult);
745 			if (flags & LONGDBL) {
746 				fparg.ldbl = GETARG(long double);
747 				dtoaresult = cp =
748 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
749 				    &expt, &signflag, &dtoaend);
750 				if (dtoaresult == NULL) {
751 					errno = ENOMEM;
752 					goto error;
753 				}
754 			} else {
755 				fparg.dbl = GETARG(double);
756 				dtoaresult = cp =
757 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
758 				    &expt, &signflag, &dtoaend);
759 				if (dtoaresult == NULL) {
760 					errno = ENOMEM;
761 					goto error;
762 				}
763 				if (expt == 9999)
764 					expt = INT_MAX;
765  			}
766 fp_common:
767 			if (signflag)
768 				sign = '-';
769 			if (expt == INT_MAX) {	/* inf or nan */
770 				if (*cp == 'N')
771 					cp = (ch >= 'a') ? "nan" : "NAN";
772 				else
773 					cp = (ch >= 'a') ? "inf" : "INF";
774  				size = 3;
775 				flags &= ~ZEROPAD;
776  				break;
777  			}
778 			flags |= FPT;
779 			ndig = dtoaend - cp;
780  			if (ch == 'g' || ch == 'G') {
781 				if (expt > -4 && expt <= prec) {
782 					/* Make %[gG] smell like %[fF] */
783 					expchar = '\0';
784 					if (flags & ALT)
785 						prec -= expt;
786 					else
787 						prec = ndig - expt;
788 					if (prec < 0)
789 						prec = 0;
790 				} else {
791 					/*
792 					 * Make %[gG] smell like %[eE], but
793 					 * trim trailing zeroes if no # flag.
794 					 */
795 					if (!(flags & ALT))
796 						prec = ndig;
797 				}
798  			}
799 			if (expchar) {
800 				expsize = exponent(expstr, expt - 1, expchar);
801 				size = expsize + prec;
802 				if (prec > 1 || flags & ALT)
803  					++size;
804 			} else {
805 				/* space for digits before decimal point */
806 				if (expt > 0)
807 					size = expt;
808 				else	/* "0" */
809 					size = 1;
810 				/* space for decimal pt and following digits */
811 				if (prec || flags & ALT)
812 					size += prec + 1;
813 				lead = expt;
814 			}
815 			break;
816 #endif /* FLOATING_POINT */
817 		case 'n': {
818 			static const char n_msg[] = ": *printf used %n, aborting: ";
819 			char buf[1024], *p;
820 
821 			/* <10> is LOG_CRIT */
822 			strlcpy(buf, "<10>", sizeof buf);
823 
824 			/* Make sure progname does not fill the whole buffer */
825 			strlcat(buf, __progname, sizeof(buf) - sizeof n_msg);
826 			strlcat(buf, n_msg, sizeof buf);
827 			strlcat(buf, fmt0, sizeof buf);
828 			if ((p = strchr(buf, '\n')))
829 				*p = '\0';
830 			sendsyslog(buf, strlen(buf), LOG_CONS);
831 			abort();
832 			break;
833 			}
834 		case 'O':
835 			flags |= LONGINT;
836 			/*FALLTHROUGH*/
837 		case 'o':
838 			_umax = UARG();
839 			base = OCT;
840 			goto nosign;
841 		case 'p':
842 			/*
843 			 * ``The argument shall be a pointer to void.  The
844 			 * value of the pointer is converted to a sequence
845 			 * of printable characters, in an implementation-
846 			 * defined manner.''
847 			 *	-- ANSI X3J11
848 			 */
849 			_umax = (u_long)GETARG(void *);
850 			base = HEX;
851 			xdigs = xdigs_lower;
852 			ox[1] = 'x';
853 			goto nosign;
854 		case 's': {
855 			size_t len;
856 
857 #ifdef PRINTF_WIDE_CHAR
858 			if (flags & LONGINT) {
859 				wchar_t *wcp;
860 
861 				if ((wcp = GETARG(wchar_t *)) == NULL) {
862 					struct syslog_data sdata = SYSLOG_DATA_INIT;
863 					int save_errno = errno;
864 
865 					syslog_r(LOG_CRIT | LOG_CONS, &sdata,
866 					    "vfprintf %%ls NULL in \"%s\"", fmt0);
867 					errno = save_errno;
868 
869 					cp = "(null)";
870 				} else {
871 					cp = __wcsconv(wcp, prec, &convbuf,
872 					    &convbufsiz);
873 					if (cp == NULL) {
874 						ret = -1;
875 						goto error;
876 					}
877 				}
878 			} else
879 #endif /* PRINTF_WIDE_CHAR */
880 
881 			if ((cp = GETARG(char *)) == NULL) {
882 				struct syslog_data sdata = SYSLOG_DATA_INIT;
883 				int save_errno = errno;
884 
885 				syslog_r(LOG_CRIT | LOG_CONS, &sdata,
886 				    "vfprintf %%s NULL in \"%s\"", fmt0);
887 				errno = save_errno;
888 
889 				cp = "(null)";
890 			}
891 			len = prec >= 0 ? strnlen(cp, prec) : strlen(cp);
892 			if (len > INT_MAX)
893 				goto overflow;
894 			size = (int)len;
895 			sign = '\0';
896 			}
897 			break;
898 		case 'U':
899 			flags |= LONGINT;
900 			/*FALLTHROUGH*/
901 		case 'u':
902 			_umax = UARG();
903 			base = DEC;
904 			goto nosign;
905 		case 'X':
906 			xdigs = xdigs_upper;
907 			goto hex;
908 		case 'x':
909 			xdigs = xdigs_lower;
910 hex:			_umax = UARG();
911 			base = HEX;
912 			/* leading 0x/X only if non-zero */
913 			if (flags & ALT && _umax != 0)
914 				ox[1] = ch;
915 
916 			/* unsigned conversions */
917 nosign:			sign = '\0';
918 			/*
919 			 * ``... diouXx conversions ... if a precision is
920 			 * specified, the 0 flag will be ignored.''
921 			 *	-- ANSI X3J11
922 			 */
923 number:			if ((dprec = prec) >= 0)
924 				flags &= ~ZEROPAD;
925 
926 			/*
927 			 * ``The result of converting a zero value with an
928 			 * explicit precision of zero is no characters.''
929 			 *	-- ANSI X3J11
930 			 */
931 			cp = buf + BUF;
932 			if (_umax != 0 || prec != 0) {
933 				/*
934 				 * Unsigned mod is hard, and unsigned mod
935 				 * by a constant is easier than that by
936 				 * a variable; hence this switch.
937 				 */
938 				switch (base) {
939 				case OCT:
940 					do {
941 						*--cp = to_char(_umax & 7);
942 						_umax >>= 3;
943 					} while (_umax);
944 					/* handle octal leading 0 */
945 					if (flags & ALT && *cp != '0')
946 						*--cp = '0';
947 					break;
948 
949 				case DEC:
950 					/* many numbers are 1 digit */
951 					while (_umax >= 10) {
952 						*--cp = to_char(_umax % 10);
953 						_umax /= 10;
954 					}
955 					*--cp = to_char(_umax);
956 					break;
957 
958 				case HEX:
959 					do {
960 						*--cp = xdigs[_umax & 15];
961 						_umax >>= 4;
962 					} while (_umax);
963 					break;
964 
965 				default:
966 					cp = "bug in vfprintf: bad base";
967 					size = strlen(cp);
968 					goto skipsize;
969 				}
970 			}
971 			size = buf + BUF - cp;
972 			if (size > BUF)	/* should never happen */
973 				abort();
974 		skipsize:
975 			break;
976 		default:	/* "%?" prints ?, unless ? is NUL */
977 			if (ch == '\0')
978 				goto done;
979 			/* pretend it was %c with argument ch */
980 			cp = buf;
981 			*cp = ch;
982 			size = 1;
983 			sign = '\0';
984 			break;
985 		}
986 
987 		/*
988 		 * All reasonable formats wind up here.  At this point, `cp'
989 		 * points to a string which (if not flags&LADJUST) should be
990 		 * padded out to `width' places.  If flags&ZEROPAD, it should
991 		 * first be prefixed by any sign or other prefix; otherwise,
992 		 * it should be blank padded before the prefix is emitted.
993 		 * After any left-hand padding and prefixing, emit zeroes
994 		 * required by a decimal %[diouxX] precision, then print the
995 		 * string proper, then emit zeroes required by any leftover
996 		 * floating precision; finally, if LADJUST, pad with blanks.
997 		 *
998 		 * Compute actual size, so we know how much to pad.
999 		 * size excludes decimal prec; realsz includes it.
1000 		 */
1001 		realsz = dprec > size ? dprec : size;
1002 		if (sign)
1003 			realsz++;
1004 		if (ox[1])
1005 			realsz+= 2;
1006 
1007 		/* right-adjusting blank padding */
1008 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1009 			PAD(width - realsz, blanks);
1010 
1011 		/* prefix */
1012 		if (sign)
1013 			PRINT(&sign, 1);
1014 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1015 			ox[0] = '0';
1016 			PRINT(ox, 2);
1017 		}
1018 
1019 		/* right-adjusting zero padding */
1020 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1021 			PAD(width - realsz, zeroes);
1022 
1023 		/* leading zeroes from decimal precision */
1024 		PAD(dprec - size, zeroes);
1025 
1026 		/* the string or number proper */
1027 #ifdef FLOATING_POINT
1028 		if ((flags & FPT) == 0) {
1029 			PRINT(cp, size);
1030 		} else {	/* glue together f_p fragments */
1031 			if (decimal_point == NULL)
1032 				decimal_point = nl_langinfo(RADIXCHAR);
1033 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1034 				if (expt <= 0) {
1035 					PRINT(zeroes, 1);
1036 					if (prec || flags & ALT)
1037 						PRINT(decimal_point, 1);
1038 					PAD(-expt, zeroes);
1039 					/* already handled initial 0's */
1040 					prec += expt;
1041  				} else {
1042 					PRINTANDPAD(cp, dtoaend, lead, zeroes);
1043 					cp += lead;
1044 					if (prec || flags & ALT)
1045 						PRINT(decimal_point, 1);
1046 				}
1047 				PRINTANDPAD(cp, dtoaend, prec, zeroes);
1048 			} else {	/* %[eE] or sufficiently long %[gG] */
1049 				if (prec > 1 || flags & ALT) {
1050 					buf[0] = *cp++;
1051 					buf[1] = *decimal_point;
1052 					PRINT(buf, 2);
1053 					PRINT(cp, ndig-1);
1054 					PAD(prec - ndig, zeroes);
1055 				} else { /* XeYYY */
1056 					PRINT(cp, 1);
1057 				}
1058 				PRINT(expstr, expsize);
1059 			}
1060 		}
1061 #else
1062 		PRINT(cp, size);
1063 #endif
1064 		/* left-adjusting padding (always blank) */
1065 		if (flags & LADJUST)
1066 			PAD(width - realsz, blanks);
1067 
1068 		/* finally, adjust ret */
1069 		if (width < realsz)
1070 			width = realsz;
1071 		if (width > INT_MAX - ret)
1072 			goto overflow;
1073 		ret += width;
1074 
1075 		FLUSH();	/* copy out the I/O vectors */
1076 	}
1077 done:
1078 	FLUSH();
1079 error:
1080 	va_end(orgap);
1081 	if (__sferror(fp))
1082 		ret = -1;
1083 	goto finish;
1084 
1085 overflow:
1086 	errno = EOVERFLOW;
1087 	ret = -1;
1088 
1089 finish:
1090 #ifdef PRINTF_WIDE_CHAR
1091 	if (convbuf != NULL)
1092 		munmap(convbuf, convbufsiz);
1093 #endif
1094 #ifdef FLOATING_POINT
1095 	if (dtoaresult)
1096 		__freedtoa(dtoaresult);
1097 #endif
1098 	if (argtable != NULL && argtable != statargtable) {
1099 		munmap(argtable, argtablesiz);
1100 		argtable = NULL;
1101 	}
1102 	return (ret);
1103 }
1104 
1105 /*
1106  * Type ids for argument type table.
1107  */
1108 #define T_UNUSED	0
1109 #define T_SHORT		1
1110 #define T_U_SHORT	2
1111 #define TP_SHORT	3
1112 #define T_INT		4
1113 #define T_U_INT		5
1114 #define TP_INT		6
1115 #define T_LONG		7
1116 #define T_U_LONG	8
1117 #define TP_LONG		9
1118 #define T_LLONG		10
1119 #define T_U_LLONG	11
1120 #define TP_LLONG	12
1121 #define T_DOUBLE	13
1122 #define T_LONG_DOUBLE	14
1123 #define TP_CHAR		15
1124 #define TP_VOID		16
1125 #define T_PTRINT	17
1126 #define TP_PTRINT	18
1127 #define T_SIZEINT	19
1128 #define T_SSIZEINT	20
1129 #define TP_SSIZEINT	21
1130 #define T_MAXINT	22
1131 #define T_MAXUINT	23
1132 #define TP_MAXINT	24
1133 #define T_CHAR		25
1134 #define T_U_CHAR	26
1135 #define T_WINT		27
1136 #define TP_WCHAR	28
1137 
1138 /*
1139  * Find all arguments when a positional parameter is encountered.  Returns a
1140  * table, indexed by argument number, of pointers to each arguments.  The
1141  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1142  * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1143  * used since we are attempting to make snprintf thread safe, and alloca is
1144  * problematic since we have nested functions..)
1145  */
1146 static int
__find_arguments(const char * fmt0,va_list ap,union arg ** argtable,size_t * argtablesiz)1147 __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
1148     size_t *argtablesiz)
1149 {
1150 	char *fmt;		/* format string */
1151 	int ch;			/* character from fmt */
1152 	int n, n2;		/* handy integer (short term usage) */
1153 	char *cp;		/* handy char pointer (short term usage) */
1154 	int flags;		/* flags as above */
1155 	unsigned char *typetable; /* table of types */
1156 	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1157 	int tablesize;		/* current size of type table */
1158 	int tablemax;		/* largest used index in table */
1159 	int nextarg;		/* 1-based argument index */
1160 	int ret = 0;		/* return value */
1161 
1162 	/*
1163 	 * Add an argument type to the table, expanding if necessary.
1164 	 */
1165 #define ADDTYPE(type) \
1166 	((nextarg >= tablesize) ? \
1167 		__grow_type_table(&typetable, &tablesize) : 0, \
1168 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1169 	typetable[nextarg++] = type)
1170 
1171 #define	ADDSARG() \
1172         ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
1173 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1174 	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
1175 	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1176 	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
1177 	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
1178 	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
1179 
1180 #define	ADDUARG() \
1181         ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
1182 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1183 	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
1184 	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1185 	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
1186 	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
1187 	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
1188 
1189 	/*
1190 	 * Add * arguments to the type array.
1191 	 */
1192 #define ADDASTER() \
1193 	n2 = 0; \
1194 	cp = fmt; \
1195 	while (is_digit(*cp)) { \
1196 		APPEND_DIGIT(n2, *cp); \
1197 		cp++; \
1198 	} \
1199 	if (*cp == '$') { \
1200 		int hold = nextarg; \
1201 		nextarg = n2; \
1202 		ADDTYPE(T_INT); \
1203 		nextarg = hold; \
1204 		fmt = ++cp; \
1205 	} else { \
1206 		ADDTYPE(T_INT); \
1207 	}
1208 	fmt = (char *)fmt0;
1209 	typetable = stattypetable;
1210 	tablesize = STATIC_ARG_TBL_SIZE;
1211 	tablemax = 0;
1212 	nextarg = 1;
1213 	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1214 
1215 	/*
1216 	 * Scan the format for conversions (`%' character).
1217 	 */
1218 	for (;;) {
1219 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1220 			continue;
1221 		if (ch == '\0')
1222 			goto done;
1223 		fmt++;		/* skip over '%' */
1224 
1225 		flags = 0;
1226 
1227 rflag:		ch = *fmt++;
1228 reswitch:	switch (ch) {
1229 		case ' ':
1230 		case '#':
1231 		case '\'':
1232 			goto rflag;
1233 		case '*':
1234 			ADDASTER();
1235 			goto rflag;
1236 		case '-':
1237 		case '+':
1238 			goto rflag;
1239 		case '.':
1240 			if ((ch = *fmt++) == '*') {
1241 				ADDASTER();
1242 				goto rflag;
1243 			}
1244 			while (is_digit(ch)) {
1245 				ch = *fmt++;
1246 			}
1247 			goto reswitch;
1248 		case '0':
1249 			goto rflag;
1250 		case '1': case '2': case '3': case '4':
1251 		case '5': case '6': case '7': case '8': case '9':
1252 			n = 0;
1253 			do {
1254 				APPEND_DIGIT(n ,ch);
1255 				ch = *fmt++;
1256 			} while (is_digit(ch));
1257 			if (ch == '$') {
1258 				nextarg = n;
1259 				goto rflag;
1260 			}
1261 			goto reswitch;
1262 #ifdef FLOATING_POINT
1263 		case 'L':
1264 			flags |= LONGDBL;
1265 			goto rflag;
1266 #endif
1267 		case 'h':
1268 			if (*fmt == 'h') {
1269 				fmt++;
1270 				flags |= CHARINT;
1271 			} else {
1272 				flags |= SHORTINT;
1273 			}
1274 			goto rflag;
1275 		case 'j':
1276 			flags |= MAXINT;
1277 			goto rflag;
1278 		case 'l':
1279 			if (*fmt == 'l') {
1280 				fmt++;
1281 				flags |= LLONGINT;
1282 			} else {
1283 				flags |= LONGINT;
1284 			}
1285 			goto rflag;
1286 		case 'q':
1287 			flags |= LLONGINT;
1288 			goto rflag;
1289 		case 't':
1290 			flags |= PTRINT;
1291 			goto rflag;
1292 		case 'z':
1293 			flags |= SIZEINT;
1294 			goto rflag;
1295 		case 'c':
1296 #ifdef PRINTF_WIDE_CHAR
1297 			if (flags & LONGINT)
1298 				ADDTYPE(T_WINT);
1299 			else
1300 #endif
1301 				ADDTYPE(T_INT);
1302 			break;
1303 		case 'D':
1304 			flags |= LONGINT;
1305 			/*FALLTHROUGH*/
1306 		case 'd':
1307 		case 'i':
1308 			ADDSARG();
1309 			break;
1310 #ifdef FLOATING_POINT
1311 		case 'a':
1312 		case 'A':
1313 		case 'e':
1314 		case 'E':
1315 		case 'f':
1316 		case 'F':
1317 		case 'g':
1318 		case 'G':
1319 			if (flags & LONGDBL)
1320 				ADDTYPE(T_LONG_DOUBLE);
1321 			else
1322 				ADDTYPE(T_DOUBLE);
1323 			break;
1324 #endif /* FLOATING_POINT */
1325 		case 'n':
1326 			if (flags & LLONGINT)
1327 				ADDTYPE(TP_LLONG);
1328 			else if (flags & LONGINT)
1329 				ADDTYPE(TP_LONG);
1330 			else if (flags & SHORTINT)
1331 				ADDTYPE(TP_SHORT);
1332 			else if (flags & PTRINT)
1333 				ADDTYPE(TP_PTRINT);
1334 			else if (flags & SIZEINT)
1335 				ADDTYPE(TP_SSIZEINT);
1336 			else if (flags & MAXINT)
1337 				ADDTYPE(TP_MAXINT);
1338 			else
1339 				ADDTYPE(TP_INT);
1340 			continue;	/* no output */
1341 		case 'O':
1342 			flags |= LONGINT;
1343 			/*FALLTHROUGH*/
1344 		case 'o':
1345 			ADDUARG();
1346 			break;
1347 		case 'p':
1348 			ADDTYPE(TP_VOID);
1349 			break;
1350 		case 's':
1351 #ifdef PRINTF_WIDE_CHAR
1352 			if (flags & LONGINT)
1353 				ADDTYPE(TP_WCHAR);
1354 			else
1355 #endif
1356 				ADDTYPE(TP_CHAR);
1357 			break;
1358 		case 'U':
1359 			flags |= LONGINT;
1360 			/*FALLTHROUGH*/
1361 		case 'u':
1362 		case 'X':
1363 		case 'x':
1364 			ADDUARG();
1365 			break;
1366 		default:	/* "%?" prints ?, unless ? is NUL */
1367 			if (ch == '\0')
1368 				goto done;
1369 			break;
1370 		}
1371 	}
1372 done:
1373 	/*
1374 	 * Build the argument table.
1375 	 */
1376 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1377 		*argtablesiz = sizeof(union arg) * (tablemax + 1);
1378 		*argtable = mmap(NULL, *argtablesiz,
1379 		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
1380 		if (*argtable == MAP_FAILED)
1381 			return (-1);
1382 	}
1383 
1384 	for (n = 1; n <= tablemax; n++) {
1385 		switch (typetable[n]) {
1386 		case T_UNUSED:
1387 		case T_CHAR:
1388 		case T_U_CHAR:
1389 		case T_SHORT:
1390 		case T_U_SHORT:
1391 		case T_INT:
1392 			(*argtable)[n].intarg = va_arg(ap, int);
1393 			break;
1394 		case TP_SHORT:
1395 			(*argtable)[n].pshortarg = va_arg(ap, short *);
1396 			break;
1397 		case T_U_INT:
1398 			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
1399 			break;
1400 		case TP_INT:
1401 			(*argtable)[n].pintarg = va_arg(ap, int *);
1402 			break;
1403 		case T_LONG:
1404 			(*argtable)[n].longarg = va_arg(ap, long);
1405 			break;
1406 		case T_U_LONG:
1407 			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1408 			break;
1409 		case TP_LONG:
1410 			(*argtable)[n].plongarg = va_arg(ap, long *);
1411 			break;
1412 		case T_LLONG:
1413 			(*argtable)[n].longlongarg = va_arg(ap, long long);
1414 			break;
1415 		case T_U_LLONG:
1416 			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1417 			break;
1418 		case TP_LLONG:
1419 			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
1420 			break;
1421 #ifdef FLOATING_POINT
1422 		case T_DOUBLE:
1423 			(*argtable)[n].doublearg = va_arg(ap, double);
1424 			break;
1425 		case T_LONG_DOUBLE:
1426 			(*argtable)[n].longdoublearg = va_arg(ap, long double);
1427 			break;
1428 #endif
1429 		case TP_CHAR:
1430 			(*argtable)[n].pchararg = va_arg(ap, char *);
1431 			break;
1432 		case TP_VOID:
1433 			(*argtable)[n].pvoidarg = va_arg(ap, void *);
1434 			break;
1435 		case T_PTRINT:
1436 			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1437 			break;
1438 		case TP_PTRINT:
1439 			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
1440 			break;
1441 		case T_SIZEINT:
1442 			(*argtable)[n].sizearg = va_arg(ap, size_t);
1443 			break;
1444 		case T_SSIZEINT:
1445 			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
1446 			break;
1447 		case TP_SSIZEINT:
1448 			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
1449 			break;
1450 		case T_MAXINT:
1451 			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1452 			break;
1453 		case T_MAXUINT:
1454 			(*argtable)[n].uintmaxarg = va_arg(ap, uintmax_t);
1455 			break;
1456 		case TP_MAXINT:
1457 			(*argtable)[n].pintmaxarg = va_arg(ap, intmax_t *);
1458 			break;
1459 #ifdef PRINTF_WIDE_CHAR
1460 		case T_WINT:
1461 			(*argtable)[n].wintarg = va_arg(ap, wint_t);
1462 			break;
1463 		case TP_WCHAR:
1464 			(*argtable)[n].pwchararg = va_arg(ap, wchar_t *);
1465 			break;
1466 #endif
1467 		}
1468 	}
1469 	goto finish;
1470 
1471 overflow:
1472 	errno = EOVERFLOW;
1473 	ret = -1;
1474 
1475 finish:
1476 	if (typetable != NULL && typetable != stattypetable) {
1477 		munmap(typetable, *argtablesiz);
1478 		typetable = NULL;
1479 	}
1480 	return (ret);
1481 }
1482 
1483 /*
1484  * Increase the size of the type table.
1485  */
1486 static int
__grow_type_table(unsigned char ** typetable,int * tablesize)1487 __grow_type_table(unsigned char **typetable, int *tablesize)
1488 {
1489 	unsigned char *oldtable = *typetable;
1490 	int newsize = *tablesize * 2;
1491 
1492 	if (newsize < getpagesize())
1493 		newsize = getpagesize();
1494 
1495 	if (*tablesize == STATIC_ARG_TBL_SIZE) {
1496 		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1497 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1498 		if (*typetable == MAP_FAILED)
1499 			return (-1);
1500 		bcopy(oldtable, *typetable, *tablesize);
1501 	} else {
1502 		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1503 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1504 		if (new == MAP_FAILED)
1505 			return (-1);
1506 		memmove(new, *typetable, *tablesize);
1507 		munmap(*typetable, *tablesize);
1508 		*typetable = new;
1509 	}
1510 	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
1511 
1512 	*tablesize = newsize;
1513 	return (0);
1514 }
1515 
1516 
1517 #ifdef FLOATING_POINT
1518 static int
exponent(char * p0,int exp,int fmtch)1519 exponent(char *p0, int exp, int fmtch)
1520 {
1521 	char *p, *t;
1522 	char expbuf[MAXEXPDIG];
1523 
1524 	p = p0;
1525 	*p++ = fmtch;
1526 	if (exp < 0) {
1527 		exp = -exp;
1528 		*p++ = '-';
1529 	} else
1530 		*p++ = '+';
1531 	t = expbuf + MAXEXPDIG;
1532 	if (exp > 9) {
1533 		do {
1534 			*--t = to_char(exp % 10);
1535 		} while ((exp /= 10) > 9);
1536 		*--t = to_char(exp);
1537 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++)
1538 			/* nothing */;
1539 	} else {
1540 		/*
1541 		 * Exponents for decimal floating point conversions
1542 		 * (%[eEgG]) must be at least two characters long,
1543 		 * whereas exponents for hexadecimal conversions can
1544 		 * be only one character long.
1545 		 */
1546 		if (fmtch == 'e' || fmtch == 'E')
1547 			*p++ = '0';
1548 		*p++ = to_char(exp);
1549 	}
1550 	return (p - p0);
1551 }
1552 #endif /* FLOATING_POINT */
1553