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