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