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