xref: /netbsd-src/lib/libc/stdio/vfwprintf.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: vfwprintf.c,v 1.21 2010/07/31 08:47:34 tnozaki 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.21 2010/07/31 08:47:34 tnozaki 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, 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(int, enum typeid **, int *);
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, (const wchar_t **)&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, (const wchar_t **)&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 	n2 = (ep) - (p);       			\
728 	if (n2 > (len))				\
729 		n2 = (len);			\
730 	if (n2 > 0)				\
731 		PRINT((p), n2);			\
732 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
733 } while(/*CONSTCOND*/0)
734 
735 	/*
736 	 * Get the argument indexed by nextarg.   If the argument table is
737 	 * built, use it to get the argument.  If its not, get the next
738 	 * argument (and arguments must be gotten sequentially).
739 	 */
740 #define GETARG(type) \
741 	((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
742 	    (nextarg++, va_arg(ap, type)))
743 
744 	/*
745 	 * To extend shorts properly, we need both signed and unsigned
746 	 * argument extraction methods.
747 	 */
748 #define	SARG() \
749 	(flags&LONGINT ? GETARG(long) : \
750 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
751 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
752 	    (long)GETARG(int))
753 #define	UARG() \
754 	(flags&LONGINT ? GETARG(u_long) : \
755 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
756 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
757 	    (u_long)GETARG(u_int))
758 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
759 #define SJARG() \
760 	(flags&INTMAXT ? GETARG(intmax_t) : \
761 	    flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
762 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
763 	    (intmax_t)GETARG(long long))
764 #define	UJARG() \
765 	(flags&INTMAXT ? GETARG(uintmax_t) : \
766 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
767 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
768 	    (uintmax_t)GETARG(unsigned long long))
769 
770 	/*
771 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
772 	 * that the argument can be gotten once the type is determined.
773 	 */
774 #define GETASTER(val) \
775 	n2 = 0; \
776 	cp = fmt; \
777 	while (is_digit(*cp)) { \
778 		n2 = 10 * n2 + to_digit(*cp); \
779 		cp++; \
780 	} \
781 	if (*cp == '$') { \
782 		int hold = nextarg; \
783 		if (argtable == NULL) { \
784 			argtable = statargtable; \
785 			if (__find_arguments(fmt0, orgap, &argtable) == -1) \
786 				goto oomem; \
787 		} \
788 		nextarg = n2; \
789 		val = GETARG (int); \
790 		nextarg = hold; \
791 		fmt = ++cp; \
792 	} else { \
793 		val = GETARG (int); \
794 	}
795 
796 	_DIAGASSERT(fp != NULL);
797 	_DIAGASSERT(fmt0 != NULL);
798 
799 	_SET_ORIENTATION(fp, -1);
800 
801 	ndig = -1;	/* XXX gcc */
802 
803 	thousands_sep = '\0';
804 	grouping = NULL;
805 #ifndef NO_FLOATING_POINT
806 	decimal_point = localeconv()->decimal_point;
807 	expsize = 0;		/* XXXGCC -Wuninitialized [sh3,m68000] */
808 #endif
809 	convbuf = NULL;
810 	/* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
811 	if (cantwrite(fp)) {
812 		errno = EBADF;
813 		return (END_OF_FILE);
814 	}
815 
816 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
817 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
818 	    __sfileno(fp) != -1)
819 		return (__sbprintf(fp, fmt0, ap));
820 
821 	fmt = (CHAR_T *)__UNCONST(fmt0);
822 	argtable = NULL;
823 	nextarg = 1;
824 	va_copy(orgap, ap);
825 #ifdef NARROW
826 	uio.uio_iov = iovp = iov;
827 	uio.uio_resid = 0;
828 	uio.uio_iovcnt = 0;
829 #endif
830 	ret = 0;
831 
832 	/*
833 	 * Scan the format for conversions (`%' character).
834 	 */
835 	for (;;) {
836 		const CHAR_T *result;
837 
838 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
839 			continue;
840 		if ((n = fmt - cp) != 0) {
841 			if ((unsigned)ret + n > INT_MAX) {
842 				ret = END_OF_FILE;
843 				goto error;
844 			}
845 			PRINT(cp, n);
846 			ret += n;
847 		}
848 		if (ch == '\0')
849 			goto done;
850 		fmt++;		/* skip over '%' */
851 
852 		flags = 0;
853 		dprec = 0;
854 		width = 0;
855 		prec = -1;
856 		sign = '\0';
857 		ox[1] = '\0';
858 		expchar = '\0';
859 		lead = 0;
860 		nseps = nrepeats = 0;
861 		ulval = 0;
862 		ujval = 0;
863 		xdigs = NULL;
864 
865 rflag:		ch = *fmt++;
866 reswitch:	switch (ch) {
867 		case ' ':
868 			/*-
869 			 * ``If the space and + flags both appear, the space
870 			 * flag will be ignored.''
871 			 *	-- ANSI X3J11
872 			 */
873 			if (!sign)
874 				sign = ' ';
875 			goto rflag;
876 		case '#':
877 			flags |= ALT;
878 			goto rflag;
879 		case '*':
880 			/*-
881 			 * ``A negative field width argument is taken as a
882 			 * - flag followed by a positive field width.''
883 			 *	-- ANSI X3J11
884 			 * They don't exclude field widths read from args.
885 			 */
886 			GETASTER (width);
887 			if (width >= 0)
888 				goto rflag;
889 			width = -width;
890 			/* FALLTHROUGH */
891 		case '-':
892 			flags |= LADJUST;
893 			goto rflag;
894 		case '+':
895 			sign = '+';
896 			goto rflag;
897 		case '\'':
898 			flags |= GROUPING;
899 			thousands_sep = *(localeconv()->thousands_sep);
900 			grouping = localeconv()->grouping;
901 			/* If the locale doesn't define the above, use sane
902 			 * defaults - otherwise silly things happen! */
903 			if (thousands_sep == 0)
904 				thousands_sep = ',';
905 			if (!grouping || !*grouping)
906 				grouping = "\3";
907 			goto rflag;
908 		case '.':
909 			if ((ch = *fmt++) == '*') {
910 				GETASTER (prec);
911 				goto rflag;
912 			}
913 			prec = 0;
914 			while (is_digit(ch)) {
915 				prec = 10 * prec + to_digit(ch);
916 				ch = *fmt++;
917 			}
918 			goto reswitch;
919 		case '0':
920 			/*-
921 			 * ``Note that 0 is taken as a flag, not as the
922 			 * beginning of a field width.''
923 			 *	-- ANSI X3J11
924 			 */
925 			flags |= ZEROPAD;
926 			goto rflag;
927 		case '1': case '2': case '3': case '4':
928 		case '5': case '6': case '7': case '8': case '9':
929 			n = 0;
930 			do {
931 				n = 10 * n + to_digit(ch);
932 				ch = *fmt++;
933 			} while (is_digit(ch));
934 			if (ch == '$') {
935 				nextarg = n;
936 				if (argtable == NULL) {
937 					argtable = statargtable;
938 					if (__find_arguments(fmt0, orgap,
939 					    &argtable) == -1)
940 						goto oomem;
941 				}
942 				goto rflag;
943 			}
944 			width = n;
945 			goto reswitch;
946 #ifndef NO_FLOATING_POINT
947 		case 'L':
948 			flags |= LONGDBL;
949 			goto rflag;
950 #endif
951 		case 'h':
952 			if (flags & SHORTINT) {
953 				flags &= ~SHORTINT;
954 				flags |= CHARINT;
955 			} else
956 				flags |= SHORTINT;
957 			goto rflag;
958 		case 'j':
959 			flags |= INTMAXT;
960 			goto rflag;
961 		case 'l':
962 			if (flags & LONGINT) {
963 				flags &= ~LONGINT;
964 				flags |= LLONGINT;
965 			} else
966 				flags |= LONGINT;
967 			goto rflag;
968 		case 'q':
969 			flags |= LLONGINT;	/* not necessarily */
970 			goto rflag;
971 		case 't':
972 			flags |= PTRDIFFT;
973 			goto rflag;
974 		case 'z':
975 			flags |= SIZET;
976 			goto rflag;
977 		case 'C':
978 			flags |= LONGINT;
979 			/*FALLTHROUGH*/
980 		case 'c':
981 #ifdef NARROW
982 			if (flags & LONGINT) {
983 				static const mbstate_t initial;
984 				mbstate_t mbs;
985 				size_t mbseqlen;
986 
987 				mbs = initial;
988 				mbseqlen = wcrtomb(buf,
989 				    (wchar_t)GETARG(wint_t), &mbs);
990 				if (mbseqlen == (size_t)-1) {
991 					fp->_flags |= __SERR;
992 					goto error;
993 				}
994 				size = (int)mbseqlen;
995 			} else {
996 				*buf = GETARG(int);
997 				size = 1;
998 			}
999 #else
1000 			if (flags & LONGINT)
1001 				*buf = (wchar_t)GETARG(wint_t);
1002 			else
1003 				*buf = (wchar_t)btowc(GETARG(int));
1004 			size = 1;
1005 #endif
1006 			result = buf;
1007 			sign = '\0';
1008 			break;
1009 		case 'D':
1010 			flags |= LONGINT;
1011 			/*FALLTHROUGH*/
1012 		case 'd':
1013 		case 'i':
1014 			if (flags & INTMAX_SIZE) {
1015 				ujval = SJARG();
1016 				if ((intmax_t)ujval < 0) {
1017 					ujval = -ujval;
1018 					sign = '-';
1019 				}
1020 			} else {
1021 				ulval = SARG();
1022 				if ((long)ulval < 0) {
1023 					ulval = -ulval;
1024 					sign = '-';
1025 				}
1026 			}
1027 			base = 10;
1028 			goto number;
1029 #ifndef NO_FLOATING_POINT
1030 #ifdef WIDE_DOUBLE
1031 		case 'a':
1032 		case 'A':
1033 			if (ch == 'a') {
1034 				ox[1] = 'x';
1035 				xdigs = xdigs_lower;
1036 				expchar = 'p';
1037 			} else {
1038 				ox[1] = 'X';
1039 				xdigs = xdigs_upper;
1040 				expchar = 'P';
1041 			}
1042 			if (prec >= 0)
1043 				prec++;
1044 			if (flags & LONGDBL) {
1045 				fparg.ldbl = GETARG(long double);
1046 				dtoaresult =
1047 				    __hldtoa(fparg.ldbl, xdigs, prec,
1048 				        &expt, &signflag, &dtoaend);
1049 			} else {
1050 				fparg.dbl = GETARG(double);
1051 				dtoaresult =
1052 				    __hdtoa(fparg.dbl, xdigs, prec,
1053 				        &expt, &signflag, &dtoaend);
1054 			}
1055 			if (dtoaresult == NULL)
1056 				goto oomem;
1057 
1058 			if (prec < 0)
1059 				prec = dtoaend - dtoaresult;
1060 			if (expt == INT_MAX)
1061 				ox[1] = '\0';
1062 			ndig = dtoaend - dtoaresult;
1063 			if (convbuf != NULL)
1064 				free(convbuf);
1065 #ifndef NARROW
1066 			result = convbuf = __mbsconv(dtoaresult, -1);
1067 #else
1068 			/*XXX inefficient*/
1069 			result = convbuf = strdup(dtoaresult);
1070 #endif
1071 			if (result == NULL)
1072 				goto oomem;
1073 			__freedtoa(dtoaresult);
1074 			goto fp_common;
1075 		case 'e':
1076 		case 'E':
1077 			expchar = ch;
1078 			if (prec < 0)	/* account for digit before decpt */
1079 				prec = DEFPREC + 1;
1080 			else
1081 				prec++;
1082 			goto fp_begin;
1083 		case 'f':
1084 		case 'F':
1085 			expchar = '\0';
1086 			goto fp_begin;
1087 		case 'g':
1088 		case 'G':
1089 			expchar = ch - ('g' - 'e');
1090 			if (prec == 0)
1091 				prec = 1;
1092 fp_begin:
1093 			if (prec < 0)
1094 				prec = DEFPREC;
1095 			if (flags & LONGDBL) {
1096 				fparg.ldbl = GETARG(long double);
1097 				dtoaresult =
1098 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
1099 				    &expt, &signflag, &dtoaend);
1100 			} else {
1101 				fparg.dbl = GETARG(double);
1102 				dtoaresult =
1103 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
1104 				    &expt, &signflag, &dtoaend);
1105 				if (expt == 9999)
1106 					expt = INT_MAX;
1107 			}
1108 			if (dtoaresult == NULL)
1109 				goto oomem;
1110 			ndig = dtoaend - dtoaresult;
1111 			if (convbuf != NULL)
1112 				free(convbuf);
1113 #ifndef NARROW
1114 			result = convbuf = __mbsconv(dtoaresult, -1);
1115 #else
1116 			/*XXX inefficient*/
1117 			result = convbuf = strdup(dtoaresult);
1118 #endif
1119 			if (result == NULL)
1120 				goto oomem;
1121 			__freedtoa(dtoaresult);
1122 fp_common:
1123 			if (signflag)
1124 				sign = '-';
1125 			if (expt == INT_MAX) {	/* inf or nan */
1126 				if (*result == 'N') {
1127 					result = (ch >= 'a') ? STRCONST("nan") :
1128 					    STRCONST("NAN");
1129 					sign = '\0';
1130 				} else
1131 					result = (ch >= 'a') ? STRCONST("inf") :
1132 					    STRCONST("INF");
1133 				size = 3;
1134 				break;
1135 			}
1136 #else
1137 		case 'e':
1138 		case 'E':
1139 		case 'f':
1140 		case 'F':
1141 		case 'g':
1142 		case 'G':
1143 			if (prec == -1) {
1144 				prec = DEFPREC;
1145 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
1146 				prec = 1;
1147 			}
1148 
1149 			if (flags & LONGDBL) {
1150 				_double = (double) GETARG(long double);
1151 			} else {
1152 				_double = GETARG(double);
1153 			}
1154 
1155 			/* do this before tricky precision changes */
1156 			if (isinf(_double)) {
1157 				if (_double < 0)
1158 					sign = '-';
1159 				if (ch == 'E' || ch == 'F' || ch == 'G')
1160 					result = STRCONST("INF");
1161 				else
1162 					result = STRCONST("inf");
1163 				size = 3;
1164 				break;
1165 			}
1166 			if (isnan(_double)) {
1167 				if (ch == 'E' || ch == 'F' || ch == 'G')
1168 					result = STRCONST("NAN");
1169 				else
1170 					result = STRCONST("nan");
1171 				size = 3;
1172 				break;
1173 			}
1174 
1175 			flags |= FPT;
1176 			dtoaresult = cvt(_double, prec, flags, &softsign,
1177 			    &expt, ch, &ndig);
1178 			if (dtoaresult == NULL)
1179 				goto oomem;
1180 			if (convbuf != NULL)
1181 				free(convbuf);
1182 #ifndef NARROW
1183 			result = convbuf = __mbsconv(dtoaresult, -1);
1184 #else
1185 			/*XXX inefficient*/
1186 			result = convbuf = strdup(dtoaresult);
1187 #endif
1188 			if (result == NULL)
1189 				goto oomem;
1190 			__freedtoa(dtoaresult);
1191 			if (softsign)
1192 				sign = '-';
1193 #endif
1194 			flags |= FPT;
1195 			if (ch == 'g' || ch == 'G') {
1196 				if (expt > -4 && expt <= prec) {
1197 					/* Make %[gG] smell like %[fF] */
1198 					expchar = '\0';
1199 					if (flags & ALT)
1200 						prec -= expt;
1201 					else
1202 						prec = ndig - expt;
1203 					if (prec < 0)
1204 						prec = 0;
1205 				} else {
1206 					/*
1207 					 * Make %[gG] smell like %[eE], but
1208 					 * trim trailing zeroes if no # flag.
1209 					 */
1210 					if (!(flags & ALT))
1211 						prec = ndig;
1212 				}
1213 			}
1214 			if (expchar) {
1215 				expsize = exponent(expstr, expt - 1, expchar);
1216 				size = expsize + prec;
1217 				if (prec > 1 || flags & ALT)
1218 					++size;
1219 			} else {
1220 				/* space for digits before decimal point */
1221 				if (expt > 0)
1222 					size = expt;
1223 				else	/* "0" */
1224 					size = 1;
1225 				/* space for decimal pt and following digits */
1226 				if (prec || flags & ALT)
1227 					size += prec + 1;
1228 				if (grouping && expt > 0) {
1229 					/* space for thousands' grouping */
1230 					nseps = nrepeats = 0;
1231 					lead = expt;
1232 					while (*grouping != CHAR_MAX) {
1233 						if (lead <= *grouping)
1234 							break;
1235 						lead -= *grouping;
1236 						if (*(grouping+1)) {
1237 							nseps++;
1238 							grouping++;
1239 						} else
1240 							nrepeats++;
1241 					}
1242 					size += nseps + nrepeats;
1243 				} else
1244 					lead = expt;
1245 			}
1246 			break;
1247 #endif /* !NO_FLOATING_POINT */
1248 		case 'n':
1249 			/*
1250 			 * Assignment-like behavior is specified if the
1251 			 * value overflows or is otherwise unrepresentable.
1252 			 * C99 says to use `signed char' for %hhn conversions.
1253 			 */
1254 			if (flags & LLONGINT)
1255 				*GETARG(long long *) = ret;
1256 			else if (flags & SIZET)
1257 				*GETARG(ssize_t *) = (ssize_t)ret;
1258 			else if (flags & PTRDIFFT)
1259 				*GETARG(ptrdiff_t *) = ret;
1260 			else if (flags & INTMAXT)
1261 				*GETARG(intmax_t *) = ret;
1262 			else if (flags & LONGINT)
1263 				*GETARG(long *) = ret;
1264 			else if (flags & SHORTINT)
1265 				*GETARG(short *) = ret;
1266 			else if (flags & CHARINT)
1267 				*GETARG(signed char *) = ret;
1268 			else
1269 				*GETARG(int *) = ret;
1270 			continue;	/* no output */
1271 		case 'O':
1272 			flags |= LONGINT;
1273 			/*FALLTHROUGH*/
1274 		case 'o':
1275 			if (flags & INTMAX_SIZE)
1276 				ujval = UJARG();
1277 			else
1278 				ulval = UARG();
1279 			base = 8;
1280 			goto nosign;
1281 		case 'p':
1282 			/*-
1283 			 * ``The argument shall be a pointer to void.  The
1284 			 * value of the pointer is converted to a sequence
1285 			 * of printable characters, in an implementation-
1286 			 * defined manner.''
1287 			 *	-- ANSI X3J11
1288 			 */
1289 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1290 			base = 16;
1291 			xdigs = xdigs_lower;
1292 			flags = flags | INTMAXT;
1293 			ox[1] = 'x';
1294 			goto nosign;
1295 		case 'S':
1296 			flags |= LONGINT;
1297 			/*FALLTHROUGH*/
1298 		case 's':
1299 			if ((flags & LONGINT) != MULTI) {
1300 				if ((result = GETARG(CHAR_T *)) == NULL)
1301 					result = STRCONST("(null)");
1302 			} else {
1303 				MCHAR_T *mc;
1304 
1305 				if (convbuf != NULL)
1306 					free(convbuf);
1307 				if ((mc = GETARG(MCHAR_T *)) == NULL)
1308 					result = STRCONST("(null)");
1309 				else {
1310 					convbuf = SCONV(mc, prec);
1311 					if (convbuf == NULL) {
1312 						fp->_flags |= __SERR;
1313 						goto error;
1314 					}
1315 					result = convbuf;
1316 				}
1317 			}
1318 
1319 			if (prec >= 0) {
1320 				/*
1321 				 * can't use STRLEN; can only look for the
1322 				 * NUL in the first `prec' characters, and
1323 				 * STRLEN() will go further.
1324 				 */
1325 				CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
1326 
1327 				if (p != NULL) {
1328 					size = p - result;
1329 					if (size > prec)
1330 						size = prec;
1331 				} else
1332 					size = prec;
1333 			} else
1334 				size = STRLEN(result);
1335 			sign = '\0';
1336 			break;
1337 		case 'U':
1338 			flags |= LONGINT;
1339 			/*FALLTHROUGH*/
1340 		case 'u':
1341 			if (flags & INTMAX_SIZE)
1342 				ujval = UJARG();
1343 			else
1344 				ulval = UARG();
1345 			base = 10;
1346 			goto nosign;
1347 		case 'X':
1348 			xdigs = xdigs_upper;
1349 			goto hex;
1350 		case 'x':
1351 			xdigs = xdigs_lower;
1352 hex:
1353 			if (flags & INTMAX_SIZE)
1354 				ujval = UJARG();
1355 			else
1356 				ulval = UARG();
1357 			base = 16;
1358 			/* leading 0x/X only if non-zero */
1359 			if (flags & ALT &&
1360 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1361 				ox[1] = ch;
1362 
1363 			flags &= ~GROUPING;
1364 			/* unsigned conversions */
1365 nosign:			sign = '\0';
1366 			/*-
1367 			 * ``... diouXx conversions ... if a precision is
1368 			 * specified, the 0 flag will be ignored.''
1369 			 *	-- ANSI X3J11
1370 			 */
1371 number:			if ((dprec = prec) >= 0)
1372 				flags &= ~ZEROPAD;
1373 
1374 			/*-
1375 			 * ``The result of converting a zero value with an
1376 			 * explicit precision of zero is no characters.''
1377 			 *	-- ANSI X3J11
1378 			 *
1379 			 * ``The C Standard is clear enough as is.  The call
1380 			 * printf("%#.0o", 0) should print 0.''
1381 			 *	-- Defect Report #151
1382 			 */
1383 			result = cp = buf + BUF;
1384 			if (flags & INTMAX_SIZE) {
1385 				if (ujval != 0 || prec != 0 ||
1386 				    (flags & ALT && base == 8))
1387 					result = __ujtoa(ujval, cp, base,
1388 					    flags & ALT, xdigs,
1389 					    flags & GROUPING, thousands_sep,
1390 					    grouping);
1391 			} else {
1392 				if (ulval != 0 || prec != 0 ||
1393 				    (flags & ALT && base == 8))
1394 					result = __ultoa(ulval, cp, base,
1395 					    flags & ALT, xdigs,
1396 					    flags & GROUPING, thousands_sep,
1397 					    grouping);
1398 			}
1399 			size = buf + BUF - result;
1400 			if (size > BUF)	/* should never happen */
1401 				abort();
1402 			break;
1403 		default:	/* "%?" prints ?, unless ? is NUL */
1404 			if (ch == '\0')
1405 				goto done;
1406 			/* pretend it was %c with argument ch */
1407 			*buf = ch;
1408 			result = buf;
1409 			size = 1;
1410 			sign = '\0';
1411 			break;
1412 		}
1413 
1414 		/*
1415 		 * All reasonable formats wind up here.  At this point, `result'
1416 		 * points to a string which (if not flags&LADJUST) should be
1417 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1418 		 * first be prefixed by any sign or other prefix; otherwise,
1419 		 * it should be blank padded before the prefix is emitted.
1420 		 * After any left-hand padding and prefixing, emit zeroes
1421 		 * required by a decimal [diouxX] precision, then print the
1422 		 * string proper, then emit zeroes required by any leftover
1423 		 * floating precision; finally, if LADJUST, pad with blanks.
1424 		 *
1425 		 * Compute actual size, so we know how much to pad.
1426 		 * size excludes decimal prec; realsz includes it.
1427 		 */
1428 		realsz = dprec > size ? dprec : size;
1429 		if (sign)
1430 			realsz++;
1431 		if (ox[1])
1432 			realsz += 2;
1433 
1434 		prsize = width > realsz ? width : realsz;
1435 		if ((unsigned)ret + prsize > INT_MAX) {
1436 			ret = END_OF_FILE;
1437 			goto error;
1438 		}
1439 
1440 		/* right-adjusting blank padding */
1441 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1442 			PAD(width - realsz, blanks);
1443 
1444 		/* prefix */
1445 		if (sign)
1446 			PRINT(&sign, 1);
1447 
1448 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1449 			ox[0] = '0';
1450 			PRINT(ox, 2);
1451 		}
1452 
1453 		/* right-adjusting zero padding */
1454 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1455 			PAD(width - realsz, zeroes);
1456 
1457 		/* leading zeroes from decimal precision */
1458 		PAD(dprec - size, zeroes);
1459 
1460 		/* the string or number proper */
1461 #ifndef NO_FLOATING_POINT
1462 		if ((flags & FPT) == 0) {
1463 			PRINT(result, size);
1464 		} else {	/* glue together f_p fragments */
1465 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1466 				if (expt <= 0) {
1467 					PRINT(zeroes, 1);
1468 					if (prec || flags & ALT)
1469 						PRINT(decimal_point, 1);
1470 					PAD(-expt, zeroes);
1471 					/* already handled initial 0's */
1472 					prec += expt;
1473 				} else {
1474 					PRINTANDPAD(result, convbuf + ndig,
1475 					    lead, zeroes);
1476 					result += lead;
1477 					if (grouping) {
1478 						while (nseps>0 || nrepeats>0) {
1479 							if (nrepeats > 0)
1480 								nrepeats--;
1481 							else {
1482 								grouping--;
1483 								nseps--;
1484 							}
1485 							PRINT(&thousands_sep,
1486 							    1);
1487 							PRINTANDPAD(result,
1488 							    convbuf + ndig,
1489 							    *grouping, zeroes);
1490 							result += *grouping;
1491 						}
1492 						if (result > convbuf + ndig)
1493 							result = convbuf + ndig;
1494 					}
1495 					if (prec || flags & ALT) {
1496 						buf[0] = *decimal_point;
1497 						PRINT(buf, 1);
1498 					}
1499 				}
1500 				PRINTANDPAD(result, convbuf + ndig, prec,
1501 				    zeroes);
1502 			} else {	/* %[eE] or sufficiently long %[gG] */
1503 				if (prec > 1 || flags & ALT) {
1504 					buf[0] = *result++;
1505 					buf[1] = *decimal_point;
1506 					PRINT(buf, 2);
1507 					PRINT(result, ndig-1);
1508 					PAD(prec - ndig, zeroes);
1509 				} else	/* XeYYY */
1510 					PRINT(result, 1);
1511 				PRINT(expstr, expsize);
1512 			}
1513 		}
1514 #else
1515 		PRINT(result, size);
1516 #endif
1517 		/* left-adjusting padding (always blank) */
1518 		if (flags & LADJUST)
1519 			PAD(width - realsz, blanks);
1520 
1521 		/* finally, adjust ret */
1522 		ret += prsize;
1523 		FLUSH();
1524 	}
1525 done:
1526 	FLUSH();
1527 error:
1528 	va_end(orgap);
1529 	if (convbuf != NULL)
1530 		free(convbuf);
1531 	if (__sferror(fp))
1532 		ret = END_OF_FILE;
1533 	if ((argtable != NULL) && (argtable != statargtable))
1534 		free (argtable);
1535 	return (ret);
1536 	/* NOTREACHED */
1537 oomem:
1538 	errno = ENOMEM;
1539 	ret = END_OF_FILE;
1540 	goto error;
1541 }
1542 
1543 /*
1544  * Find all arguments when a positional parameter is encountered.  Returns a
1545  * table, indexed by argument number, of pointers to each arguments.  The
1546  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1547  * It will be replaces with a malloc-ed one if it overflows.
1548  */
1549 static int
1550 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
1551 {
1552 	CHAR_T *fmt;		/* format string */
1553 	int ch;			/* character from fmt */
1554 	int n, n2;		/* handy integer (short term usage) */
1555 	CHAR_T *cp;		/* handy char pointer (short term usage) */
1556 	int flags;		/* flags as above */
1557 	enum typeid *typetable; /* table of types */
1558 	enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1559 	int tablesize;		/* current size of type table */
1560 	int tablemax;		/* largest used index in table */
1561 	int nextarg;		/* 1-based argument index */
1562 
1563 	/*
1564 	 * Add an argument type to the table, expanding if necessary.
1565 	 */
1566 #define ADDTYPE(type) \
1567 	do { \
1568 		if (nextarg >= tablesize) \
1569 			if (__grow_type_table(nextarg, &typetable, \
1570 			    &tablesize) == -1) \
1571 				return -1; \
1572 		if (nextarg > tablemax) \
1573 			tablemax = nextarg; \
1574 		typetable[nextarg++] = type; \
1575 	} while (/*CONSTCOND*/0)
1576 
1577 #define	ADDSARG() \
1578 	do { \
1579 		if (flags & INTMAXT)  \
1580 			ADDTYPE(T_INTMAXT); \
1581 		else if (flags & SIZET)  \
1582 			ADDTYPE(T_SSIZET); \
1583 		else if (flags & PTRDIFFT) \
1584 			ADDTYPE(T_PTRDIFFT); \
1585 		else if (flags & LLONGINT) \
1586 			ADDTYPE(T_LLONG); \
1587 		else if (flags & LONGINT) \
1588 			ADDTYPE(T_LONG); \
1589 		else \
1590 			ADDTYPE(T_INT); \
1591 	} while (/*CONSTCOND*/0)
1592 
1593 #define	ADDUARG() \
1594 	do { \
1595 		if (flags & INTMAXT)  \
1596 			ADDTYPE(T_UINTMAXT); \
1597 		else if (flags & SIZET)  \
1598 			ADDTYPE(T_SIZET); \
1599 		else if (flags & PTRDIFFT) \
1600 			ADDTYPE(T_PTRDIFFT); \
1601 		else if (flags & LLONGINT) \
1602 			ADDTYPE(T_U_LLONG); \
1603 		else if (flags & LONGINT) \
1604 			ADDTYPE(T_U_LONG); \
1605 		else \
1606 			ADDTYPE(T_U_INT); \
1607 	} while (/*CONSTCOND*/0)
1608 	/*
1609 	 * Add * arguments to the type array.
1610 	 */
1611 #define ADDASTER() \
1612 	n2 = 0; \
1613 	cp = fmt; \
1614 	while (is_digit(*cp)) { \
1615 		n2 = 10 * n2 + to_digit(*cp); \
1616 		cp++; \
1617 	} \
1618 	if (*cp == '$') { \
1619 		int hold = nextarg; \
1620 		nextarg = n2; \
1621 		ADDTYPE(T_INT); \
1622 		nextarg = hold; \
1623 		fmt = ++cp; \
1624 	} else { \
1625 		ADDTYPE(T_INT); \
1626 	}
1627 	fmt = (CHAR_T *)__UNCONST(fmt0);
1628 	typetable = stattypetable;
1629 	tablesize = STATIC_ARG_TBL_SIZE;
1630 	tablemax = 0;
1631 	nextarg = 1;
1632 	for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1633 		typetable[n] = T_UNUSED;
1634 
1635 	/*
1636 	 * Scan the format for conversions (`%' character).
1637 	 */
1638 	for (;;) {
1639 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1640 			/* void */;
1641 		if (ch == '\0')
1642 			goto done;
1643 		fmt++;		/* skip over '%' */
1644 
1645 		flags = 0;
1646 
1647 rflag:		ch = *fmt++;
1648 reswitch:	switch (ch) {
1649 		case ' ':
1650 		case '#':
1651 			goto rflag;
1652 		case '*':
1653 			ADDASTER ();
1654 			goto rflag;
1655 		case '-':
1656 		case '+':
1657 		case '\'':
1658 			goto rflag;
1659 		case '.':
1660 			if ((ch = *fmt++) == '*') {
1661 				ADDASTER ();
1662 				goto rflag;
1663 			}
1664 			while (is_digit(ch)) {
1665 				ch = *fmt++;
1666 			}
1667 			goto reswitch;
1668 		case '0':
1669 			goto rflag;
1670 		case '1': case '2': case '3': case '4':
1671 		case '5': case '6': case '7': case '8': case '9':
1672 			n = 0;
1673 			do {
1674 				n = 10 * n + to_digit(ch);
1675 				ch = *fmt++;
1676 			} while (is_digit(ch));
1677 			if (ch == '$') {
1678 				nextarg = n;
1679 				goto rflag;
1680 			}
1681 			goto reswitch;
1682 #ifndef NO_FLOATING_POINT
1683 		case 'L':
1684 			flags |= LONGDBL;
1685 			goto rflag;
1686 #endif
1687 		case 'h':
1688 			if (flags & SHORTINT) {
1689 				flags &= ~SHORTINT;
1690 				flags |= CHARINT;
1691 			} else
1692 				flags |= SHORTINT;
1693 			goto rflag;
1694 		case 'j':
1695 			flags |= INTMAXT;
1696 			goto rflag;
1697 		case 'l':
1698 			if (flags & LONGINT) {
1699 				flags &= ~LONGINT;
1700 				flags |= LLONGINT;
1701 			} else
1702 				flags |= LONGINT;
1703 			goto rflag;
1704 		case 'q':
1705 			flags |= LLONGINT;	/* not necessarily */
1706 			goto rflag;
1707 		case 't':
1708 			flags |= PTRDIFFT;
1709 			goto rflag;
1710 		case 'z':
1711 			flags |= SIZET;
1712 			goto rflag;
1713 		case 'C':
1714 			flags |= LONGINT;
1715 			/*FALLTHROUGH*/
1716 		case 'c':
1717 			if (flags & LONGINT)
1718 				ADDTYPE(T_WINT);
1719 			else
1720 				ADDTYPE(T_INT);
1721 			break;
1722 		case 'D':
1723 			flags |= LONGINT;
1724 			/*FALLTHROUGH*/
1725 		case 'd':
1726 		case 'i':
1727 			ADDSARG();
1728 			break;
1729 #ifndef NO_FLOATING_POINT
1730 		case 'a':
1731 		case 'A':
1732 		case 'e':
1733 		case 'E':
1734 		case 'f':
1735 		case 'g':
1736 		case 'G':
1737 			if (flags & LONGDBL)
1738 				ADDTYPE(T_LONG_DOUBLE);
1739 			else
1740 				ADDTYPE(T_DOUBLE);
1741 			break;
1742 #endif /* !NO_FLOATING_POINT */
1743 		case 'n':
1744 			if (flags & INTMAXT)
1745 				ADDTYPE(TP_INTMAXT);
1746 			else if (flags & PTRDIFFT)
1747 				ADDTYPE(TP_PTRDIFFT);
1748 			else if (flags & SIZET)
1749 				ADDTYPE(TP_SIZET);
1750 			else if (flags & LLONGINT)
1751 				ADDTYPE(TP_LLONG);
1752 			else if (flags & LONGINT)
1753 				ADDTYPE(TP_LONG);
1754 			else if (flags & SHORTINT)
1755 				ADDTYPE(TP_SHORT);
1756 			else if (flags & CHARINT)
1757 				ADDTYPE(TP_SCHAR);
1758 			else
1759 				ADDTYPE(TP_INT);
1760 			continue;	/* no output */
1761 		case 'O':
1762 			flags |= LONGINT;
1763 			/*FALLTHROUGH*/
1764 		case 'o':
1765 			ADDUARG();
1766 			break;
1767 		case 'p':
1768 			ADDTYPE(TP_VOID);
1769 			break;
1770 		case 'S':
1771 			flags |= LONGINT;
1772 			/*FALLTHROUGH*/
1773 		case 's':
1774 			if (flags & LONGINT)
1775 				ADDTYPE(TP_WCHAR);
1776 			else
1777 				ADDTYPE(TP_CHAR);
1778 			break;
1779 		case 'U':
1780 			flags |= LONGINT;
1781 			/*FALLTHROUGH*/
1782 		case 'u':
1783 		case 'X':
1784 		case 'x':
1785 			ADDUARG();
1786 			break;
1787 		default:	/* "%?" prints ?, unless ? is NUL */
1788 			if (ch == '\0')
1789 				goto done;
1790 			break;
1791 		}
1792 	}
1793 done:
1794 	/*
1795 	 * Build the argument table.
1796 	 */
1797 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1798 		*argtable = (union arg *)
1799 		    malloc (sizeof (union arg) * (tablemax + 1));
1800 		if (*argtable == NULL)
1801 			return -1;
1802 	}
1803 
1804 	(*argtable) [0].intarg = 0;
1805 	for (n = 1; n <= tablemax; n++) {
1806 		switch (typetable [n]) {
1807 		    case T_UNUSED: /* whoops! */
1808 			(*argtable) [n].intarg = va_arg (ap, int);
1809 			break;
1810 		    case TP_SCHAR:
1811 			(*argtable) [n].pschararg = va_arg (ap, signed char *);
1812 			break;
1813 		    case TP_SHORT:
1814 			(*argtable) [n].pshortarg = va_arg (ap, short *);
1815 			break;
1816 		    case T_INT:
1817 			(*argtable) [n].intarg = va_arg (ap, int);
1818 			break;
1819 		    case T_U_INT:
1820 			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
1821 			break;
1822 		    case TP_INT:
1823 			(*argtable) [n].pintarg = va_arg (ap, int *);
1824 			break;
1825 		    case T_LONG:
1826 			(*argtable) [n].longarg = va_arg (ap, long);
1827 			break;
1828 		    case T_U_LONG:
1829 			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1830 			break;
1831 		    case TP_LONG:
1832 			(*argtable) [n].plongarg = va_arg (ap, long *);
1833 			break;
1834 		    case T_LLONG:
1835 			(*argtable) [n].longlongarg = va_arg (ap, long long);
1836 			break;
1837 		    case T_U_LLONG:
1838 			(*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1839 			break;
1840 		    case TP_LLONG:
1841 			(*argtable) [n].plonglongarg = va_arg (ap, long long *);
1842 			break;
1843 		    case T_PTRDIFFT:
1844 			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1845 			break;
1846 		    case TP_PTRDIFFT:
1847 			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1848 			break;
1849 		    case T_SSIZET:
1850 			(*argtable) [n].ssizearg = va_arg (ap, ssize_t);
1851 			break;
1852 		    case T_SIZET:
1853 			(*argtable) [n].sizearg = va_arg (ap, size_t);
1854 			break;
1855 		    case TP_SIZET:
1856 			(*argtable) [n].psizearg = va_arg (ap, size_t *);
1857 			break;
1858 		    case T_INTMAXT:
1859 			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1860 			break;
1861 		    case T_UINTMAXT:
1862 			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1863 			break;
1864 		    case TP_INTMAXT:
1865 			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1866 			break;
1867 		    case T_DOUBLE:
1868 #ifndef NO_FLOATING_POINT
1869 			(*argtable) [n].doublearg = va_arg (ap, double);
1870 #endif
1871 			break;
1872 		    case T_LONG_DOUBLE:
1873 #ifndef NO_FLOATING_POINT
1874 			(*argtable) [n].longdoublearg = va_arg (ap, long double);
1875 #endif
1876 			break;
1877 		    case TP_CHAR:
1878 			(*argtable) [n].pchararg = va_arg (ap, char *);
1879 			break;
1880 		    case TP_VOID:
1881 			(*argtable) [n].pvoidarg = va_arg (ap, void *);
1882 			break;
1883 		    case T_WINT:
1884 			(*argtable) [n].wintarg = va_arg (ap, wint_t);
1885 			break;
1886 		    case TP_WCHAR:
1887 			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1888 			break;
1889 		}
1890 	}
1891 
1892 	if ((typetable != NULL) && (typetable != stattypetable))
1893 		free (typetable);
1894 	return 0;
1895 }
1896 
1897 /*
1898  * Increase the size of the type table.
1899  */
1900 static int
1901 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1902 {
1903 	enum typeid *const oldtable = *typetable;
1904 	const int oldsize = *tablesize;
1905 	enum typeid *newtable;
1906 	int n, newsize = oldsize * 2;
1907 
1908 	if (newsize < nextarg + 1)
1909 		newsize = nextarg + 1;
1910 	if (oldsize == STATIC_ARG_TBL_SIZE) {
1911 		if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1912 			return -1;
1913 		memcpy(newtable, oldtable, oldsize * sizeof(enum typeid));
1914 	} else {
1915 		newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1916 		if (newtable == NULL) {
1917 			free(oldtable);
1918 			return -1;
1919 		}
1920 	}
1921 	for (n = oldsize; n < newsize; n++)
1922 		newtable[n] = T_UNUSED;
1923 
1924 	*typetable = newtable;
1925 	*tablesize = newsize;
1926 	return 0;
1927 }
1928 
1929 
1930 #ifndef NO_FLOATING_POINT
1931 #ifndef WIDE_DOUBLE
1932 static char *
1933 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1934     int *length)
1935 {
1936 	int mode, dsgn;
1937 	char *digits, *bp, *rve;
1938 
1939 	_DIAGASSERT(decpt != NULL);
1940 	_DIAGASSERT(length != NULL);
1941 	_DIAGASSERT(sign != NULL);
1942 
1943 	if (ch == 'f') {
1944 		mode = 3;		/* ndigits after the decimal point */
1945 	} else {
1946 		/* To obtain ndigits after the decimal point for the 'e'
1947 		 * and 'E' formats, round to ndigits + 1 significant
1948 		 * figures.
1949 		 */
1950 		if (ch == 'e' || ch == 'E') {
1951 			ndigits++;
1952 		}
1953 		mode = 2;		/* ndigits significant digits */
1954 	}
1955 
1956 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1957 	if (digits == NULL)
1958 		return NULL;
1959 	if (dsgn) {
1960 		value = -value;
1961 		*sign = '-';
1962 	} else
1963 		*sign = '\000';
1964 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
1965 		bp = digits + ndigits;
1966 		if (ch == 'f') {
1967 			if (*digits == '0' && value)
1968 				*decpt = -ndigits + 1;
1969 			bp += *decpt;
1970 		}
1971 		if (value == 0)	/* kludge for __dtoa irregularity */
1972 			rve = bp;
1973 		while (rve < bp)
1974 			*rve++ = '0';
1975 	}
1976 	*length = rve - digits;
1977 	return digits;
1978 }
1979 #endif
1980 
1981 static int
1982 exponent(CHAR_T *p0, int expo, int fmtch)
1983 {
1984 	CHAR_T *p, *t;
1985 	CHAR_T expbuf[MAXEXPDIG];
1986 
1987 	p = p0;
1988 	*p++ = fmtch;
1989 	if (expo < 0) {
1990 		expo = -expo;
1991 		*p++ = '-';
1992 	}
1993 	else
1994 		*p++ = '+';
1995 	t = expbuf + MAXEXPDIG;
1996 	if (expo > 9) {
1997 		do {
1998 			*--t = to_char(expo % 10);
1999 		} while ((expo /= 10) > 9);
2000 		*--t = to_char(expo);
2001 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
2002 	}
2003 	else {
2004 		/*
2005 		 * Exponents for decimal floating point conversions
2006 		 * (%[eEgG]) must be at least two characters long,
2007 		 * whereas exponents for hexadecimal conversions can
2008 		 * be only one character long.
2009 		 */
2010 		if (fmtch == 'e' || fmtch == 'E')
2011 			*p++ = '0';
2012 		*p++ = to_char(expo);
2013 	}
2014 	return (p - p0);
2015 }
2016 #endif /* !NO_FLOATING_POINT */
2017