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