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