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