xref: /freebsd-14-stable/lib/libc/stdio/vfwprintf.c (revision 2ce4f021827a718005e44db693ee5aee7ed175b9)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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  * Copyright (c) 2011 The FreeBSD Foundation
11  *
12  * Portions of this software were developed by David Chisnall
13  * under sponsorship from the FreeBSD Foundation.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 #if 0
41 #if defined(LIBC_SCCS) && !defined(lint)
42 static char sccsid[] = "@(#)vfprintf.c	8.1 (Berkeley) 6/4/93";
43 #endif /* LIBC_SCCS and not lint */
44 #endif
45 /*
46  * Actual wprintf innards.
47  *
48  * Avoid making gratuitous changes to this source file; it should be kept
49  * as close as possible to vfprintf.c for ease of maintenance.
50  */
51 
52 #include "namespace.h"
53 #include <sys/types.h>
54 
55 #include <ctype.h>
56 #include <errno.h>
57 #include <limits.h>
58 #include <locale.h>
59 #include <stdarg.h>
60 #include <stddef.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <wchar.h>
66 #include <wctype.h>
67 #include "un-namespace.h"
68 
69 #include "libc_private.h"
70 #include "local.h"
71 #include "fvwrite.h"
72 #include "printflocal.h"
73 #include "xlocale_private.h"
74 
75 static int	__sprint(FILE *, struct __suio *, locale_t);
76 static int	__sbprintf(FILE *, locale_t, const wchar_t *, va_list) __noinline;
77 static wint_t	__xfputwc(wchar_t, FILE *, locale_t);
78 static wchar_t	*__mbsconv(char *, int);
79 
80 #define	CHAR	wchar_t
81 #include "printfcommon.h"
82 
83 struct grouping_state {
84 	wchar_t thousands_sep;	/* locale-specific thousands separator */
85 	const char *grouping;	/* locale-specific numeric grouping rules */
86 	int lead;		/* sig figs before decimal or group sep */
87 	int nseps;		/* number of group separators with ' */
88 	int nrepeats;		/* number of repeats of the last group */
89 };
90 
91 static const mbstate_t initial_mbs;
92 
93 static inline wchar_t
get_decpt(locale_t locale)94 get_decpt(locale_t locale)
95 {
96 	mbstate_t mbs;
97 	wchar_t decpt;
98 	int nconv;
99 
100 	mbs = initial_mbs;
101 	nconv = mbrtowc(&decpt, localeconv_l(locale)->decimal_point, MB_CUR_MAX, &mbs);
102 	if (nconv == (size_t)-1 || nconv == (size_t)-2)
103 		decpt = '.';    /* failsafe */
104 	return (decpt);
105 }
106 
107 static inline wchar_t
get_thousep(locale_t locale)108 get_thousep(locale_t locale)
109 {
110 	mbstate_t mbs;
111 	wchar_t thousep;
112 	int nconv;
113 
114 	mbs = initial_mbs;
115 	nconv = mbrtowc(&thousep, localeconv_l(locale)->thousands_sep,
116 	    MB_CUR_MAX, &mbs);
117 	if (nconv == (size_t)-1 || nconv == (size_t)-2)
118 		thousep = '\0';    /* failsafe */
119 	return (thousep);
120 }
121 
122 /*
123  * Initialize the thousands' grouping state in preparation to print a
124  * number with ndigits digits. This routine returns the total number
125  * of wide characters that will be printed.
126  */
127 static int
grouping_init(struct grouping_state * gs,int ndigits,locale_t locale)128 grouping_init(struct grouping_state *gs, int ndigits, locale_t locale)
129 {
130 
131 	gs->grouping = localeconv_l(locale)->grouping;
132 	gs->thousands_sep = get_thousep(locale);
133 
134 	gs->nseps = gs->nrepeats = 0;
135 	gs->lead = ndigits;
136 	while (*gs->grouping != CHAR_MAX) {
137 		if (gs->lead <= *gs->grouping)
138 			break;
139 		gs->lead -= *gs->grouping;
140 		if (*(gs->grouping+1)) {
141 			gs->nseps++;
142 			gs->grouping++;
143 		} else
144 			gs->nrepeats++;
145 	}
146 	return (gs->nseps + gs->nrepeats);
147 }
148 
149 /*
150  * Print a number with thousands' separators.
151  */
152 static int
grouping_print(struct grouping_state * gs,struct io_state * iop,const CHAR * cp,const CHAR * ep,locale_t locale)153 grouping_print(struct grouping_state *gs, struct io_state *iop,
154 	       const CHAR *cp, const CHAR *ep, locale_t locale)
155 {
156 	const CHAR *cp0 = cp;
157 
158 	if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
159 		return (-1);
160 	cp += gs->lead;
161 	while (gs->nseps > 0 || gs->nrepeats > 0) {
162 		if (gs->nrepeats > 0)
163 			gs->nrepeats--;
164 		else {
165 			gs->grouping--;
166 			gs->nseps--;
167 		}
168 		if (io_print(iop, &gs->thousands_sep, 1, locale))
169 			return (-1);
170 		if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
171 			return (-1);
172 		cp += *gs->grouping;
173 	}
174 	if (cp > ep)
175 		cp = ep;
176 	return (cp - cp0);
177 }
178 
179 
180 /*
181  * Flush out all the vectors defined by the given uio,
182  * then reset it so that it can be reused.
183  *
184  * XXX The fact that we do this a character at a time and convert to a
185  * multibyte character sequence even if the destination is a wide
186  * string eclipses the benefits of buffering.
187  */
188 static int
__sprint(FILE * fp,struct __suio * uio,locale_t locale)189 __sprint(FILE *fp, struct __suio *uio, locale_t locale)
190 {
191 	struct __siov *iov;
192 	wchar_t *p;
193 	int i, len;
194 
195 	iov = uio->uio_iov;
196 	for (; uio->uio_resid != 0; uio->uio_resid -= len, iov++) {
197 		p = (wchar_t *)iov->iov_base;
198 		len = iov->iov_len;
199 		for (i = 0; i < len; i++) {
200 			if (__xfputwc(p[i], fp, locale) == WEOF)
201 				return (-1);
202 		}
203 	}
204 	uio->uio_iovcnt = 0;
205 	return (0);
206 }
207 
208 /*
209  * Helper function for `fprintf to unbuffered unix file': creates a
210  * temporary buffer.  We only work on write-only files; this avoids
211  * worries about ungetc buffers and so forth.
212  */
213 static int
__sbprintf(FILE * fp,locale_t locale,const wchar_t * fmt,va_list ap)214 __sbprintf(FILE *fp, locale_t locale, const wchar_t *fmt, va_list ap)
215 {
216 	int ret;
217 	FILE fake;
218 	unsigned char buf[BUFSIZ];
219 
220 	/* XXX This is probably not needed. */
221 	if (prepwrite(fp) != 0)
222 		return (EOF);
223 
224 	/* copy the important variables */
225 	fake._flags = fp->_flags & ~__SNBF;
226 	fake._file = fp->_file;
227 	fake._cookie = fp->_cookie;
228 	fake._write = fp->_write;
229 	fake._orientation = fp->_orientation;
230 	fake._mbstate = fp->_mbstate;
231 
232 	/* set up the buffer */
233 	fake._bf._base = fake._p = buf;
234 	fake._bf._size = fake._w = sizeof(buf);
235 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
236 
237 	/* do the work, then copy any error status */
238 	ret = __vfwprintf(&fake, locale, fmt, ap);
239 	if (ret >= 0 && __fflush(&fake))
240 		ret = WEOF;
241 	if (fake._flags & __SERR)
242 		fp->_flags |= __SERR;
243 	return (ret);
244 }
245 
246 /*
247  * Like __fputwc, but handles fake string (__SSTR) files properly.
248  * File must already be locked.
249  */
250 static wint_t
__xfputwc(wchar_t wc,FILE * fp,locale_t locale)251 __xfputwc(wchar_t wc, FILE *fp, locale_t locale)
252 {
253 	mbstate_t mbs;
254 	char buf[MB_LEN_MAX];
255 	struct __suio uio;
256 	struct __siov iov;
257 	size_t len;
258 
259 	if ((fp->_flags & __SSTR) == 0)
260 		return (__fputwc(wc, fp, locale));
261 
262 	mbs = initial_mbs;
263 	if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
264 		fp->_flags |= __SERR;
265 		return (WEOF);
266 	}
267 	uio.uio_iov = &iov;
268 	uio.uio_resid = len;
269 	uio.uio_iovcnt = 1;
270 	iov.iov_base = buf;
271 	iov.iov_len = len;
272 	return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
273 }
274 
275 /*
276  * Convert a multibyte character string argument for the %s format to a wide
277  * string representation. ``prec'' specifies the maximum number of bytes
278  * to output. If ``prec'' is greater than or equal to zero, we can't assume
279  * that the multibyte char. string ends in a null character.
280  */
281 static wchar_t *
__mbsconv(char * mbsarg,int prec)282 __mbsconv(char *mbsarg, int prec)
283 {
284 	mbstate_t mbs;
285 	wchar_t *convbuf, *wcp;
286 	const char *p;
287 	size_t insize, nchars, nconv;
288 
289 	if (mbsarg == NULL)
290 		return (NULL);
291 
292 	/*
293 	 * Supplied argument is a multibyte string; convert it to wide
294 	 * characters first.
295 	 */
296 	if (prec >= 0) {
297 		/*
298 		 * String is not guaranteed to be NUL-terminated. Find the
299 		 * number of characters to print.
300 		 */
301 		p = mbsarg;
302 		insize = nchars = nconv = 0;
303 		mbs = initial_mbs;
304 		while (nchars != (size_t)prec) {
305 			nconv = mbrlen(p, MB_CUR_MAX, &mbs);
306 			if (nconv == 0 || nconv == (size_t)-1 ||
307 			    nconv == (size_t)-2)
308 				break;
309 			p += nconv;
310 			nchars++;
311 			insize += nconv;
312 		}
313 		if (nconv == (size_t)-1 || nconv == (size_t)-2)
314 			return (NULL);
315 	} else {
316 		insize = strlen(mbsarg);
317 		nconv = 0;
318 	}
319 
320 	/*
321 	 * Allocate buffer for the result and perform the conversion,
322 	 * converting at most `size' bytes of the input multibyte string to
323 	 * wide characters for printing.
324 	 */
325 	convbuf = malloc((insize + 1) * sizeof(*convbuf));
326 	if (convbuf == NULL)
327 		return (NULL);
328 	wcp = convbuf;
329 	p = mbsarg;
330 	mbs = initial_mbs;
331 	while (insize != 0) {
332 		nconv = mbrtowc(wcp, p, insize, &mbs);
333 		if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
334 			break;
335 		wcp++;
336 		p += nconv;
337 		insize -= nconv;
338 	}
339 	if (nconv == (size_t)-1 || nconv == (size_t)-2) {
340 		free(convbuf);
341 		return (NULL);
342 	}
343 	*wcp = L'\0';
344 
345 	return (convbuf);
346 }
347 
348 /*
349  * MT-safe version
350  */
351 int
vfwprintf_l(FILE * __restrict fp,locale_t locale,const wchar_t * __restrict fmt0,va_list ap)352 vfwprintf_l(FILE * __restrict fp, locale_t locale,
353 		const wchar_t * __restrict fmt0, va_list ap)
354 
355 {
356 	int ret;
357 	FIX_LOCALE(locale);
358 	FLOCKFILE_CANCELSAFE(fp);
359 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
360 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
361 	    fp->_file >= 0)
362 		ret = __sbprintf(fp, locale, fmt0, ap);
363 	else
364 		ret = __vfwprintf(fp, locale, fmt0, ap);
365 	FUNLOCKFILE_CANCELSAFE();
366 	return (ret);
367 }
368 int
vfwprintf(FILE * __restrict fp,const wchar_t * __restrict fmt0,va_list ap)369 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
370 {
371 	return vfwprintf_l(fp, __get_locale(), fmt0, ap);
372 }
373 
374 /*
375  * The size of the buffer we use as scratch space for integer
376  * conversions, among other things.  We need enough space to
377  * write a uintmax_t in binary.
378  */
379 #define BUF	(sizeof(uintmax_t) * CHAR_BIT)
380 
381 /*
382  * Non-MT-safe version
383  */
384 int
__vfwprintf(FILE * fp,locale_t locale,const wchar_t * fmt0,va_list ap)385 __vfwprintf(FILE *fp, locale_t locale, const wchar_t *fmt0, va_list ap)
386 {
387 	wchar_t *fmt;		/* format string */
388 	wchar_t ch;		/* character from fmt */
389 	int n, n2;		/* handy integer (short term usage) */
390 	wchar_t *cp;		/* handy char pointer (short term usage) */
391 	int flags;		/* flags as above */
392 	int ret;		/* return value accumulator */
393 	int width;		/* width from format (%8d), or 0 */
394 	int prec;		/* precision from format; <0 for N/A */
395 	wchar_t sign;		/* sign prefix (' ', '+', '-', or \0) */
396 	struct grouping_state gs; /* thousands' grouping info */
397 #ifndef NO_FLOATING_POINT
398 	/*
399 	 * We can decompose the printed representation of floating
400 	 * point numbers into several parts, some of which may be empty:
401 	 *
402 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
403 	 *    A       B     ---C---      D       E   F
404 	 *
405 	 * A:	'sign' holds this value if present; '\0' otherwise
406 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
407 	 * C:	cp points to the string MMMNNN.  Leading and trailing
408 	 *	zeros are not in the string and must be added.
409 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
410 	 * F:	at least two digits for decimal, at least one digit for hex
411 	 */
412 	wchar_t decimal_point;	/* locale specific decimal point */
413 	int signflag;		/* true if float is negative */
414 	union {			/* floating point arguments %[aAeEfFgG] */
415 		double dbl;
416 		long double ldbl;
417 	} fparg;
418 	int expt;		/* integer value of exponent */
419 	char expchar;		/* exponent character: [eEpP\0] */
420 	char *dtoaend;		/* pointer to end of converted digits */
421 	int expsize;		/* character count for expstr */
422 	int ndig;		/* actual number of digits returned by dtoa */
423 	wchar_t expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
424 	char *dtoaresult;	/* buffer allocated by dtoa */
425 #endif
426 	u_long	ulval;		/* integer arguments %[diouxX] */
427 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
428 	int base;		/* base for [diouxX] conversion */
429 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
430 	int realsz;		/* field size expanded by dprec, sign, etc */
431 	int size;		/* size of converted field or string */
432 	int prsize;             /* max size of printed field */
433 	const char *xdigs;	/* digits for [xX] conversion */
434 	struct io_state io;	/* I/O buffering state */
435 	wchar_t buf[BUF];	/* buffer with space for digits of uintmax_t */
436 	wchar_t ox[2];		/* space for 0x hex-prefix */
437 	union arg *argtable;	/* args, built due to positional arg */
438 	union arg statargtable [STATIC_ARG_TBL_SIZE];
439 	int nextarg;		/* 1-based argument index */
440 	va_list orgap;		/* original argument pointer */
441 	wchar_t *convbuf;	/* multibyte to wide conversion result */
442 	int savserr;
443 
444 	static const char xdigs_lower[16] = "0123456789abcdef";
445 	static const char xdigs_upper[16] = "0123456789ABCDEF";
446 
447 	/* BEWARE, these `goto error' on error. */
448 #define	PRINT(ptr, len)	do {			\
449 	if (io_print(&io, (ptr), (len), locale))	\
450 		goto error; \
451 } while (0)
452 #define	PAD(howmany, with) { \
453 	if (io_pad(&io, (howmany), (with), locale)) \
454 		goto error; \
455 }
456 #define	PRINTANDPAD(p, ep, len, with) {	\
457 	if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
458 		goto error; \
459 }
460 #define	FLUSH() { \
461 	if (io_flush(&io, locale)) \
462 		goto error; \
463 }
464 
465 	/*
466 	 * Get the argument indexed by nextarg.   If the argument table is
467 	 * built, use it to get the argument.  If its not, get the next
468 	 * argument (and arguments must be gotten sequentially).
469 	 */
470 #define GETARG(type) \
471 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
472 	    (nextarg++, va_arg(ap, type)))
473 
474 	/*
475 	 * To extend shorts properly, we need both signed and unsigned
476 	 * argument extraction methods.
477 	 */
478 #define	SARG() \
479 	(flags&LONGINT ? GETARG(long) : \
480 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
481 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
482 	    (long)GETARG(int))
483 #define	UARG() \
484 	(flags&LONGINT ? GETARG(u_long) : \
485 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
486 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
487 	    (u_long)GETARG(u_int))
488 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
489 #define SJARG() \
490 	(flags&INTMAXT ? GETARG(intmax_t) : \
491 	    flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
492 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
493 	    (intmax_t)GETARG(long long))
494 #define	UJARG() \
495 	(flags&INTMAXT ? GETARG(uintmax_t) : \
496 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
497 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
498 	    (uintmax_t)GETARG(unsigned long long))
499 
500 	/*
501 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
502 	 * that the argument can be gotten once the type is determined.
503 	 */
504 #define GETASTER(val) \
505 	n2 = 0; \
506 	cp = fmt; \
507 	while (is_digit(*cp)) { \
508 		n2 = 10 * n2 + to_digit(*cp); \
509 		cp++; \
510 	} \
511 	if (*cp == '$') { \
512 		int hold = nextarg; \
513 		if (argtable == NULL) { \
514 			argtable = statargtable; \
515 			if (__find_warguments (fmt0, orgap, &argtable)) { \
516 				ret = EOF; \
517 				goto error; \
518 			} \
519 		} \
520 		nextarg = n2; \
521 		val = GETARG (int); \
522 		nextarg = hold; \
523 		fmt = ++cp; \
524 	} else { \
525 		val = GETARG (int); \
526 	}
527 
528 
529 	/* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
530 	if (prepwrite(fp) != 0) {
531 		errno = EBADF;
532 		return (EOF);
533 	}
534 
535 	savserr = fp->_flags & __SERR;
536 	fp->_flags &= ~__SERR;
537 
538 	convbuf = NULL;
539 	fmt = (wchar_t *)fmt0;
540 	argtable = NULL;
541 	nextarg = 1;
542 	va_copy(orgap, ap);
543 	io_init(&io, fp);
544 	ret = 0;
545 #ifndef NO_FLOATING_POINT
546 	decimal_point = get_decpt(locale);
547 #endif
548 
549 	/*
550 	 * Scan the format for conversions (`%' character).
551 	 */
552 	for (;;) {
553 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
554 			/* void */;
555 		if ((n = fmt - cp) != 0) {
556 			if ((unsigned)ret + n > INT_MAX) {
557 				ret = EOF;
558 				errno = EOVERFLOW;
559 				goto error;
560 			}
561 			PRINT(cp, n);
562 			ret += n;
563 		}
564 		if (ch == '\0')
565 			goto done;
566 		fmt++;		/* skip over '%' */
567 
568 		flags = 0;
569 		dprec = 0;
570 		width = 0;
571 		prec = -1;
572 		gs.grouping = NULL;
573 		sign = '\0';
574 		ox[1] = '\0';
575 
576 rflag:		ch = *fmt++;
577 reswitch:	switch (ch) {
578 		case ' ':
579 			/*-
580 			 * ``If the space and + flags both appear, the space
581 			 * flag will be ignored.''
582 			 *	-- ANSI X3J11
583 			 */
584 			if (!sign)
585 				sign = ' ';
586 			goto rflag;
587 		case '#':
588 			flags |= ALT;
589 			goto rflag;
590 		case '*':
591 			/*-
592 			 * ``A negative field width argument is taken as a
593 			 * - flag followed by a positive field width.''
594 			 *	-- ANSI X3J11
595 			 * They don't exclude field widths read from args.
596 			 */
597 			GETASTER (width);
598 			if (width >= 0)
599 				goto rflag;
600 			width = -width;
601 			/* FALLTHROUGH */
602 		case '-':
603 			flags |= LADJUST;
604 			goto rflag;
605 		case '+':
606 			sign = '+';
607 			goto rflag;
608 		case '\'':
609 			flags |= GROUPING;
610 			goto rflag;
611 		case '.':
612 			if ((ch = *fmt++) == '*') {
613 				GETASTER (prec);
614 				goto rflag;
615 			}
616 			prec = 0;
617 			while (is_digit(ch)) {
618 				prec = 10 * prec + to_digit(ch);
619 				ch = *fmt++;
620 			}
621 			goto reswitch;
622 		case '0':
623 			/*-
624 			 * ``Note that 0 is taken as a flag, not as the
625 			 * beginning of a field width.''
626 			 *	-- ANSI X3J11
627 			 */
628 			flags |= ZEROPAD;
629 			goto rflag;
630 		case '1': case '2': case '3': case '4':
631 		case '5': case '6': case '7': case '8': case '9':
632 			n = 0;
633 			do {
634 				n = 10 * n + to_digit(ch);
635 				ch = *fmt++;
636 			} while (is_digit(ch));
637 			if (ch == '$') {
638 				nextarg = n;
639 				if (argtable == NULL) {
640 					argtable = statargtable;
641 					if (__find_warguments (fmt0, orgap,
642 							       &argtable)) {
643 						ret = EOF;
644 						goto error;
645 					}
646 				}
647 				goto rflag;
648 			}
649 			width = n;
650 			goto reswitch;
651 #ifndef NO_FLOATING_POINT
652 		case 'L':
653 			flags |= LONGDBL;
654 			goto rflag;
655 #endif
656 		case 'h':
657 			if (flags & SHORTINT) {
658 				flags &= ~SHORTINT;
659 				flags |= CHARINT;
660 			} else
661 				flags |= SHORTINT;
662 			goto rflag;
663 		case 'j':
664 			flags |= INTMAXT;
665 			goto rflag;
666 		case 'l':
667 			if (flags & LONGINT) {
668 				flags &= ~LONGINT;
669 				flags |= LLONGINT;
670 			} else
671 				flags |= LONGINT;
672 			goto rflag;
673 		case 'q':
674 			flags |= LLONGINT;	/* not necessarily */
675 			goto rflag;
676 		case 't':
677 			flags |= PTRDIFFT;
678 			goto rflag;
679 		case 'w':
680 			/*
681 			 * Fixed-width integer types.  On all platforms we
682 			 * support, int8_t is equivalent to char, int16_t
683 			 * is equivalent to short, int32_t is equivalent
684 			 * to int, int64_t is equivalent to long long int.
685 			 * Furthermore, int_fast8_t, int_fast16_t and
686 			 * int_fast32_t are equivalent to int, and
687 			 * int_fast64_t is equivalent to long long int.
688 			 */
689 			flags &= ~(CHARINT|SHORTINT|LONGINT|LLONGINT|INTMAXT);
690 			if (fmt[0] == 'f') {
691 				flags |= FASTINT;
692 				fmt++;
693 			} else {
694 				flags &= ~FASTINT;
695 			}
696 			if (fmt[0] == '8') {
697 				if (!(flags & FASTINT))
698 					flags |= CHARINT;
699 				else
700 					/* no flag set = 32 */ ;
701 				fmt += 1;
702 			} else if (fmt[0] == '1' && fmt[1] == '6') {
703 				if (!(flags & FASTINT))
704 					flags |= SHORTINT;
705 				else
706 					/* no flag set = 32 */ ;
707 				fmt += 2;
708 			} else if (fmt[0] == '3' && fmt[1] == '2') {
709 				/* no flag set = 32 */ ;
710 				fmt += 2;
711 			} else if (fmt[0] == '6' && fmt[1] == '4') {
712 				flags |= LLONGINT;
713 				fmt += 2;
714 			} else {
715 				if (flags & FASTINT) {
716 					flags &= ~FASTINT;
717 					fmt--;
718 				}
719 				goto invalid;
720 			}
721 			goto rflag;
722 		case 'z':
723 			flags |= SIZET;
724 			goto rflag;
725 		case 'B':
726 		case 'b':
727 			if (flags & INTMAX_SIZE)
728 				ujval = UJARG();
729 			else
730 				ulval = UARG();
731 			base = 2;
732 			/* leading 0b/B only if non-zero */
733 			if (flags & ALT &&
734 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
735 				ox[1] = ch;
736 			goto nosign;
737 			break;
738 		case 'C':
739 			flags |= LONGINT;
740 			/*FALLTHROUGH*/
741 		case 'c':
742 			if (flags & LONGINT)
743 				*(cp = buf) = (wchar_t)GETARG(wint_t);
744 			else
745 				*(cp = buf) = (wchar_t)btowc(GETARG(int));
746 			size = 1;
747 			sign = '\0';
748 			break;
749 		case 'D':
750 			flags |= LONGINT;
751 			/*FALLTHROUGH*/
752 		case 'd':
753 		case 'i':
754 			if (flags & INTMAX_SIZE) {
755 				ujval = SJARG();
756 				if ((intmax_t)ujval < 0) {
757 					ujval = -ujval;
758 					sign = '-';
759 				}
760 			} else {
761 				ulval = SARG();
762 				if ((long)ulval < 0) {
763 					ulval = -ulval;
764 					sign = '-';
765 				}
766 			}
767 			base = 10;
768 			goto number;
769 #ifndef NO_FLOATING_POINT
770 		case 'a':
771 		case 'A':
772 			if (ch == 'a') {
773 				ox[1] = 'x';
774 				xdigs = xdigs_lower;
775 				expchar = 'p';
776 			} else {
777 				ox[1] = 'X';
778 				xdigs = xdigs_upper;
779 				expchar = 'P';
780 			}
781 			if (prec >= 0)
782 				prec++;
783 			if (flags & LONGDBL) {
784 				fparg.ldbl = GETARG(long double);
785 				dtoaresult =
786 				    __hldtoa(fparg.ldbl, xdigs, prec,
787 				        &expt, &signflag, &dtoaend);
788 			} else {
789 				fparg.dbl = GETARG(double);
790 				dtoaresult =
791 				    __hdtoa(fparg.dbl, xdigs, prec,
792 				        &expt, &signflag, &dtoaend);
793 			}
794 			if (prec < 0)
795 				prec = dtoaend - dtoaresult;
796 			if (expt == INT_MAX)
797 				ox[1] = '\0';
798 			if (convbuf != NULL)
799 				free(convbuf);
800 			ndig = dtoaend - dtoaresult;
801 			cp = convbuf = __mbsconv(dtoaresult, -1);
802 			freedtoa(dtoaresult);
803 			goto fp_common;
804 		case 'e':
805 		case 'E':
806 			expchar = ch;
807 			if (prec < 0)	/* account for digit before decpt */
808 				prec = DEFPREC + 1;
809 			else
810 				prec++;
811 			goto fp_begin;
812 		case 'f':
813 		case 'F':
814 			expchar = '\0';
815 			goto fp_begin;
816 		case 'g':
817 		case 'G':
818 			expchar = ch - ('g' - 'e');
819 			if (prec == 0)
820 				prec = 1;
821 fp_begin:
822 			if (prec < 0)
823 				prec = DEFPREC;
824 			if (convbuf != NULL)
825 				free(convbuf);
826 			if (flags & LONGDBL) {
827 				fparg.ldbl = GETARG(long double);
828 				dtoaresult =
829 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
830 				    &expt, &signflag, &dtoaend);
831 			} else {
832 				fparg.dbl = GETARG(double);
833 				dtoaresult =
834 				    dtoa(fparg.dbl, expchar ? 2 : 3, prec,
835 				    &expt, &signflag, &dtoaend);
836 				if (expt == 9999)
837 					expt = INT_MAX;
838 			}
839 			ndig = dtoaend - dtoaresult;
840 			cp = convbuf = __mbsconv(dtoaresult, -1);
841 			freedtoa(dtoaresult);
842 fp_common:
843 			if (signflag)
844 				sign = '-';
845 			if (expt == INT_MAX) {	/* inf or nan */
846 				if (*cp == 'N') {
847 					cp = (ch >= 'a') ? L"nan" : L"NAN";
848 					sign = '\0';
849 				} else
850 					cp = (ch >= 'a') ? L"inf" : L"INF";
851 				size = 3;
852 				flags &= ~ZEROPAD;
853 				break;
854 			}
855 			flags |= FPT;
856 			if (ch == 'g' || ch == 'G') {
857 				if (expt > -4 && expt <= prec) {
858 					/* Make %[gG] smell like %[fF] */
859 					expchar = '\0';
860 					if (flags & ALT)
861 						prec -= expt;
862 					else
863 						prec = ndig - expt;
864 					if (prec < 0)
865 						prec = 0;
866 				} else {
867 					/*
868 					 * Make %[gG] smell like %[eE], but
869 					 * trim trailing zeroes if no # flag.
870 					 */
871 					if (!(flags & ALT))
872 						prec = ndig;
873 				}
874 			}
875 			if (expchar) {
876 				expsize = exponent(expstr, expt - 1, expchar);
877 				size = expsize + prec;
878 				if (prec > 1 || flags & ALT)
879 					++size;
880 			} else {
881 				/* space for digits before decimal point */
882 				if (expt > 0)
883 					size = expt;
884 				else	/* "0" */
885 					size = 1;
886 				/* space for decimal pt and following digits */
887 				if (prec || flags & ALT)
888 					size += prec + 1;
889 				if ((flags & GROUPING) && expt > 0)
890 					size += grouping_init(&gs, expt, locale);
891 			}
892 			break;
893 #endif /* !NO_FLOATING_POINT */
894 		case 'n':
895 			/*
896 			 * Assignment-like behavior is specified if the
897 			 * value overflows or is otherwise unrepresentable.
898 			 * C99 says to use `signed char' for %hhn conversions.
899 			 */
900 			if (flags & LLONGINT)
901 				*GETARG(long long *) = ret;
902 			else if (flags & SIZET)
903 				*GETARG(ssize_t *) = (ssize_t)ret;
904 			else if (flags & PTRDIFFT)
905 				*GETARG(ptrdiff_t *) = ret;
906 			else if (flags & INTMAXT)
907 				*GETARG(intmax_t *) = ret;
908 			else if (flags & LONGINT)
909 				*GETARG(long *) = ret;
910 			else if (flags & SHORTINT)
911 				*GETARG(short *) = ret;
912 			else if (flags & CHARINT)
913 				*GETARG(signed char *) = ret;
914 			else
915 				*GETARG(int *) = ret;
916 			continue;	/* no output */
917 		case 'O':
918 			flags |= LONGINT;
919 			/*FALLTHROUGH*/
920 		case 'o':
921 			if (flags & INTMAX_SIZE)
922 				ujval = UJARG();
923 			else
924 				ulval = UARG();
925 			base = 8;
926 			goto nosign;
927 		case 'p':
928 			/*-
929 			 * ``The argument shall be a pointer to void.  The
930 			 * value of the pointer is converted to a sequence
931 			 * of printable characters, in an implementation-
932 			 * defined manner.''
933 			 *	-- ANSI X3J11
934 			 */
935 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
936 			base = 16;
937 			xdigs = xdigs_lower;
938 			flags = flags | INTMAXT;
939 			ox[1] = 'x';
940 			goto nosign;
941 		case 'S':
942 			flags |= LONGINT;
943 			/*FALLTHROUGH*/
944 		case 's':
945 			if (flags & LONGINT) {
946 				if ((cp = GETARG(wchar_t *)) == NULL)
947 					cp = L"(null)";
948 			} else {
949 				char *mbp;
950 
951 				if (convbuf != NULL)
952 					free(convbuf);
953 				if ((mbp = GETARG(char *)) == NULL)
954 					cp = L"(null)";
955 				else {
956 					convbuf = __mbsconv(mbp, prec);
957 					if (convbuf == NULL) {
958 						fp->_flags |= __SERR;
959 						goto error;
960 					}
961 					cp = convbuf;
962 				}
963 			}
964 			size = (prec >= 0) ? wcsnlen(cp, prec) : wcslen(cp);
965 			sign = '\0';
966 			break;
967 		case 'U':
968 			flags |= LONGINT;
969 			/*FALLTHROUGH*/
970 		case 'u':
971 			if (flags & INTMAX_SIZE)
972 				ujval = UJARG();
973 			else
974 				ulval = UARG();
975 			base = 10;
976 			goto nosign;
977 		case 'X':
978 			xdigs = xdigs_upper;
979 			goto hex;
980 		case 'x':
981 			xdigs = xdigs_lower;
982 hex:
983 			if (flags & INTMAX_SIZE)
984 				ujval = UJARG();
985 			else
986 				ulval = UARG();
987 			base = 16;
988 			/* leading 0x/X only if non-zero */
989 			if (flags & ALT &&
990 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
991 				ox[1] = ch;
992 
993 			flags &= ~GROUPING;
994 			/* unsigned conversions */
995 nosign:			sign = '\0';
996 			/*-
997 			 * ``... diouXx conversions ... if a precision is
998 			 * specified, the 0 flag will be ignored.''
999 			 *	-- ANSI X3J11
1000 			 */
1001 number:			if ((dprec = prec) >= 0)
1002 				flags &= ~ZEROPAD;
1003 
1004 			/*-
1005 			 * ``The result of converting a zero value with an
1006 			 * explicit precision of zero is no characters.''
1007 			 *	-- ANSI X3J11
1008 			 *
1009 			 * ``The C Standard is clear enough as is.  The call
1010 			 * printf("%#.0o", 0) should print 0.''
1011 			 *	-- Defect Report #151
1012 			 */
1013 			cp = buf + BUF;
1014 			if (flags & INTMAX_SIZE) {
1015 				if (ujval != 0 || prec != 0 ||
1016 				    (flags & ALT && base == 8))
1017 					cp = __ujtoa(ujval, cp, base,
1018 					    flags & ALT, xdigs);
1019 			} else {
1020 				if (ulval != 0 || prec != 0 ||
1021 				    (flags & ALT && base == 8))
1022 					cp = __ultoa(ulval, cp, base,
1023 					    flags & ALT, xdigs);
1024 			}
1025 			size = buf + BUF - cp;
1026 			if (size > BUF)	/* should never happen */
1027 				abort();
1028 			if ((flags & GROUPING) && size != 0)
1029 				size += grouping_init(&gs, size, locale);
1030 			break;
1031 		default:	/* "%?" prints ?, unless ? is NUL */
1032 			if (ch == '\0')
1033 				goto done;
1034 invalid:
1035 			/* pretend it was %c with argument ch */
1036 			cp = buf;
1037 			*cp = ch;
1038 			size = 1;
1039 			sign = '\0';
1040 			break;
1041 		}
1042 
1043 		/*
1044 		 * All reasonable formats wind up here.  At this point, `cp'
1045 		 * points to a string which (if not flags&LADJUST) should be
1046 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1047 		 * first be prefixed by any sign or other prefix; otherwise,
1048 		 * it should be blank padded before the prefix is emitted.
1049 		 * After any left-hand padding and prefixing, emit zeroes
1050 		 * required by a decimal [diouxX] precision, then print the
1051 		 * string proper, then emit zeroes required by any leftover
1052 		 * floating precision; finally, if LADJUST, pad with blanks.
1053 		 *
1054 		 * Compute actual size, so we know how much to pad.
1055 		 * size excludes decimal prec; realsz includes it.
1056 		 */
1057 		realsz = dprec > size ? dprec : size;
1058 		if (sign)
1059 			realsz++;
1060 		if (ox[1])
1061 			realsz += 2;
1062 
1063 		prsize = width > realsz ? width : realsz;
1064 		if ((unsigned)ret + prsize > INT_MAX) {
1065 			ret = EOF;
1066 			errno = EOVERFLOW;
1067 			goto error;
1068 		}
1069 
1070 		/* right-adjusting blank padding */
1071 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1072 			PAD(width - realsz, blanks);
1073 
1074 		/* prefix */
1075 		if (sign)
1076 			PRINT(&sign, 1);
1077 
1078 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1079 			ox[0] = '0';
1080 			PRINT(ox, 2);
1081 		}
1082 
1083 		/* right-adjusting zero padding */
1084 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1085 			PAD(width - realsz, zeroes);
1086 
1087 		/* the string or number proper */
1088 #ifndef NO_FLOATING_POINT
1089 		if ((flags & FPT) == 0) {
1090 #endif
1091 			/* leading zeroes from decimal precision */
1092 			PAD(dprec - size, zeroes);
1093 			if (gs.grouping) {
1094 				if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1095 					goto error;
1096 			} else {
1097 				PRINT(cp, size);
1098 			}
1099 #ifndef NO_FLOATING_POINT
1100 		} else {	/* glue together f_p fragments */
1101 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1102 				if (expt <= 0) {
1103 					PRINT(zeroes, 1);
1104 					if (prec || flags & ALT)
1105 						PRINT(&decimal_point, 1);
1106 					PAD(-expt, zeroes);
1107 					/* already handled initial 0's */
1108 					prec += expt;
1109 				} else {
1110 					if (gs.grouping) {
1111 						n = grouping_print(&gs, &io,
1112 						    cp, convbuf + ndig, locale);
1113 						if (n < 0)
1114 							goto error;
1115 						cp += n;
1116 					} else {
1117 						PRINTANDPAD(cp, convbuf + ndig,
1118 						    expt, zeroes);
1119 						cp += expt;
1120 					}
1121 					if (prec || flags & ALT)
1122 						PRINT(&decimal_point, 1);
1123 				}
1124 				PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1125 			} else {	/* %[eE] or sufficiently long %[gG] */
1126 				if (prec > 1 || flags & ALT) {
1127 					buf[0] = *cp++;
1128 					buf[1] = decimal_point;
1129 					PRINT(buf, 2);
1130 					PRINT(cp, ndig-1);
1131 					PAD(prec - ndig, zeroes);
1132 				} else	/* XeYYY */
1133 					PRINT(cp, 1);
1134 				PRINT(expstr, expsize);
1135 			}
1136 		}
1137 #endif
1138 		/* left-adjusting padding (always blank) */
1139 		if (flags & LADJUST)
1140 			PAD(width - realsz, blanks);
1141 
1142 		/* finally, adjust ret */
1143 		ret += prsize;
1144 
1145 		FLUSH();	/* copy out the I/O vectors */
1146 	}
1147 done:
1148 	FLUSH();
1149 error:
1150 	va_end(orgap);
1151 	if (convbuf != NULL)
1152 		free(convbuf);
1153 	if (__sferror(fp))
1154 		ret = EOF;
1155 	else
1156 		fp->_flags |= savserr;
1157 	if ((argtable != NULL) && (argtable != statargtable))
1158 		free (argtable);
1159 	return (ret);
1160 	/* NOTREACHED */
1161 }
1162