xref: /netbsd-src/lib/libc/stdio/vfwprintf.c (revision 526d942790cc352b6ea7931f9884cc6bdbf20404)
1 /*	$NetBSD: vfwprintf.c,v 1.28 2012/03/15 18:22:30 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)vfprintf.c	8.1 (Berkeley) 6/4/93";
39 __FBSDID("$FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.27 2007/01/09 00:28:08 imp Exp $");
40 #else
41 __RCSID("$NetBSD: vfwprintf.c,v 1.28 2012/03/15 18:22:30 christos Exp $");
42 #endif
43 #endif /* LIBC_SCCS and not lint */
44 
45 /*
46  * Actual {w,}printf innards.
47  */
48 
49 #include "namespace.h"
50 #include <sys/types.h>
51 
52 #include <assert.h>
53 #include <ctype.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <stdarg.h>
57 #include <stddef.h>
58 #include <stdint.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <errno.h>
63 #include <wchar.h>
64 #include <wctype.h>
65 
66 #include "reentrant.h"
67 #include "local.h"
68 #include "extern.h"
69 #include "fvwrite.h"
70 
71 #ifndef NARROW
72 #define MCHAR_T		char
73 #define CHAR_T		wchar_t
74 #define STRLEN(a)	wcslen(a)
75 #define MEMCHR(a, b, c)	wmemchr(a, b, c)
76 #define SCONV(a, b)	__mbsconv(a, b)
77 #define STRCONST(a)	L ## a
78 #define WDECL(a, b)	a ## w ## b
79 #define END_OF_FILE	WEOF
80 #define MULTI		0
81 #else
82 #define MCHAR_T		wchar_t
83 #define CHAR_T		char
84 #define STRLEN(a)	strlen(a)
85 #define MEMCHR(a, b, c)	memchr(a, b, c)
86 #define SCONV(a, b)	__wcsconv(a, b)
87 #define STRCONST(a)	a
88 #define WDECL(a, b)	a ## b
89 #define END_OF_FILE	EOF
90 #define MULTI		LONGINT
91 #endif
92 
93 union arg {
94 	int	intarg;
95 	u_int	uintarg;
96 	long	longarg;
97 	u_long	ulongarg;
98 	long long longlongarg;
99 	unsigned long long ulonglongarg;
100 	ptrdiff_t ptrdiffarg;
101 	ssize_t ssizearg;
102 	size_t	sizearg;
103 	intmax_t intmaxarg;
104 	uintmax_t uintmaxarg;
105 	void	*pvoidarg;
106 	char	*pchararg;
107 	signed char *pschararg;
108 	short	*pshortarg;
109 	int	*pintarg;
110 	long	*plongarg;
111 	long long *plonglongarg;
112 	ptrdiff_t *pptrdiffarg;
113 	size_t	*psizearg;
114 	intmax_t *pintmaxarg;
115 #ifndef NO_FLOATING_POINT
116 	double	doublearg;
117 	long double longdoublearg;
118 #endif
119 	wint_t	wintarg;
120 	wchar_t	*pwchararg;
121 };
122 
123 /*
124  * Type ids for argument type table.
125  */
126 enum typeid {
127 	T_UNUSED = 0, TP_SHORT, T_INT, T_U_INT, TP_INT,
128 	T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
129 	T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SIZET,
130 	T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
131 	T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
132 };
133 
134 static int	__sbprintf(FILE *, const CHAR_T *, va_list);
135 static CHAR_T	*__ujtoa(uintmax_t, CHAR_T *, int, int, const char *, int,
136 		    char, const char *);
137 static CHAR_T	*__ultoa(u_long, CHAR_T *, int, int, const char *, int,
138 		    char, const char *);
139 #ifndef NARROW
140 static CHAR_T	*__mbsconv(char *, int);
141 static wint_t	__xfputwc(CHAR_T, FILE *);
142 #else
143 static char	*__wcsconv(wchar_t *, int);
144 static int	__sprint(FILE *, struct __suio *);
145 #endif
146 static int	__find_arguments(const CHAR_T *, va_list, union arg **);
147 static int	__grow_type_table(size_t, enum typeid **, size_t *);
148 
149 /*
150  * Helper function for `fprintf to unbuffered unix file': creates a
151  * temporary buffer.  We only work on write-only files; this avoids
152  * worries about ungetc buffers and so forth.
153  */
154 static int
155 __sbprintf(FILE *fp, const CHAR_T *fmt, va_list ap)
156 {
157 	int ret;
158 	FILE fake;
159 	struct __sfileext fakeext;
160 	unsigned char buf[BUFSIZ];
161 
162 	_DIAGASSERT(fp != NULL);
163 	_DIAGASSERT(fmt != NULL);
164 
165 	_FILEEXT_SETUP(&fake, &fakeext);
166 	memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
167 
168 	/* copy the important variables */
169 	fake._flags = fp->_flags & ~__SNBF;
170 	fake._file = fp->_file;
171 	fake._cookie = fp->_cookie;
172 	fake._write = fp->_write;
173 
174 	/* set up the buffer */
175 	fake._bf._base = fake._p = buf;
176 	fake._bf._size = fake._w = sizeof(buf);
177 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
178 
179 	/* do the work, then copy any error status */
180 	ret = WDECL(__vf,printf_unlocked)(&fake, fmt, ap);
181 	if (ret >= 0 && fflush(&fake))
182 		ret = END_OF_FILE;
183 	if (fake._flags & __SERR)
184 		fp->_flags |= __SERR;
185 	return ret;
186 }
187 
188 #ifndef NARROW
189 /*
190  * Like __fputwc, but handles fake string (__SSTR) files properly.
191  * File must already be locked.
192  */
193 static wint_t
194 __xfputwc(wchar_t wc, FILE *fp)
195 {
196 	static const mbstate_t initial;
197 	mbstate_t mbs;
198 	char buf[MB_LEN_MAX];
199 	struct __suio uio;
200 	struct __siov iov;
201 	size_t len;
202 
203 	if ((fp->_flags & __SSTR) == 0)
204 		return __fputwc_unlock(wc, fp);
205 
206 	mbs = initial;
207 	if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
208 		fp->_flags |= __SERR;
209 		return END_OF_FILE;
210 	}
211 	uio.uio_iov = &iov;
212 	uio.uio_resid = len;
213 	uio.uio_iovcnt = 1;
214 	iov.iov_base = buf;
215 	iov.iov_len = len;
216 	return __sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE;
217 }
218 #else
219 /*
220  * Flush out all the vectors defined by the given uio,
221  * then reset it so that it can be reused.
222  */
223 static int
224 __sprint(FILE *fp, struct __suio *uio)
225 {
226 	int err;
227 
228 	_DIAGASSERT(fp != NULL);
229 	_DIAGASSERT(uio != NULL);
230 
231 	if (uio->uio_resid == 0) {
232 		uio->uio_iovcnt = 0;
233 		return 0;
234 	}
235 	err = __sfvwrite(fp, uio);
236 	uio->uio_resid = 0;
237 	uio->uio_iovcnt = 0;
238 	return err;
239 }
240 #endif
241 
242 /*
243  * Macros for converting digits to letters and vice versa
244  */
245 #define	to_digit(c)	((c) - '0')
246 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
247 #define	to_char(n)	(CHAR_T)((n) + '0')
248 
249 /*
250  * Convert an unsigned long to ASCII for printf purposes, returning
251  * a pointer to the first character of the string representation.
252  * Octal numbers can be forced to have a leading zero; hex numbers
253  * use the given digits.
254  */
255 static CHAR_T *
256 __ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs,
257     int needgrp, char thousep, const char *grp)
258 {
259 	CHAR_T *cp = endp;
260 	long sval;
261 	int ndig;
262 
263 	/*
264 	 * Handle the three cases separately, in the hope of getting
265 	 * better/faster code.
266 	 */
267 	switch (base) {
268 	case 10:
269 		if (val < 10) {	/* many numbers are 1 digit */
270 			*--cp = to_char(val);
271 			return cp;
272 		}
273 		ndig = 0;
274 		/*
275 		 * On many machines, unsigned arithmetic is harder than
276 		 * signed arithmetic, so we do at most one unsigned mod and
277 		 * divide; this is sufficient to reduce the range of
278 		 * the incoming value to where signed arithmetic works.
279 		 */
280 		if (val > LONG_MAX) {
281 			*--cp = to_char(val % 10);
282 			ndig++;
283 			sval = val / 10;
284 		} else
285 			sval = val;
286 		do {
287 			*--cp = to_char(sval % 10);
288 			ndig++;
289 			/*
290 			 * If (*grp == CHAR_MAX) then no more grouping
291 			 * should be performed.
292 			 */
293 			if (needgrp && ndig == *grp && *grp != CHAR_MAX
294 					&& sval > 9) {
295 				*--cp = thousep;
296 				ndig = 0;
297 				/*
298 				 * If (*(grp+1) == '\0') then we have to
299 				 * use *grp character (last grouping rule)
300 				 * for all next cases
301 				 */
302 				if (*(grp+1) != '\0')
303 					grp++;
304 			}
305 			sval /= 10;
306 		} while (sval != 0);
307 		break;
308 
309 	case 8:
310 		do {
311 			*--cp = to_char(val & 7);
312 			val >>= 3;
313 		} while (val);
314 		if (octzero && *cp != '0')
315 			*--cp = '0';
316 		break;
317 
318 	case 16:
319 		do {
320 			*--cp = xdigs[(size_t)val & 15];
321 			val >>= 4;
322 		} while (val);
323 		break;
324 
325 	default:			/* oops */
326 		abort();
327 	}
328 	return cp;
329 }
330 
331 /* Identical to __ultoa, but for intmax_t. */
332 static CHAR_T *
333 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero,
334     const char *xdigs, int needgrp, char thousep, const char *grp)
335 {
336 	CHAR_T *cp = endp;
337 	intmax_t sval;
338 	int ndig;
339 
340 	/* quick test for small values; __ultoa is typically much faster */
341 	/* (perhaps instead we should run until small, then call __ultoa?) */
342 	if (val <= ULONG_MAX)
343 		return __ultoa((u_long)val, endp, base, octzero, xdigs,
344 		    needgrp, thousep, grp);
345 	switch (base) {
346 	case 10:
347 		if (val < 10) {
348 			*--cp = to_char(val % 10);
349 			return cp;
350 		}
351 		ndig = 0;
352 		if (val > INTMAX_MAX) {
353 			*--cp = to_char(val % 10);
354 			ndig++;
355 			sval = val / 10;
356 		} else
357 			sval = val;
358 		do {
359 			*--cp = to_char(sval % 10);
360 			ndig++;
361 			/*
362 			 * If (*grp == CHAR_MAX) then no more grouping
363 			 * should be performed.
364 			 */
365 			if (needgrp && *grp != CHAR_MAX && ndig == *grp
366 					&& sval > 9) {
367 				*--cp = thousep;
368 				ndig = 0;
369 				/*
370 				 * If (*(grp+1) == '\0') then we have to
371 				 * use *grp character (last grouping rule)
372 				 * for all next cases
373 				 */
374 				if (*(grp+1) != '\0')
375 					grp++;
376 			}
377 			sval /= 10;
378 		} while (sval != 0);
379 		break;
380 
381 	case 8:
382 		do {
383 			*--cp = to_char(val & 7);
384 			val >>= 3;
385 		} while (val);
386 		if (octzero && *cp != '0')
387 			*--cp = '0';
388 		break;
389 
390 	case 16:
391 		do {
392 			*--cp = xdigs[(size_t)val & 15];
393 			val >>= 4;
394 		} while (val);
395 		break;
396 
397 	default:
398 		abort();
399 	}
400 	return cp;
401 }
402 
403 #ifndef NARROW
404 /*
405  * Convert a multibyte character string argument for the %s format to a wide
406  * string representation. ``prec'' specifies the maximum number of bytes
407  * to output. If ``prec'' is greater than or equal to zero, we can't assume
408  * that the multibyte char. string ends in a null character.
409  */
410 static wchar_t *
411 __mbsconv(char *mbsarg, int prec)
412 {
413 	static const mbstate_t initial;
414 	mbstate_t mbs;
415 	wchar_t *convbuf, *wcp;
416 	const char *p;
417 	size_t insize, nchars, nconv;
418 
419 	if (mbsarg == NULL)
420 		return NULL;
421 
422 	/*
423 	 * Supplied argument is a multibyte string; convert it to wide
424 	 * characters first.
425 	 */
426 	if (prec >= 0) {
427 		/*
428 		 * String is not guaranteed to be NUL-terminated. Find the
429 		 * number of characters to print.
430 		 */
431 		p = mbsarg;
432 		insize = nchars = nconv = 0;
433 		mbs = initial;
434 		while (nchars != (size_t)prec) {
435 			nconv = mbrlen(p, MB_CUR_MAX, &mbs);
436 			if (nconv == 0 || nconv == (size_t)-1 ||
437 			    nconv == (size_t)-2)
438 				break;
439 			p += nconv;
440 			nchars++;
441 			insize += nconv;
442 		}
443 		if (nconv == (size_t)-1 || nconv == (size_t)-2)
444 			return NULL;
445 	} else
446 		insize = strlen(mbsarg);
447 
448 	/*
449 	 * Allocate buffer for the result and perform the conversion,
450 	 * converting at most `size' bytes of the input multibyte string to
451 	 * wide characters for printing.
452 	 */
453 	convbuf = malloc((insize + 1) * sizeof(*convbuf));
454 	if (convbuf == NULL)
455 		return NULL;
456 	wcp = convbuf;
457 	p = mbsarg;
458 	mbs = initial;
459 	nconv = 0;
460 	while (insize != 0) {
461 		nconv = mbrtowc(wcp, p, insize, &mbs);
462 		if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
463 			break;
464 		wcp++;
465 		p += nconv;
466 		insize -= nconv;
467 	}
468 	if (nconv == (size_t)-1 || nconv == (size_t)-2) {
469 		free(convbuf);
470 		return NULL;
471 	}
472 	*wcp = L'\0';
473 
474 	return convbuf;
475 }
476 #else
477 /*
478  * Convert a wide-character string argument for the %ls format to a multibyte
479  * string representation. If not -1, prec specifies the maximum number of
480  * bytes to output, and also means that we can't assume that the wide-char.
481  * string ends is null-terminated.
482  */
483 static char *
484 __wcsconv(wchar_t *wcsarg, int prec)
485 {
486 	static const mbstate_t initial;
487 	mbstate_t mbs;
488 	char buf[MB_LEN_MAX];
489 	wchar_t *p;
490 	char *convbuf;
491 	size_t clen, nbytes;
492 
493 	/* Allocate space for the maximum number of bytes we could output. */
494 	if (prec < 0) {
495 		p = wcsarg;
496 		mbs = initial;
497 		nbytes = wcsrtombs(NULL, (void *)&p, 0, &mbs);
498 		if (nbytes == (size_t)-1)
499 			return NULL;
500 	} else {
501 		/*
502 		 * Optimisation: if the output precision is small enough,
503 		 * just allocate enough memory for the maximum instead of
504 		 * scanning the string.
505 		 */
506 		if (prec < 128)
507 			nbytes = prec;
508 		else {
509 			nbytes = 0;
510 			p = wcsarg;
511 			mbs = initial;
512 			for (;;) {
513 				clen = wcrtomb(buf, *p++, &mbs);
514 				if (clen == 0 || clen == (size_t)-1 ||
515 				    nbytes + clen > (size_t)prec)
516 					break;
517 				nbytes += clen;
518 			}
519 		}
520 	}
521 	if ((convbuf = malloc(nbytes + 1)) == NULL)
522 		return NULL;
523 
524 	/* Fill the output buffer. */
525 	p = wcsarg;
526 	mbs = initial;
527 	if ((nbytes = wcsrtombs(convbuf, (void *)&p,
528 	    nbytes, &mbs)) == (size_t)-1) {
529 		free(convbuf);
530 		return NULL;
531 	}
532 	convbuf[nbytes] = '\0';
533 	return convbuf;
534 }
535 #endif
536 
537 /*
538  * MT-safe version
539  */
540 int
541 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap)
542 {
543 	int ret;
544 
545 	FLOCKFILE(fp);
546 	ret = WDECL(__vf,printf_unlocked)(fp, fmt0, ap);
547 	FUNLOCKFILE(fp);
548 	return ret;
549 }
550 
551 #ifndef NO_FLOATING_POINT
552 
553 #include <float.h>
554 #include <math.h>
555 #include "floatio.h"
556 
557 #define	DEFPREC		6
558 
559 static int exponent(CHAR_T *, int, int);
560 #ifndef WIDE_DOUBLE
561 static char *cvt(double, int, int, char *, int *, int, int *);
562 #endif
563 
564 #endif /* !NO_FLOATING_POINT */
565 
566 /*
567  * The size of the buffer we use as scratch space for integer
568  * conversions, among other things.  Technically, we would need the
569  * most space for base 10 conversions with thousands' grouping
570  * characters between each pair of digits.  100 bytes is a
571  * conservative overestimate even for a 128-bit uintmax_t.
572  */
573 #define	BUF	100
574 
575 #define STATIC_ARG_TBL_SIZE 8           /* Size of static argument table. */
576 
577 /*
578  * Flags used during conversion.
579  */
580 #define	ALT		0x001		/* alternate form */
581 #define	LADJUST		0x004		/* left adjustment */
582 #define	LONGDBL		0x008		/* long double */
583 #define	LONGINT		0x010		/* long integer */
584 #define	LLONGINT	0x020		/* long long integer */
585 #define	SHORTINT	0x040		/* short integer */
586 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
587 #define	FPT		0x100		/* Floating point number */
588 #define	GROUPING	0x200		/* use grouping ("'" flag) */
589 					/* C99 additional size modifiers: */
590 #define	SIZET		0x400		/* size_t */
591 #define	PTRDIFFT	0x800		/* ptrdiff_t */
592 #define	INTMAXT		0x1000		/* intmax_t */
593 #define	CHARINT		0x2000		/* print char using int format */
594 
595 /*
596  * Non-MT-safe version
597  */
598 int
599 WDECL(__vf,printf_unlocked)(FILE *fp, const CHAR_T *fmt0, va_list ap)
600 {
601 	CHAR_T *fmt;		/* format string */
602 	int ch;			/* character from fmt */
603 	int n, n2;		/* handy integer (short term usage) */
604 	CHAR_T *cp;		/* handy char pointer (short term usage) */
605 	int flags;		/* flags as above */
606 	int ret;		/* return value accumulator */
607 	int width;		/* width from format (%8d), or 0 */
608 	int prec;		/* precision from format; <0 for N/A */
609 	CHAR_T sign;		/* sign prefix (' ', '+', '-', or \0) */
610 	char thousands_sep;	/* locale specific thousands separator */
611 	const char *grouping;	/* locale specific numeric grouping rules */
612 #ifndef NO_FLOATING_POINT
613 	/*
614 	 * We can decompose the printed representation of floating
615 	 * point numbers into several parts, some of which may be empty:
616 	 *
617 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
618 	 *    A       B     ---C---      D       E   F
619 	 *
620 	 * A:	'sign' holds this value if present; '\0' otherwise
621 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
622 	 * C:	cp points to the string MMMNNN.  Leading and trailing
623 	 *	zeros are not in the string and must be added.
624 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
625 	 * F:	at least two digits for decimal, at least one digit for hex
626 	 */
627 	char *decimal_point;	/* locale specific decimal point */
628 #ifdef WIDE_DOUBLE
629 	int signflag;		/* true if float is negative */
630 	union {			/* floating point arguments %[aAeEfFgG] */
631 		double dbl;
632 		long double ldbl;
633 	} fparg;
634 	char *dtoaend;		/* pointer to end of converted digits */
635 #else
636 	double _double;		/* double precision arguments %[eEfgG] */
637 	char softsign;		/* temporary negative sign for floats */
638 #endif
639 	char *dtoaresult;	/* buffer allocated by dtoa */
640 	int expt;		/* integer value of exponent */
641 	char expchar;		/* exponent character: [eEpP\0] */
642 	int expsize;		/* character count for expstr */
643 	int lead;		/* sig figs before decimal or group sep */
644 	int ndig;		/* actual number of digits returned by dtoa */
645 	CHAR_T expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
646 	int nseps;		/* number of group separators with ' */
647 	int nrepeats;		/* number of repeats of the last group */
648 #endif
649 	u_long	ulval;		/* integer arguments %[diouxX] */
650 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
651 	int base;		/* base for [diouxX] conversion */
652 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
653 	int realsz;		/* field size expanded by dprec, sign, etc */
654 	int size;		/* size of converted field or string */
655 	int prsize;             /* max size of printed field */
656 	const char *xdigs;	/* digits for %[xX] conversion */
657 #ifdef NARROW
658 #define NIOV 8
659 	struct __siov *iovp;	/* for PRINT macro */
660 	struct __suio uio;	/* output information: summary */
661 	struct __siov iov[NIOV];/* ... and individual io vectors */
662 #else
663 	int n3;
664 #endif
665 	CHAR_T buf[BUF];	/* buffer with space for digits of uintmax_t */
666 	CHAR_T ox[2];		/* space for 0x hex-prefix */
667 	union arg *argtable;	/* args, built due to positional arg */
668 	union arg statargtable [STATIC_ARG_TBL_SIZE];
669 	int nextarg;		/* 1-based argument index */
670 	va_list orgap;		/* original argument pointer */
671 	CHAR_T *convbuf;	/* multibyte to wide conversion result */
672 
673 	/*
674 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
675 	 * fields occur frequently, increase PADSIZE and make the initialisers
676 	 * below longer.
677 	 */
678 #define	PADSIZE	16		/* pad chunk size */
679 	static CHAR_T blanks[PADSIZE] =
680 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
681 	static CHAR_T zeroes[PADSIZE] =
682 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
683 
684 	static const char xdigs_lower[16] = "0123456789abcdef";
685 	static const char xdigs_upper[16] = "0123456789ABCDEF";
686 
687 	/*
688 	 * BEWARE, these `goto error' on error, PRINT uses `n2' and
689 	 * PAD uses `n'.
690 	 */
691 #ifndef NARROW
692 #define	PRINT(ptr, len)	do {			\
693 	for (n3 = 0; n3 < (len); n3++)		\
694 		__xfputwc((ptr)[n3], fp);	\
695 } while (/*CONSTCOND*/0)
696 #define FLUSH()
697 #else
698 #define	PRINT(ptr, len) do { \
699 	iovp->iov_base = __UNCONST(ptr); \
700 	iovp->iov_len = (len); \
701 	uio.uio_resid += (len); \
702 	iovp++; \
703 	if (++uio.uio_iovcnt >= NIOV) { \
704 		if (__sprint(fp, &uio)) \
705 			goto error; \
706 		iovp = iov; \
707 	} \
708 } while (/*CONSTCOND*/0)
709 #define	FLUSH() do { \
710 	if (uio.uio_resid && __sprint(fp, &uio)) \
711 		goto error; \
712 	uio.uio_iovcnt = 0; \
713 	iovp = iov; \
714 } while (/*CONSTCOND*/0)
715 #endif /* NARROW */
716 
717 #define	PAD(howmany, with)	do {		\
718 	if ((n = (howmany)) > 0) {		\
719 		while (n > PADSIZE) {		\
720 			PRINT(with, PADSIZE);	\
721 			n -= PADSIZE;		\
722 		}				\
723 		PRINT(with, n);			\
724 	}					\
725 } while (/*CONSTCOND*/0)
726 #define	PRINTANDPAD(p, ep, len, with) do {	\
727 	ptrdiff_t td = (ep) - (p);		\
728 	_DIAGASSERT(__type_fit(int, td));	\
729 	n2 = (int)td;       			\
730 	if (n2 > (len))				\
731 		n2 = (len);			\
732 	if (n2 > 0)				\
733 		PRINT((p), n2);			\
734 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
735 } while(/*CONSTCOND*/0)
736 
737 	/*
738 	 * Get the argument indexed by nextarg.   If the argument table is
739 	 * built, use it to get the argument.  If its not, get the next
740 	 * argument (and arguments must be gotten sequentially).
741 	 */
742 #define GETARG(type) \
743 	((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
744 	    (nextarg++, va_arg(ap, type)))
745 
746 	/*
747 	 * To extend shorts properly, we need both signed and unsigned
748 	 * argument extraction methods.
749 	 */
750 #define	SARG() \
751 	(flags&LONGINT ? GETARG(long) : \
752 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
753 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
754 	    (long)GETARG(int))
755 #define	UARG() \
756 	(flags&LONGINT ? GETARG(u_long) : \
757 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
758 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
759 	    (u_long)GETARG(u_int))
760 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
761 #define SJARG() \
762 	(flags&INTMAXT ? GETARG(intmax_t) : \
763 	    flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
764 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
765 	    (intmax_t)GETARG(long long))
766 #define	UJARG() \
767 	(flags&INTMAXT ? GETARG(uintmax_t) : \
768 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
769 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
770 	    (uintmax_t)GETARG(unsigned long long))
771 
772 	/*
773 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
774 	 * that the argument can be gotten once the type is determined.
775 	 */
776 #define GETASTER(val) \
777 	n2 = 0; \
778 	cp = fmt; \
779 	while (is_digit(*cp)) { \
780 		n2 = 10 * n2 + to_digit(*cp); \
781 		cp++; \
782 	} \
783 	if (*cp == '$') { \
784 		int hold = nextarg; \
785 		if (argtable == NULL) { \
786 			argtable = statargtable; \
787 			if (__find_arguments(fmt0, orgap, &argtable) == -1) \
788 				goto oomem; \
789 		} \
790 		nextarg = n2; \
791 		val = GETARG (int); \
792 		nextarg = hold; \
793 		fmt = ++cp; \
794 	} else { \
795 		val = GETARG (int); \
796 	}
797 
798 	_DIAGASSERT(fp != NULL);
799 	_DIAGASSERT(fmt0 != NULL);
800 
801 	_SET_ORIENTATION(fp, -1);
802 
803 	ndig = -1;	/* XXX gcc */
804 
805 	thousands_sep = '\0';
806 	grouping = NULL;
807 #ifndef NO_FLOATING_POINT
808 	decimal_point = localeconv()->decimal_point;
809 	expsize = 0;		/* XXXGCC -Wuninitialized [sh3,m68000] */
810 #endif
811 	convbuf = NULL;
812 	/* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
813 	if (cantwrite(fp)) {
814 		errno = EBADF;
815 		return END_OF_FILE;
816 	}
817 
818 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
819 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
820 	    __sfileno(fp) != -1)
821 		return __sbprintf(fp, fmt0, ap);
822 
823 	fmt = (CHAR_T *)__UNCONST(fmt0);
824 	argtable = NULL;
825 	nextarg = 1;
826 	va_copy(orgap, ap);
827 #ifdef NARROW
828 	uio.uio_iov = iovp = iov;
829 	uio.uio_resid = 0;
830 	uio.uio_iovcnt = 0;
831 #endif
832 	ret = 0;
833 
834 	/*
835 	 * Scan the format for conversions (`%' character).
836 	 */
837 	for (;;) {
838 		const CHAR_T *result;
839 
840 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
841 			continue;
842 		_DIAGASSERT(__type_fit(int, fmt - cp));
843 		if ((n = (int)(fmt - cp)) != 0) {
844 			if ((unsigned)ret + n > INT_MAX) {
845 				ret = END_OF_FILE;
846 				goto error;
847 			}
848 			PRINT(cp, n);
849 			ret += n;
850 		}
851 		if (ch == '\0')
852 			goto done;
853 		fmt++;		/* skip over '%' */
854 
855 		flags = 0;
856 		dprec = 0;
857 		width = 0;
858 		prec = -1;
859 		sign = '\0';
860 		ox[1] = '\0';
861 		expchar = '\0';
862 		lead = 0;
863 		nseps = nrepeats = 0;
864 		ulval = 0;
865 		ujval = 0;
866 		xdigs = NULL;
867 
868 rflag:		ch = *fmt++;
869 reswitch:	switch (ch) {
870 		case ' ':
871 			/*-
872 			 * ``If the space and + flags both appear, the space
873 			 * flag will be ignored.''
874 			 *	-- ANSI X3J11
875 			 */
876 			if (!sign)
877 				sign = ' ';
878 			goto rflag;
879 		case '#':
880 			flags |= ALT;
881 			goto rflag;
882 		case '*':
883 			/*-
884 			 * ``A negative field width argument is taken as a
885 			 * - flag followed by a positive field width.''
886 			 *	-- ANSI X3J11
887 			 * They don't exclude field widths read from args.
888 			 */
889 			GETASTER (width);
890 			if (width >= 0)
891 				goto rflag;
892 			width = -width;
893 			/* FALLTHROUGH */
894 		case '-':
895 			flags |= LADJUST;
896 			goto rflag;
897 		case '+':
898 			sign = '+';
899 			goto rflag;
900 		case '\'':
901 			flags |= GROUPING;
902 			thousands_sep = *(localeconv()->thousands_sep);
903 			grouping = localeconv()->grouping;
904 			/* If the locale doesn't define the above, use sane
905 			 * defaults - otherwise silly things happen! */
906 			if (thousands_sep == 0)
907 				thousands_sep = ',';
908 			if (!grouping || !*grouping)
909 				grouping = "\3";
910 			goto rflag;
911 		case '.':
912 			if ((ch = *fmt++) == '*') {
913 				GETASTER (prec);
914 				goto rflag;
915 			}
916 			prec = 0;
917 			while (is_digit(ch)) {
918 				prec = 10 * prec + to_digit(ch);
919 				ch = *fmt++;
920 			}
921 			goto reswitch;
922 		case '0':
923 			/*-
924 			 * ``Note that 0 is taken as a flag, not as the
925 			 * beginning of a field width.''
926 			 *	-- ANSI X3J11
927 			 */
928 			flags |= ZEROPAD;
929 			goto rflag;
930 		case '1': case '2': case '3': case '4':
931 		case '5': case '6': case '7': case '8': case '9':
932 			n = 0;
933 			do {
934 				n = 10 * n + to_digit(ch);
935 				ch = *fmt++;
936 			} while (is_digit(ch));
937 			if (ch == '$') {
938 				nextarg = n;
939 				if (argtable == NULL) {
940 					argtable = statargtable;
941 					if (__find_arguments(fmt0, orgap,
942 					    &argtable) == -1)
943 						goto oomem;
944 				}
945 				goto rflag;
946 			}
947 			width = n;
948 			goto reswitch;
949 #ifndef NO_FLOATING_POINT
950 		case 'L':
951 			flags |= LONGDBL;
952 			goto rflag;
953 #endif
954 		case 'h':
955 			if (flags & SHORTINT) {
956 				flags &= ~SHORTINT;
957 				flags |= CHARINT;
958 			} else
959 				flags |= SHORTINT;
960 			goto rflag;
961 		case 'j':
962 			flags |= INTMAXT;
963 			goto rflag;
964 		case 'l':
965 			if (flags & LONGINT) {
966 				flags &= ~LONGINT;
967 				flags |= LLONGINT;
968 			} else
969 				flags |= LONGINT;
970 			goto rflag;
971 		case 'q':
972 			flags |= LLONGINT;	/* not necessarily */
973 			goto rflag;
974 		case 't':
975 			flags |= PTRDIFFT;
976 			goto rflag;
977 		case 'z':
978 			flags |= SIZET;
979 			goto rflag;
980 		case 'C':
981 			flags |= LONGINT;
982 			/*FALLTHROUGH*/
983 		case 'c':
984 #ifdef NARROW
985 			if (flags & LONGINT) {
986 				static const mbstate_t initial;
987 				mbstate_t mbs;
988 				size_t mbseqlen;
989 
990 				mbs = initial;
991 				mbseqlen = wcrtomb(buf,
992 				    (wchar_t)GETARG(wint_t), &mbs);
993 				if (mbseqlen == (size_t)-1) {
994 					fp->_flags |= __SERR;
995 					goto error;
996 				}
997 				size = (int)mbseqlen;
998 			} else {
999 				*buf = GETARG(int);
1000 				size = 1;
1001 			}
1002 #else
1003 			if (flags & LONGINT)
1004 				*buf = (wchar_t)GETARG(wint_t);
1005 			else
1006 				*buf = (wchar_t)btowc(GETARG(int));
1007 			size = 1;
1008 #endif
1009 			result = buf;
1010 			sign = '\0';
1011 			break;
1012 		case 'D':
1013 			flags |= LONGINT;
1014 			/*FALLTHROUGH*/
1015 		case 'd':
1016 		case 'i':
1017 			if (flags & INTMAX_SIZE) {
1018 				ujval = SJARG();
1019 				if ((intmax_t)ujval < 0) {
1020 					ujval = -ujval;
1021 					sign = '-';
1022 				}
1023 			} else {
1024 				ulval = SARG();
1025 				if ((long)ulval < 0) {
1026 					ulval = -ulval;
1027 					sign = '-';
1028 				}
1029 			}
1030 			base = 10;
1031 			goto number;
1032 #ifndef NO_FLOATING_POINT
1033 #ifdef WIDE_DOUBLE
1034 		case 'a':
1035 		case 'A':
1036 			if (ch == 'a') {
1037 				ox[1] = 'x';
1038 				xdigs = xdigs_lower;
1039 				expchar = 'p';
1040 			} else {
1041 				ox[1] = 'X';
1042 				xdigs = xdigs_upper;
1043 				expchar = 'P';
1044 			}
1045 			if (prec >= 0)
1046 				prec++;
1047 			if (flags & LONGDBL) {
1048 				fparg.ldbl = GETARG(long double);
1049 				dtoaresult =
1050 				    __hldtoa(fparg.ldbl, xdigs, prec,
1051 				        &expt, &signflag, &dtoaend);
1052 			} else {
1053 				fparg.dbl = GETARG(double);
1054 				dtoaresult =
1055 				    __hdtoa(fparg.dbl, xdigs, prec,
1056 				        &expt, &signflag, &dtoaend);
1057 			}
1058 			if (dtoaresult == NULL)
1059 				goto oomem;
1060 
1061 			if (prec < 0) {
1062 				_DIAGASSERT(__type_fit(int,
1063 				    dtoaend - dtoaresult));
1064 				prec = (int)(dtoaend - dtoaresult);
1065 			}
1066 			if (expt == INT_MAX)
1067 				ox[1] = '\0';
1068 			_DIAGASSERT(__type_fit(int, dtoaend - dtoaresult));
1069 			ndig = (int)(dtoaend - dtoaresult);
1070 			if (convbuf != NULL)
1071 				free(convbuf);
1072 #ifndef NARROW
1073 			result = convbuf = __mbsconv(dtoaresult, -1);
1074 #else
1075 			/*XXX inefficient*/
1076 			result = convbuf = strdup(dtoaresult);
1077 #endif
1078 			if (result == NULL)
1079 				goto oomem;
1080 			__freedtoa(dtoaresult);
1081 			goto fp_common;
1082 		case 'e':
1083 		case 'E':
1084 			expchar = ch;
1085 			if (prec < 0)	/* account for digit before decpt */
1086 				prec = DEFPREC + 1;
1087 			else
1088 				prec++;
1089 			goto fp_begin;
1090 		case 'f':
1091 		case 'F':
1092 			expchar = '\0';
1093 			goto fp_begin;
1094 		case 'g':
1095 		case 'G':
1096 			expchar = ch - ('g' - 'e');
1097 			if (prec == 0)
1098 				prec = 1;
1099 fp_begin:
1100 			if (prec < 0)
1101 				prec = DEFPREC;
1102 			if (flags & LONGDBL) {
1103 				fparg.ldbl = GETARG(long double);
1104 				dtoaresult =
1105 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
1106 				    &expt, &signflag, &dtoaend);
1107 			} else {
1108 				fparg.dbl = GETARG(double);
1109 				dtoaresult =
1110 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
1111 				    &expt, &signflag, &dtoaend);
1112 				if (expt == 9999)
1113 					expt = INT_MAX;
1114 			}
1115 			if (dtoaresult == NULL)
1116 				goto oomem;
1117 			_DIAGASSERT(__type_fit(int, dtoaend - dtoaresult));
1118 			ndig = (int)(dtoaend - dtoaresult);
1119 			if (convbuf != NULL)
1120 				free(convbuf);
1121 #ifndef NARROW
1122 			result = convbuf = __mbsconv(dtoaresult, -1);
1123 #else
1124 			/*XXX inefficient*/
1125 			result = convbuf = strdup(dtoaresult);
1126 #endif
1127 			if (result == NULL)
1128 				goto oomem;
1129 			__freedtoa(dtoaresult);
1130 fp_common:
1131 			if (signflag)
1132 				sign = '-';
1133 			if (expt == INT_MAX) {	/* inf or nan */
1134 				if (*result == 'N') {
1135 					result = (ch >= 'a') ? STRCONST("nan") :
1136 					    STRCONST("NAN");
1137 					sign = '\0';
1138 				} else
1139 					result = (ch >= 'a') ? STRCONST("inf") :
1140 					    STRCONST("INF");
1141 				size = 3;
1142 				flags &= ~ZEROPAD;
1143 				break;
1144 			}
1145 #else
1146 		case 'e':
1147 		case 'E':
1148 		case 'f':
1149 		case 'F':
1150 		case 'g':
1151 		case 'G':
1152 			if (prec == -1) {
1153 				prec = DEFPREC;
1154 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
1155 				prec = 1;
1156 			}
1157 
1158 			if (flags & LONGDBL) {
1159 				_double = (double) GETARG(long double);
1160 			} else {
1161 				_double = GETARG(double);
1162 			}
1163 
1164 			/* do this before tricky precision changes */
1165 			if (isinf(_double)) {
1166 				if (_double < 0)
1167 					sign = '-';
1168 				if (ch == 'E' || ch == 'F' || ch == 'G')
1169 					result = STRCONST("INF");
1170 				else
1171 					result = STRCONST("inf");
1172 				size = 3;
1173 				flags &= ~ZEROPAD;
1174 				break;
1175 			}
1176 			if (isnan(_double)) {
1177 				if (ch == 'E' || ch == 'F' || ch == 'G')
1178 					result = STRCONST("NAN");
1179 				else
1180 					result = STRCONST("nan");
1181 				size = 3;
1182 				flags &= ~ZEROPAD;
1183 				break;
1184 			}
1185 
1186 			flags |= FPT;
1187 			dtoaresult = cvt(_double, prec, flags, &softsign,
1188 			    &expt, ch, &ndig);
1189 			if (dtoaresult == NULL)
1190 				goto oomem;
1191 			if (convbuf != NULL)
1192 				free(convbuf);
1193 #ifndef NARROW
1194 			result = convbuf = __mbsconv(dtoaresult, -1);
1195 #else
1196 			/*XXX inefficient*/
1197 			result = convbuf = strdup(dtoaresult);
1198 #endif
1199 			if (result == NULL)
1200 				goto oomem;
1201 			__freedtoa(dtoaresult);
1202 			if (softsign)
1203 				sign = '-';
1204 #endif
1205 			flags |= FPT;
1206 			if (ch == 'g' || ch == 'G') {
1207 				if (expt > -4 && expt <= prec) {
1208 					/* Make %[gG] smell like %[fF] */
1209 					expchar = '\0';
1210 					if (flags & ALT)
1211 						prec -= expt;
1212 					else
1213 						prec = ndig - expt;
1214 					if (prec < 0)
1215 						prec = 0;
1216 				} else {
1217 					/*
1218 					 * Make %[gG] smell like %[eE], but
1219 					 * trim trailing zeroes if no # flag.
1220 					 */
1221 					if (!(flags & ALT))
1222 						prec = ndig;
1223 				}
1224 			}
1225 			if (expchar) {
1226 				expsize = exponent(expstr, expt - 1, expchar);
1227 				size = expsize + prec;
1228 				if (prec > 1 || flags & ALT)
1229 					++size;
1230 			} else {
1231 				/* space for digits before decimal point */
1232 				if (expt > 0)
1233 					size = expt;
1234 				else	/* "0" */
1235 					size = 1;
1236 				/* space for decimal pt and following digits */
1237 				if (prec || flags & ALT)
1238 					size += prec + 1;
1239 				if (grouping && expt > 0) {
1240 					/* space for thousands' grouping */
1241 					nseps = nrepeats = 0;
1242 					lead = expt;
1243 					while (*grouping != CHAR_MAX) {
1244 						if (lead <= *grouping)
1245 							break;
1246 						lead -= *grouping;
1247 						if (*(grouping+1)) {
1248 							nseps++;
1249 							grouping++;
1250 						} else
1251 							nrepeats++;
1252 					}
1253 					size += nseps + nrepeats;
1254 				} else
1255 					lead = expt;
1256 			}
1257 			break;
1258 #endif /* !NO_FLOATING_POINT */
1259 		case 'n':
1260 			/*
1261 			 * Assignment-like behavior is specified if the
1262 			 * value overflows or is otherwise unrepresentable.
1263 			 * C99 says to use `signed char' for %hhn conversions.
1264 			 */
1265 			if (flags & LLONGINT)
1266 				*GETARG(long long *) = ret;
1267 			else if (flags & SIZET)
1268 				*GETARG(ssize_t *) = (ssize_t)ret;
1269 			else if (flags & PTRDIFFT)
1270 				*GETARG(ptrdiff_t *) = ret;
1271 			else if (flags & INTMAXT)
1272 				*GETARG(intmax_t *) = ret;
1273 			else if (flags & LONGINT)
1274 				*GETARG(long *) = ret;
1275 			else if (flags & SHORTINT)
1276 				*GETARG(short *) = ret;
1277 			else if (flags & CHARINT)
1278 				*GETARG(signed char *) = ret;
1279 			else
1280 				*GETARG(int *) = ret;
1281 			continue;	/* no output */
1282 		case 'O':
1283 			flags |= LONGINT;
1284 			/*FALLTHROUGH*/
1285 		case 'o':
1286 			if (flags & INTMAX_SIZE)
1287 				ujval = UJARG();
1288 			else
1289 				ulval = UARG();
1290 			base = 8;
1291 			goto nosign;
1292 		case 'p':
1293 			/*-
1294 			 * ``The argument shall be a pointer to void.  The
1295 			 * value of the pointer is converted to a sequence
1296 			 * of printable characters, in an implementation-
1297 			 * defined manner.''
1298 			 *	-- ANSI X3J11
1299 			 */
1300 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1301 			base = 16;
1302 			xdigs = xdigs_lower;
1303 			flags = flags | INTMAXT;
1304 			ox[1] = 'x';
1305 			goto nosign;
1306 		case 'S':
1307 			flags |= LONGINT;
1308 			/*FALLTHROUGH*/
1309 		case 's':
1310 			if ((flags & LONGINT) != MULTI) {
1311 				if ((result = GETARG(CHAR_T *)) == NULL)
1312 					result = STRCONST("(null)");
1313 			} else {
1314 				MCHAR_T *mc;
1315 
1316 				if (convbuf != NULL)
1317 					free(convbuf);
1318 				if ((mc = GETARG(MCHAR_T *)) == NULL)
1319 					result = STRCONST("(null)");
1320 				else {
1321 					convbuf = SCONV(mc, prec);
1322 					if (convbuf == NULL) {
1323 						fp->_flags |= __SERR;
1324 						goto error;
1325 					}
1326 					result = convbuf;
1327 				}
1328 			}
1329 
1330 			if (prec >= 0) {
1331 				/*
1332 				 * can't use STRLEN; can only look for the
1333 				 * NUL in the first `prec' characters, and
1334 				 * STRLEN() will go further.
1335 				 */
1336 				CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
1337 
1338 				if (p != NULL) {
1339 					_DIAGASSERT(__type_fit(int,
1340 					    p - result));
1341 					size = (int)(p - result);
1342 					if (size > prec)
1343 						size = prec;
1344 				} else
1345 					size = prec;
1346 			} else {
1347 				size_t rlen = STRLEN(result);
1348 				_DIAGASSERT(__type_fit(int, rlen));
1349 				size = (int)rlen;
1350 			}
1351 			sign = '\0';
1352 			break;
1353 		case 'U':
1354 			flags |= LONGINT;
1355 			/*FALLTHROUGH*/
1356 		case 'u':
1357 			if (flags & INTMAX_SIZE)
1358 				ujval = UJARG();
1359 			else
1360 				ulval = UARG();
1361 			base = 10;
1362 			goto nosign;
1363 		case 'X':
1364 			xdigs = xdigs_upper;
1365 			goto hex;
1366 		case 'x':
1367 			xdigs = xdigs_lower;
1368 hex:
1369 			if (flags & INTMAX_SIZE)
1370 				ujval = UJARG();
1371 			else
1372 				ulval = UARG();
1373 			base = 16;
1374 			/* leading 0x/X only if non-zero */
1375 			if (flags & ALT &&
1376 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1377 				ox[1] = ch;
1378 
1379 			flags &= ~GROUPING;
1380 			/* unsigned conversions */
1381 nosign:			sign = '\0';
1382 			/*-
1383 			 * ``... diouXx conversions ... if a precision is
1384 			 * specified, the 0 flag will be ignored.''
1385 			 *	-- ANSI X3J11
1386 			 */
1387 number:			if ((dprec = prec) >= 0)
1388 				flags &= ~ZEROPAD;
1389 
1390 			/*-
1391 			 * ``The result of converting a zero value with an
1392 			 * explicit precision of zero is no characters.''
1393 			 *	-- ANSI X3J11
1394 			 *
1395 			 * ``The C Standard is clear enough as is.  The call
1396 			 * printf("%#.0o", 0) should print 0.''
1397 			 *	-- Defect Report #151
1398 			 */
1399 			result = cp = buf + BUF;
1400 			if (flags & INTMAX_SIZE) {
1401 				if (ujval != 0 || prec != 0 ||
1402 				    (flags & ALT && base == 8))
1403 					result = __ujtoa(ujval, cp, base,
1404 					    flags & ALT, xdigs,
1405 					    flags & GROUPING, thousands_sep,
1406 					    grouping);
1407 			} else {
1408 				if (ulval != 0 || prec != 0 ||
1409 				    (flags & ALT && base == 8))
1410 					result = __ultoa(ulval, cp, base,
1411 					    flags & ALT, xdigs,
1412 					    flags & GROUPING, thousands_sep,
1413 					    grouping);
1414 			}
1415 			_DIAGASSERT(__type_fit(int, buf + BUF - result));
1416 			size = (int)(buf + BUF - result);
1417 			if (size > BUF)	/* should never happen */
1418 				abort();
1419 			break;
1420 		default:	/* "%?" prints ?, unless ? is NUL */
1421 			if (ch == '\0')
1422 				goto done;
1423 			/* pretend it was %c with argument ch */
1424 			*buf = ch;
1425 			result = buf;
1426 			size = 1;
1427 			sign = '\0';
1428 			break;
1429 		}
1430 
1431 		/*
1432 		 * All reasonable formats wind up here.  At this point, `result'
1433 		 * points to a string which (if not flags&LADJUST) should be
1434 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1435 		 * first be prefixed by any sign or other prefix; otherwise,
1436 		 * it should be blank padded before the prefix is emitted.
1437 		 * After any left-hand padding and prefixing, emit zeroes
1438 		 * required by a decimal [diouxX] precision, then print the
1439 		 * string proper, then emit zeroes required by any leftover
1440 		 * floating precision; finally, if LADJUST, pad with blanks.
1441 		 *
1442 		 * Compute actual size, so we know how much to pad.
1443 		 * size excludes decimal prec; realsz includes it.
1444 		 */
1445 		realsz = dprec > size ? dprec : size;
1446 		if (sign)
1447 			realsz++;
1448 		if (ox[1])
1449 			realsz += 2;
1450 
1451 		prsize = width > realsz ? width : realsz;
1452 		if ((unsigned)ret + prsize > INT_MAX) {
1453 			ret = END_OF_FILE;
1454 			goto error;
1455 		}
1456 
1457 		/* right-adjusting blank padding */
1458 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1459 			PAD(width - realsz, blanks);
1460 
1461 		/* prefix */
1462 		if (sign)
1463 			PRINT(&sign, 1);
1464 
1465 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1466 			ox[0] = '0';
1467 			PRINT(ox, 2);
1468 		}
1469 
1470 		/* right-adjusting zero padding */
1471 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1472 			PAD(width - realsz, zeroes);
1473 
1474 		/* leading zeroes from decimal precision */
1475 		PAD(dprec - size, zeroes);
1476 
1477 		/* the string or number proper */
1478 #ifndef NO_FLOATING_POINT
1479 		if ((flags & FPT) == 0) {
1480 			PRINT(result, size);
1481 		} else {	/* glue together f_p fragments */
1482 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1483 				if (expt <= 0) {
1484 					PRINT(zeroes, 1);
1485 					if (prec || flags & ALT)
1486 						PRINT(decimal_point, 1);
1487 					PAD(-expt, zeroes);
1488 					/* already handled initial 0's */
1489 					prec += expt;
1490 				} else {
1491 					PRINTANDPAD(result, convbuf + ndig,
1492 					    lead, zeroes);
1493 					result += lead;
1494 					if (grouping) {
1495 						while (nseps>0 || nrepeats>0) {
1496 							if (nrepeats > 0)
1497 								nrepeats--;
1498 							else {
1499 								grouping--;
1500 								nseps--;
1501 							}
1502 							PRINT(&thousands_sep,
1503 							    1);
1504 							PRINTANDPAD(result,
1505 							    convbuf + ndig,
1506 							    *grouping, zeroes);
1507 							result += *grouping;
1508 						}
1509 						if (result > convbuf + ndig)
1510 							result = convbuf + ndig;
1511 					}
1512 					if (prec || flags & ALT) {
1513 						buf[0] = *decimal_point;
1514 						PRINT(buf, 1);
1515 					}
1516 				}
1517 				PRINTANDPAD(result, convbuf + ndig, prec,
1518 				    zeroes);
1519 			} else {	/* %[eE] or sufficiently long %[gG] */
1520 				if (prec > 1 || flags & ALT) {
1521 					buf[0] = *result++;
1522 					buf[1] = *decimal_point;
1523 					PRINT(buf, 2);
1524 					PRINT(result, ndig-1);
1525 					PAD(prec - ndig, zeroes);
1526 				} else	/* XeYYY */
1527 					PRINT(result, 1);
1528 				PRINT(expstr, expsize);
1529 			}
1530 		}
1531 #else
1532 		PRINT(result, size);
1533 #endif
1534 		/* left-adjusting padding (always blank) */
1535 		if (flags & LADJUST)
1536 			PAD(width - realsz, blanks);
1537 
1538 		/* finally, adjust ret */
1539 		ret += prsize;
1540 		FLUSH();
1541 	}
1542 done:
1543 	FLUSH();
1544 error:
1545 	va_end(orgap);
1546 	if (convbuf != NULL)
1547 		free(convbuf);
1548 	if (__sferror(fp))
1549 		ret = END_OF_FILE;
1550 	if ((argtable != NULL) && (argtable != statargtable))
1551 		free (argtable);
1552 	return ret;
1553 	/* NOTREACHED */
1554 oomem:
1555 	errno = ENOMEM;
1556 	ret = END_OF_FILE;
1557 	goto error;
1558 }
1559 
1560 /*
1561  * Find all arguments when a positional parameter is encountered.  Returns a
1562  * table, indexed by argument number, of pointers to each arguments.  The
1563  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1564  * It will be replaces with a malloc-ed one if it overflows.
1565  */
1566 static int
1567 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
1568 {
1569 	CHAR_T *fmt;		/* format string */
1570 	int ch;			/* character from fmt */
1571 	size_t n, n2;		/* handy index (short term usage) */
1572 	CHAR_T *cp;		/* handy char pointer (short term usage) */
1573 	int flags;		/* flags as above */
1574 	enum typeid *typetable; /* table of types */
1575 	enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1576 	size_t tablesize;	/* current size of type table */
1577 	size_t tablemax;	/* largest used index in table */
1578 	size_t nextarg;		/* 1-based argument index */
1579 	size_t nitems;		/* number of items we picked from the stack */
1580 
1581 	/*
1582 	 * Add an argument type to the table, expanding if necessary.
1583 	 * Check for overflow.
1584 	 */
1585 #define ADDTYPE(type) \
1586 	do { \
1587 		if (nextarg > SIZE_MAX / sizeof(**argtable)) { \
1588 			if (typetable != stattypetable) \
1589 				free(typetable); \
1590 			return -1; \
1591 		} \
1592 		if (nextarg >= tablesize) \
1593 			if (__grow_type_table(nextarg, &typetable, \
1594 			    &tablesize) == -1) \
1595 				return -1; \
1596 		if (nextarg > tablemax) \
1597 			tablemax = nextarg; \
1598 		typetable[nextarg++] = type; \
1599 		nitems++; \
1600 	} while (/*CONSTCOND*/0)
1601 
1602 #define	ADDSARG() \
1603 	do { \
1604 		if (flags & INTMAXT)  \
1605 			ADDTYPE(T_INTMAXT); \
1606 		else if (flags & SIZET)  \
1607 			ADDTYPE(T_SSIZET); \
1608 		else if (flags & PTRDIFFT) \
1609 			ADDTYPE(T_PTRDIFFT); \
1610 		else if (flags & LLONGINT) \
1611 			ADDTYPE(T_LLONG); \
1612 		else if (flags & LONGINT) \
1613 			ADDTYPE(T_LONG); \
1614 		else \
1615 			ADDTYPE(T_INT); \
1616 	} while (/*CONSTCOND*/0)
1617 
1618 #define	ADDUARG() \
1619 	do { \
1620 		if (flags & INTMAXT)  \
1621 			ADDTYPE(T_UINTMAXT); \
1622 		else if (flags & SIZET)  \
1623 			ADDTYPE(T_SIZET); \
1624 		else if (flags & PTRDIFFT) \
1625 			ADDTYPE(T_PTRDIFFT); \
1626 		else if (flags & LLONGINT) \
1627 			ADDTYPE(T_U_LLONG); \
1628 		else if (flags & LONGINT) \
1629 			ADDTYPE(T_U_LONG); \
1630 		else \
1631 			ADDTYPE(T_U_INT); \
1632 	} while (/*CONSTCOND*/0)
1633 	/*
1634 	 * Add * arguments to the type array.
1635 	 */
1636 #define ADDASTER() \
1637 	n2 = 0; \
1638 	cp = fmt; \
1639 	while (is_digit(*cp)) { \
1640 		n2 = 10 * n2 + to_digit(*cp); \
1641 		cp++; \
1642 	} \
1643 	if (*cp == '$') { \
1644 		size_t hold = nextarg; \
1645 		nextarg = n2; \
1646 		ADDTYPE(T_INT); \
1647 		nextarg = hold; \
1648 		fmt = ++cp; \
1649 	} else { \
1650 		ADDTYPE(T_INT); \
1651 	}
1652 	fmt = (CHAR_T *)__UNCONST(fmt0);
1653 	memset(stattypetable, 0, sizeof(stattypetable));
1654 	typetable = stattypetable;
1655 	tablesize = STATIC_ARG_TBL_SIZE;
1656 	tablemax = 0;
1657 	nextarg = 1;
1658 	nitems = 1;
1659 
1660 	/*
1661 	 * Scan the format for conversions (`%' character).
1662 	 */
1663 	for (;;) {
1664 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1665 			/* void */;
1666 		if (ch == '\0')
1667 			goto done;
1668 		fmt++;		/* skip over '%' */
1669 
1670 		flags = 0;
1671 
1672 rflag:		ch = *fmt++;
1673 reswitch:	switch (ch) {
1674 		case ' ':
1675 		case '#':
1676 			goto rflag;
1677 		case '*':
1678 			ADDASTER ();
1679 			goto rflag;
1680 		case '-':
1681 		case '+':
1682 		case '\'':
1683 			goto rflag;
1684 		case '.':
1685 			if ((ch = *fmt++) == '*') {
1686 				ADDASTER ();
1687 				goto rflag;
1688 			}
1689 			while (is_digit(ch)) {
1690 				ch = *fmt++;
1691 			}
1692 			goto reswitch;
1693 		case '0':
1694 			goto rflag;
1695 		case '1': case '2': case '3': case '4':
1696 		case '5': case '6': case '7': case '8': case '9':
1697 			n = 0;
1698 			do {
1699 				n = 10 * n + to_digit(ch);
1700 				ch = *fmt++;
1701 			} while (is_digit(ch));
1702 			if (ch == '$') {
1703 				nextarg = n;
1704 				goto rflag;
1705 			}
1706 			goto reswitch;
1707 #ifndef NO_FLOATING_POINT
1708 		case 'L':
1709 			flags |= LONGDBL;
1710 			goto rflag;
1711 #endif
1712 		case 'h':
1713 			if (flags & SHORTINT) {
1714 				flags &= ~SHORTINT;
1715 				flags |= CHARINT;
1716 			} else
1717 				flags |= SHORTINT;
1718 			goto rflag;
1719 		case 'j':
1720 			flags |= INTMAXT;
1721 			goto rflag;
1722 		case 'l':
1723 			if (flags & LONGINT) {
1724 				flags &= ~LONGINT;
1725 				flags |= LLONGINT;
1726 			} else
1727 				flags |= LONGINT;
1728 			goto rflag;
1729 		case 'q':
1730 			flags |= LLONGINT;	/* not necessarily */
1731 			goto rflag;
1732 		case 't':
1733 			flags |= PTRDIFFT;
1734 			goto rflag;
1735 		case 'z':
1736 			flags |= SIZET;
1737 			goto rflag;
1738 		case 'C':
1739 			flags |= LONGINT;
1740 			/*FALLTHROUGH*/
1741 		case 'c':
1742 			if (flags & LONGINT)
1743 				ADDTYPE(T_WINT);
1744 			else
1745 				ADDTYPE(T_INT);
1746 			break;
1747 		case 'D':
1748 			flags |= LONGINT;
1749 			/*FALLTHROUGH*/
1750 		case 'd':
1751 		case 'i':
1752 			ADDSARG();
1753 			break;
1754 #ifndef NO_FLOATING_POINT
1755 		case 'a':
1756 		case 'A':
1757 		case 'e':
1758 		case 'E':
1759 		case 'f':
1760 		case 'g':
1761 		case 'G':
1762 			if (flags & LONGDBL)
1763 				ADDTYPE(T_LONG_DOUBLE);
1764 			else
1765 				ADDTYPE(T_DOUBLE);
1766 			break;
1767 #endif /* !NO_FLOATING_POINT */
1768 		case 'n':
1769 			if (flags & INTMAXT)
1770 				ADDTYPE(TP_INTMAXT);
1771 			else if (flags & PTRDIFFT)
1772 				ADDTYPE(TP_PTRDIFFT);
1773 			else if (flags & SIZET)
1774 				ADDTYPE(TP_SIZET);
1775 			else if (flags & LLONGINT)
1776 				ADDTYPE(TP_LLONG);
1777 			else if (flags & LONGINT)
1778 				ADDTYPE(TP_LONG);
1779 			else if (flags & SHORTINT)
1780 				ADDTYPE(TP_SHORT);
1781 			else if (flags & CHARINT)
1782 				ADDTYPE(TP_SCHAR);
1783 			else
1784 				ADDTYPE(TP_INT);
1785 			continue;	/* no output */
1786 		case 'O':
1787 			flags |= LONGINT;
1788 			/*FALLTHROUGH*/
1789 		case 'o':
1790 			ADDUARG();
1791 			break;
1792 		case 'p':
1793 			ADDTYPE(TP_VOID);
1794 			break;
1795 		case 'S':
1796 			flags |= LONGINT;
1797 			/*FALLTHROUGH*/
1798 		case 's':
1799 			if (flags & LONGINT)
1800 				ADDTYPE(TP_WCHAR);
1801 			else
1802 				ADDTYPE(TP_CHAR);
1803 			break;
1804 		case 'U':
1805 			flags |= LONGINT;
1806 			/*FALLTHROUGH*/
1807 		case 'u':
1808 		case 'X':
1809 		case 'x':
1810 			ADDUARG();
1811 			break;
1812 		default:	/* "%?" prints ?, unless ? is NUL */
1813 			if (ch == '\0')
1814 				goto done;
1815 			break;
1816 		}
1817 	}
1818 done:
1819 	/*
1820 	 * nitems contains the number of arguments we picked from the stack.
1821 	 * If tablemax is larger, this means that some positional argument,
1822 	 * tried to pick an argument the number of arguments possibly supplied.
1823 	 * Since positional arguments are typically used to swap the order of
1824 	 * the printf arguments and not to pick random arguments from strange
1825 	 * positions in the stack, we assume that if the positional argument
1826 	 * is trying to pick beyond the end of arguments, then this is wrong.
1827 	 * Alternatively we could find a way to figure out when va_arg() runs
1828 	 * out, but how to do that?
1829 	 */
1830 	if (nitems < tablemax) {
1831 		if (typetable != stattypetable)
1832 			free(typetable);
1833 		return -1;
1834 	}
1835 	/*
1836 	 * Build the argument table.
1837 	 */
1838 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1839 		*argtable = malloc(sizeof(**argtable) * (tablemax + 1));
1840 		if (*argtable == NULL) {
1841 			free(typetable);
1842 			return -1;
1843 		}
1844 	}
1845 
1846 	(*argtable) [0].intarg = 0;
1847 	for (n = 1; n <= tablemax; n++) {
1848 		switch (typetable [n]) {
1849 		    case T_UNUSED: /* whoops! */
1850 			(*argtable) [n].intarg = va_arg (ap, int);
1851 			break;
1852 		    case TP_SCHAR:
1853 			(*argtable) [n].pschararg = va_arg (ap, signed char *);
1854 			break;
1855 		    case TP_SHORT:
1856 			(*argtable) [n].pshortarg = va_arg (ap, short *);
1857 			break;
1858 		    case T_INT:
1859 			(*argtable) [n].intarg = va_arg (ap, int);
1860 			break;
1861 		    case T_U_INT:
1862 			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
1863 			break;
1864 		    case TP_INT:
1865 			(*argtable) [n].pintarg = va_arg (ap, int *);
1866 			break;
1867 		    case T_LONG:
1868 			(*argtable) [n].longarg = va_arg (ap, long);
1869 			break;
1870 		    case T_U_LONG:
1871 			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1872 			break;
1873 		    case TP_LONG:
1874 			(*argtable) [n].plongarg = va_arg (ap, long *);
1875 			break;
1876 		    case T_LLONG:
1877 			(*argtable) [n].longlongarg = va_arg (ap, long long);
1878 			break;
1879 		    case T_U_LLONG:
1880 			(*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1881 			break;
1882 		    case TP_LLONG:
1883 			(*argtable) [n].plonglongarg = va_arg (ap, long long *);
1884 			break;
1885 		    case T_PTRDIFFT:
1886 			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1887 			break;
1888 		    case TP_PTRDIFFT:
1889 			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1890 			break;
1891 		    case T_SSIZET:
1892 			(*argtable) [n].ssizearg = va_arg (ap, ssize_t);
1893 			break;
1894 		    case T_SIZET:
1895 			(*argtable) [n].sizearg = va_arg (ap, size_t);
1896 			break;
1897 		    case TP_SIZET:
1898 			(*argtable) [n].psizearg = va_arg (ap, size_t *);
1899 			break;
1900 		    case T_INTMAXT:
1901 			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1902 			break;
1903 		    case T_UINTMAXT:
1904 			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1905 			break;
1906 		    case TP_INTMAXT:
1907 			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1908 			break;
1909 		    case T_DOUBLE:
1910 #ifndef NO_FLOATING_POINT
1911 			(*argtable) [n].doublearg = va_arg (ap, double);
1912 #endif
1913 			break;
1914 		    case T_LONG_DOUBLE:
1915 #ifndef NO_FLOATING_POINT
1916 			(*argtable) [n].longdoublearg = va_arg (ap, long double);
1917 #endif
1918 			break;
1919 		    case TP_CHAR:
1920 			(*argtable) [n].pchararg = va_arg (ap, char *);
1921 			break;
1922 		    case TP_VOID:
1923 			(*argtable) [n].pvoidarg = va_arg (ap, void *);
1924 			break;
1925 		    case T_WINT:
1926 			(*argtable) [n].wintarg = va_arg (ap, wint_t);
1927 			break;
1928 		    case TP_WCHAR:
1929 			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1930 			break;
1931 		}
1932 	}
1933 
1934 	if (typetable != stattypetable)
1935 		free (typetable);
1936 	return 0;
1937 }
1938 
1939 /*
1940  * Increase the size of the type table.
1941  */
1942 static int
1943 __grow_type_table (size_t nextarg, enum typeid **typetable, size_t *tablesize)
1944 {
1945 	enum typeid *const oldtable = *typetable;
1946 	const size_t oldsize = *tablesize;
1947 	enum typeid *newtable;
1948 	size_t newsize = oldsize * 2;
1949 
1950 	if (newsize < nextarg + 1)
1951 		newsize = nextarg + 1;
1952 	if (oldsize == STATIC_ARG_TBL_SIZE) {
1953 		if ((newtable = malloc(newsize * sizeof(*newtable))) == NULL)
1954 			return -1;
1955 		memcpy(newtable, oldtable, oldsize * sizeof(*newtable));
1956 	} else {
1957 		newtable = realloc(oldtable, newsize * sizeof(*newtable));
1958 		if (newtable == NULL) {
1959 			free(oldtable);
1960 			return -1;
1961 		}
1962 	}
1963 	memset(&newtable[oldsize], 0, (newsize - oldsize) * sizeof(*newtable));
1964 
1965 	*typetable = newtable;
1966 	*tablesize = newsize;
1967 	return 0;
1968 }
1969 
1970 
1971 #ifndef NO_FLOATING_POINT
1972 #ifndef WIDE_DOUBLE
1973 static char *
1974 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1975     int *length)
1976 {
1977 	int mode, dsgn;
1978 	char *digits, *bp, *rve;
1979 
1980 	_DIAGASSERT(decpt != NULL);
1981 	_DIAGASSERT(length != NULL);
1982 	_DIAGASSERT(sign != NULL);
1983 
1984 	if (ch == 'f') {
1985 		mode = 3;		/* ndigits after the decimal point */
1986 	} else {
1987 		/* To obtain ndigits after the decimal point for the 'e'
1988 		 * and 'E' formats, round to ndigits + 1 significant
1989 		 * figures.
1990 		 */
1991 		if (ch == 'e' || ch == 'E') {
1992 			ndigits++;
1993 		}
1994 		mode = 2;		/* ndigits significant digits */
1995 	}
1996 
1997 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1998 	if (digits == NULL)
1999 		return NULL;
2000 	if (dsgn) {
2001 		value = -value;
2002 		*sign = '-';
2003 	} else
2004 		*sign = '\000';
2005 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
2006 		bp = digits + ndigits;
2007 		if (ch == 'f') {
2008 			if (*digits == '0' && value)
2009 				*decpt = -ndigits + 1;
2010 			bp += *decpt;
2011 		}
2012 		if (value == 0)	/* kludge for __dtoa irregularity */
2013 			rve = bp;
2014 		while (rve < bp)
2015 			*rve++ = '0';
2016 	}
2017 	*length = rve - digits;
2018 	return digits;
2019 }
2020 #endif
2021 
2022 static int
2023 exponent(CHAR_T *p0, int expo, int fmtch)
2024 {
2025 	CHAR_T *p, *t;
2026 	CHAR_T expbuf[MAXEXPDIG];
2027 
2028 	p = p0;
2029 	*p++ = fmtch;
2030 	if (expo < 0) {
2031 		expo = -expo;
2032 		*p++ = '-';
2033 	}
2034 	else
2035 		*p++ = '+';
2036 	t = expbuf + MAXEXPDIG;
2037 	if (expo > 9) {
2038 		do {
2039 			*--t = to_char(expo % 10);
2040 		} while ((expo /= 10) > 9);
2041 		*--t = to_char(expo);
2042 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
2043 	}
2044 	else {
2045 		/*
2046 		 * Exponents for decimal floating point conversions
2047 		 * (%[eEgG]) must be at least two characters long,
2048 		 * whereas exponents for hexadecimal conversions can
2049 		 * be only one character long.
2050 		 */
2051 		if (fmtch == 'e' || fmtch == 'E')
2052 			*p++ = '0';
2053 		*p++ = to_char(expo);
2054 	}
2055 	_DIAGASSERT(__type_fit(int, p - p0));
2056 	return (int)(p - p0);
2057 }
2058 #endif /* !NO_FLOATING_POINT */
2059