xref: /freebsd/lib/libc/stdio/vfprintf.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
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 binary.
295  */
296 #define BUF	(sizeof(uintmax_t) * CHAR_BIT)
297 
298 /*
299  * Non-MT-safe version
300  */
301 int
302 __vfprintf(FILE *fp, locale_t locale, int serrno, const char *fmt0, va_list ap)
303 {
304 	char *fmt;		/* format string */
305 	int ch;			/* character from fmt */
306 	int n, n2;		/* handy integer (short term usage) */
307 	char *cp;		/* handy char pointer (short term usage) */
308 	int flags;		/* flags as above */
309 	int ret;		/* return value accumulator */
310 	int width;		/* width from format (%8d), or 0 */
311 	int prec;		/* precision from format; <0 for N/A */
312 	int error;
313 	char errnomsg[NL_TEXTMAX];
314 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
315 	struct grouping_state gs; /* thousands' grouping info */
316 
317 #ifndef NO_FLOATING_POINT
318 	/*
319 	 * We can decompose the printed representation of floating
320 	 * point numbers into several parts, some of which may be empty:
321 	 *
322 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
323 	 *    A       B     ---C---      D       E   F
324 	 *
325 	 * A:	'sign' holds this value if present; '\0' otherwise
326 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
327 	 * C:	cp points to the string MMMNNN.  Leading and trailing
328 	 *	zeros are not in the string and must be added.
329 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
330 	 * F:	at least two digits for decimal, at least one digit for hex
331 	 */
332 	char *decimal_point;	/* locale specific decimal point */
333 	int decpt_len;		/* length of decimal_point */
334 	int signflag;		/* true if float is negative */
335 	union {			/* floating point arguments %[aAeEfFgG] */
336 		double dbl;
337 		long double ldbl;
338 	} fparg;
339 	int expt;		/* integer value of exponent */
340 	char expchar;		/* exponent character: [eEpP\0] */
341 	char *dtoaend;		/* pointer to end of converted digits */
342 	int expsize;		/* character count for expstr */
343 	int ndig;		/* actual number of digits returned by dtoa */
344 	char expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
345 	char *dtoaresult;	/* buffer allocated by dtoa */
346 #endif
347 	u_long	ulval;		/* integer arguments %[diouxX] */
348 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
349 	int base;		/* base for [diouxX] conversion */
350 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
351 	int realsz;		/* field size expanded by dprec, sign, etc */
352 	int size;		/* size of converted field or string */
353 	int prsize;             /* max size of printed field */
354 	const char *xdigs;     	/* digits for %[xX] conversion */
355 	struct io_state io;	/* I/O buffering state */
356 	char buf[BUF];		/* buffer with space for digits of uintmax_t */
357 	char ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
358 	union arg *argtable;    /* args, built due to positional arg */
359 	union arg statargtable [STATIC_ARG_TBL_SIZE];
360 	int nextarg;            /* 1-based argument index */
361 	va_list orgap;          /* original argument pointer */
362 	char *convbuf;		/* wide to multibyte conversion result */
363 	int savserr;
364 
365 	static const char xdigs_lower[16] = "0123456789abcdef";
366 	static const char xdigs_upper[16] = "0123456789ABCDEF";
367 
368 	/* BEWARE, these `goto error' on error. */
369 #define	PRINT(ptr, len) { \
370 	if (io_print(&io, (ptr), (len), locale))	\
371 		goto error; \
372 }
373 #define	PAD(howmany, with) { \
374 	if (io_pad(&io, (howmany), (with), locale)) \
375 		goto error; \
376 }
377 #define	PRINTANDPAD(p, ep, len, with) {	\
378 	if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
379 		goto error; \
380 }
381 #define	FLUSH() { \
382 	if (io_flush(&io, locale)) \
383 		goto error; \
384 }
385 
386 	/*
387 	 * Get the argument indexed by nextarg.   If the argument table is
388 	 * built, use it to get the argument.  If its not, get the next
389 	 * argument (and arguments must be gotten sequentially).
390 	 */
391 #define GETARG(type) \
392 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
393 	    (nextarg++, va_arg(ap, type)))
394 
395 	/*
396 	 * To extend shorts properly, we need both signed and unsigned
397 	 * argument extraction methods.
398 	 */
399 #define	SARG() \
400 	(flags&LONGINT ? GETARG(long) : \
401 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
402 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
403 	    (long)GETARG(int))
404 #define	UARG() \
405 	(flags&LONGINT ? GETARG(u_long) : \
406 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
407 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
408 	    (u_long)GETARG(u_int))
409 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
410 #define SJARG() \
411 	(flags&INTMAXT ? GETARG(intmax_t) : \
412 	    flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
413 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
414 	    (intmax_t)GETARG(long long))
415 #define	UJARG() \
416 	(flags&INTMAXT ? GETARG(uintmax_t) : \
417 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
418 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
419 	    (uintmax_t)GETARG(unsigned long long))
420 
421 	/*
422 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
423 	 * that the argument can be gotten once the type is determined.
424 	 */
425 #define GETASTER(val) \
426 	n2 = 0; \
427 	cp = fmt; \
428 	while (is_digit(*cp)) { \
429 		n2 = 10 * n2 + to_digit(*cp); \
430 		cp++; \
431 	} \
432 	if (*cp == '$') { \
433 		int hold = nextarg; \
434 		if (argtable == NULL) { \
435 			argtable = statargtable; \
436 			if (__find_arguments (fmt0, orgap, &argtable)) { \
437 				ret = EOF; \
438 				goto error; \
439 			} \
440 		} \
441 		nextarg = n2; \
442 		val = GETARG (int); \
443 		nextarg = hold; \
444 		fmt = ++cp; \
445 	} else { \
446 		val = GETARG (int); \
447 	}
448 
449 	if (__use_xprintf > 0)
450 		return (__xvprintf(fp, fmt0, ap));
451 
452 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
453 	if (prepwrite(fp) != 0) {
454 		errno = EBADF;
455 		return (EOF);
456 	}
457 
458 	savserr = fp->_flags & __SERR;
459 	fp->_flags &= ~__SERR;
460 
461 	convbuf = NULL;
462 	fmt = (char *)fmt0;
463 	argtable = NULL;
464 	nextarg = 1;
465 	va_copy(orgap, ap);
466 	io_init(&io, fp);
467 	ret = 0;
468 #ifndef NO_FLOATING_POINT
469 	dtoaresult = NULL;
470 	decimal_point = localeconv_l(locale)->decimal_point;
471 	/* The overwhelmingly common case is decpt_len == 1. */
472 	decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
473 #endif
474 
475 	/*
476 	 * Scan the format for conversions (`%' character).
477 	 */
478 	for (;;) {
479 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
480 			/* void */;
481 		if ((n = fmt - cp) != 0) {
482 			if ((unsigned)ret + n > INT_MAX) {
483 				ret = EOF;
484 				errno = EOVERFLOW;
485 				goto error;
486 			}
487 			PRINT(cp, n);
488 			ret += n;
489 		}
490 		if (ch == '\0')
491 			goto done;
492 		fmt++;		/* skip over '%' */
493 
494 		flags = 0;
495 		dprec = 0;
496 		width = 0;
497 		prec = -1;
498 		gs.grouping = NULL;
499 		sign = '\0';
500 		ox[1] = '\0';
501 
502 rflag:		ch = *fmt++;
503 reswitch:	switch (ch) {
504 		case ' ':
505 			/*-
506 			 * ``If the space and + flags both appear, the space
507 			 * flag will be ignored.''
508 			 *	-- ANSI X3J11
509 			 */
510 			if (!sign)
511 				sign = ' ';
512 			goto rflag;
513 		case '#':
514 			flags |= ALT;
515 			goto rflag;
516 		case '*':
517 			/*-
518 			 * ``A negative field width argument is taken as a
519 			 * - flag followed by a positive field width.''
520 			 *	-- ANSI X3J11
521 			 * They don't exclude field widths read from args.
522 			 */
523 			GETASTER (width);
524 			if (width >= 0)
525 				goto rflag;
526 			width = -width;
527 			/* FALLTHROUGH */
528 		case '-':
529 			flags |= LADJUST;
530 			goto rflag;
531 		case '+':
532 			sign = '+';
533 			goto rflag;
534 		case '\'':
535 			flags |= GROUPING;
536 			goto rflag;
537 		case '.':
538 			if ((ch = *fmt++) == '*') {
539 				GETASTER (prec);
540 				goto rflag;
541 			}
542 			prec = 0;
543 			while (is_digit(ch)) {
544 				prec = 10 * prec + to_digit(ch);
545 				ch = *fmt++;
546 			}
547 			goto reswitch;
548 		case '0':
549 			/*-
550 			 * ``Note that 0 is taken as a flag, not as the
551 			 * beginning of a field width.''
552 			 *	-- ANSI X3J11
553 			 */
554 			flags |= ZEROPAD;
555 			goto rflag;
556 		case '1': case '2': case '3': case '4':
557 		case '5': case '6': case '7': case '8': case '9':
558 			n = 0;
559 			do {
560 				n = 10 * n + to_digit(ch);
561 				ch = *fmt++;
562 			} while (is_digit(ch));
563 			if (ch == '$') {
564 				nextarg = n;
565 				if (argtable == NULL) {
566 					argtable = statargtable;
567 					if (__find_arguments (fmt0, orgap,
568 							      &argtable)) {
569 						ret = EOF;
570 						goto error;
571 					}
572 				}
573 				goto rflag;
574 			}
575 			width = n;
576 			goto reswitch;
577 #ifndef NO_FLOATING_POINT
578 		case 'L':
579 			flags |= LONGDBL;
580 			goto rflag;
581 #endif
582 		case 'h':
583 			if (flags & SHORTINT) {
584 				flags &= ~SHORTINT;
585 				flags |= CHARINT;
586 			} else
587 				flags |= SHORTINT;
588 			goto rflag;
589 		case 'j':
590 			flags |= INTMAXT;
591 			goto rflag;
592 		case 'l':
593 			if (flags & LONGINT) {
594 				flags &= ~LONGINT;
595 				flags |= LLONGINT;
596 			} else
597 				flags |= LONGINT;
598 			goto rflag;
599 		case 'q':
600 			flags |= LLONGINT;	/* not necessarily */
601 			goto rflag;
602 		case 't':
603 			flags |= PTRDIFFT;
604 			goto rflag;
605 		case 'w':
606 			/*
607 			 * Fixed-width integer types.  On all platforms we
608 			 * support, int8_t is equivalent to char, int16_t
609 			 * is equivalent to short, int32_t is equivalent
610 			 * to int, int64_t is equivalent to long long int.
611 			 * Furthermore, int_fast8_t, int_fast16_t and
612 			 * int_fast32_t are equivalent to int, and
613 			 * int_fast64_t is equivalent to long long int.
614 			 */
615 			flags &= ~(CHARINT|SHORTINT|LONGINT|LLONGINT|INTMAXT);
616 			if (fmt[0] == 'f') {
617 				flags |= FASTINT;
618 				fmt++;
619 			} else {
620 				flags &= ~FASTINT;
621 			}
622 			if (fmt[0] == '8') {
623 				if (!(flags & FASTINT))
624 					flags |= CHARINT;
625 				else
626 					/* no flag set = 32 */ ;
627 				fmt += 1;
628 			} else if (fmt[0] == '1' && fmt[1] == '6') {
629 				if (!(flags & FASTINT))
630 					flags |= SHORTINT;
631 				else
632 					/* no flag set = 32 */ ;
633 				fmt += 2;
634 			} else if (fmt[0] == '3' && fmt[1] == '2') {
635 				/* no flag set = 32 */ ;
636 				fmt += 2;
637 			} else if (fmt[0] == '6' && fmt[1] == '4') {
638 				flags |= LLONGINT;
639 				fmt += 2;
640 			} else {
641 				if (flags & FASTINT) {
642 					flags &= ~FASTINT;
643 					fmt--;
644 				}
645 				goto invalid;
646 			}
647 			goto rflag;
648 		case 'z':
649 			flags |= SIZET;
650 			goto rflag;
651 		case 'B':
652 		case 'b':
653 			if (flags & INTMAX_SIZE)
654 				ujval = UJARG();
655 			else
656 				ulval = UARG();
657 			base = 2;
658 			/* leading 0b/B only if non-zero */
659 			if (flags & ALT &&
660 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
661 				ox[1] = ch;
662 			goto nosign;
663 			break;
664 		case 'C':
665 			flags |= LONGINT;
666 			/*FALLTHROUGH*/
667 		case 'c':
668 			if (flags & LONGINT) {
669 				static const mbstate_t initial;
670 				mbstate_t mbs;
671 				size_t mbseqlen;
672 
673 				mbs = initial;
674 				mbseqlen = wcrtomb(cp = buf,
675 				    (wchar_t)GETARG(wint_t), &mbs);
676 				if (mbseqlen == (size_t)-1) {
677 					fp->_flags |= __SERR;
678 					goto error;
679 				}
680 				size = (int)mbseqlen;
681 			} else {
682 				*(cp = buf) = GETARG(int);
683 				size = 1;
684 			}
685 			sign = '\0';
686 			break;
687 		case 'D':
688 			flags |= LONGINT;
689 			/*FALLTHROUGH*/
690 		case 'd':
691 		case 'i':
692 			if (flags & INTMAX_SIZE) {
693 				ujval = SJARG();
694 				if ((intmax_t)ujval < 0) {
695 					ujval = -ujval;
696 					sign = '-';
697 				}
698 			} else {
699 				ulval = SARG();
700 				if ((long)ulval < 0) {
701 					ulval = -ulval;
702 					sign = '-';
703 				}
704 			}
705 			base = 10;
706 			goto number;
707 #ifndef NO_FLOATING_POINT
708 		case 'a':
709 		case 'A':
710 			if (ch == 'a') {
711 				ox[1] = 'x';
712 				xdigs = xdigs_lower;
713 				expchar = 'p';
714 			} else {
715 				ox[1] = 'X';
716 				xdigs = xdigs_upper;
717 				expchar = 'P';
718 			}
719 			if (prec >= 0)
720 				prec++;
721 			if (dtoaresult != NULL)
722 				freedtoa(dtoaresult);
723 			if (flags & LONGDBL) {
724 				fparg.ldbl = GETARG(long double);
725 				dtoaresult = cp =
726 				    __hldtoa(fparg.ldbl, xdigs, prec,
727 				    &expt, &signflag, &dtoaend);
728 			} else {
729 				fparg.dbl = GETARG(double);
730 				dtoaresult = cp =
731 				    __hdtoa(fparg.dbl, xdigs, prec,
732 				    &expt, &signflag, &dtoaend);
733 			}
734 			if (prec < 0)
735 				prec = dtoaend - cp;
736 			if (expt == INT_MAX)
737 				ox[1] = '\0';
738 			goto fp_common;
739 		case 'e':
740 		case 'E':
741 			expchar = ch;
742 			if (prec < 0)	/* account for digit before decpt */
743 				prec = DEFPREC + 1;
744 			else
745 				prec++;
746 			goto fp_begin;
747 		case 'f':
748 		case 'F':
749 			expchar = '\0';
750 			goto fp_begin;
751 		case 'g':
752 		case 'G':
753 			expchar = ch - ('g' - 'e');
754 			if (prec == 0)
755 				prec = 1;
756 fp_begin:
757 			if (prec < 0)
758 				prec = DEFPREC;
759 			if (dtoaresult != NULL)
760 				freedtoa(dtoaresult);
761 			if (flags & LONGDBL) {
762 				fparg.ldbl = GETARG(long double);
763 				dtoaresult = cp =
764 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
765 				    &expt, &signflag, &dtoaend);
766 			} else {
767 				fparg.dbl = GETARG(double);
768 				dtoaresult = cp =
769 				    dtoa(fparg.dbl, expchar ? 2 : 3, prec,
770 				    &expt, &signflag, &dtoaend);
771 				if (expt == 9999)
772 					expt = INT_MAX;
773 			}
774 fp_common:
775 			if (signflag)
776 				sign = '-';
777 			if (expt == INT_MAX) {	/* inf or nan */
778 				if (*cp == 'N') {
779 					cp = (ch >= 'a') ? "nan" : "NAN";
780 					sign = '\0';
781 				} else
782 					cp = (ch >= 'a') ? "inf" : "INF";
783 				size = 3;
784 				flags &= ~ZEROPAD;
785 				break;
786 			}
787 			flags |= FPT;
788 			ndig = dtoaend - cp;
789 			if (ch == 'g' || ch == 'G') {
790 				if (expt > -4 && expt <= prec) {
791 					/* Make %[gG] smell like %[fF] */
792 					expchar = '\0';
793 					if (flags & ALT)
794 						prec -= expt;
795 					else
796 						prec = ndig - expt;
797 					if (prec < 0)
798 						prec = 0;
799 				} else {
800 					/*
801 					 * Make %[gG] smell like %[eE], but
802 					 * trim trailing zeroes if no # flag.
803 					 */
804 					if (!(flags & ALT))
805 						prec = ndig;
806 				}
807 			}
808 			if (expchar) {
809 				expsize = exponent(expstr, expt - 1, expchar);
810 				size = expsize + prec;
811 				if (prec > 1 || flags & ALT)
812 					size += decpt_len;
813 			} else {
814 				/* space for digits before decimal point */
815 				if (expt > 0)
816 					size = expt;
817 				else	/* "0" */
818 					size = 1;
819 				/* space for decimal pt and following digits */
820 				if (prec || flags & ALT)
821 					size += prec + decpt_len;
822 				if ((flags & GROUPING) && expt > 0)
823 					size += grouping_init(&gs, expt, locale);
824 			}
825 			break;
826 #endif /* !NO_FLOATING_POINT */
827 		case 'm':
828 			error = __strerror_rl(serrno, errnomsg,
829 			    sizeof(errnomsg), locale);
830 			cp = error == 0 ? errnomsg : "<strerror failure>";
831 			size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
832 			sign = '\0';
833 			break;
834 		case 'n':
835 			/*
836 			 * Assignment-like behavior is specified if the
837 			 * value overflows or is otherwise unrepresentable.
838 			 * C99 says to use `signed char' for %hhn conversions.
839 			 */
840 			if (flags & LLONGINT)
841 				*GETARG(long long *) = ret;
842 			else if (flags & SIZET)
843 				*GETARG(ssize_t *) = (ssize_t)ret;
844 			else if (flags & PTRDIFFT)
845 				*GETARG(ptrdiff_t *) = ret;
846 			else if (flags & INTMAXT)
847 				*GETARG(intmax_t *) = ret;
848 			else if (flags & LONGINT)
849 				*GETARG(long *) = ret;
850 			else if (flags & SHORTINT)
851 				*GETARG(short *) = ret;
852 			else if (flags & CHARINT)
853 				*GETARG(signed char *) = ret;
854 			else
855 				*GETARG(int *) = ret;
856 			continue;	/* no output */
857 		case 'O':
858 			flags |= LONGINT;
859 			/*FALLTHROUGH*/
860 		case 'o':
861 			if (flags & INTMAX_SIZE)
862 				ujval = UJARG();
863 			else
864 				ulval = UARG();
865 			base = 8;
866 			goto nosign;
867 		case 'p':
868 			/*-
869 			 * ``The argument shall be a pointer to void.  The
870 			 * value of the pointer is converted to a sequence
871 			 * of printable characters, in an implementation-
872 			 * defined manner.''
873 			 *	-- ANSI X3J11
874 			 */
875 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
876 			base = 16;
877 			xdigs = xdigs_lower;
878 			flags = flags | INTMAXT;
879 			ox[1] = 'x';
880 			goto nosign;
881 		case 'S':
882 			flags |= LONGINT;
883 			/*FALLTHROUGH*/
884 		case 's':
885 			if (flags & LONGINT) {
886 				wchar_t *wcp;
887 
888 				if (convbuf != NULL)
889 					free(convbuf);
890 				if ((wcp = GETARG(wchar_t *)) == NULL)
891 					cp = "(null)";
892 				else {
893 					convbuf = __wcsconv(wcp, prec);
894 					if (convbuf == NULL) {
895 						fp->_flags |= __SERR;
896 						goto error;
897 					}
898 					cp = convbuf;
899 				}
900 			} else if ((cp = GETARG(char *)) == NULL)
901 				cp = "(null)";
902 			size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
903 			sign = '\0';
904 			break;
905 		case 'U':
906 			flags |= LONGINT;
907 			/*FALLTHROUGH*/
908 		case 'u':
909 			if (flags & INTMAX_SIZE)
910 				ujval = UJARG();
911 			else
912 				ulval = UARG();
913 			base = 10;
914 			goto nosign;
915 		case 'X':
916 			xdigs = xdigs_upper;
917 			goto hex;
918 		case 'x':
919 			xdigs = xdigs_lower;
920 hex:
921 			if (flags & INTMAX_SIZE)
922 				ujval = UJARG();
923 			else
924 				ulval = UARG();
925 			base = 16;
926 			/* leading 0x/X only if non-zero */
927 			if (flags & ALT &&
928 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
929 				ox[1] = ch;
930 
931 			flags &= ~GROUPING;
932 			/* unsigned conversions */
933 nosign:			sign = '\0';
934 			/*-
935 			 * ``... diouXx conversions ... if a precision is
936 			 * specified, the 0 flag will be ignored.''
937 			 *	-- ANSI X3J11
938 			 */
939 number:			if ((dprec = prec) >= 0)
940 				flags &= ~ZEROPAD;
941 
942 			/*-
943 			 * ``The result of converting a zero value with an
944 			 * explicit precision of zero is no characters.''
945 			 *	-- ANSI X3J11
946 			 *
947 			 * ``The C Standard is clear enough as is.  The call
948 			 * printf("%#.0o", 0) should print 0.''
949 			 *	-- Defect Report #151
950 			 */
951 			cp = buf + BUF;
952 			if (flags & INTMAX_SIZE) {
953 				if (ujval != 0 || prec != 0 ||
954 				    (flags & ALT && base == 8))
955 					cp = __ujtoa(ujval, cp, base,
956 					    flags & ALT, xdigs);
957 			} else {
958 				if (ulval != 0 || prec != 0 ||
959 				    (flags & ALT && base == 8))
960 					cp = __ultoa(ulval, cp, base,
961 					    flags & ALT, xdigs);
962 			}
963 			size = buf + BUF - cp;
964 			if (size > BUF)	/* should never happen */
965 				abort();
966 			if ((flags & GROUPING) && size != 0)
967 				size += grouping_init(&gs, size, locale);
968 			break;
969 		default:	/* "%?" prints ?, unless ? is NUL */
970 			if (ch == '\0')
971 				goto done;
972 invalid:
973 			/* pretend it was %c with argument ch */
974 			cp = buf;
975 			*cp = ch;
976 			size = 1;
977 			sign = '\0';
978 			break;
979 		}
980 
981 		/*
982 		 * All reasonable formats wind up here.  At this point, `cp'
983 		 * points to a string which (if not flags&LADJUST) should be
984 		 * padded out to `width' places.  If flags&ZEROPAD, it should
985 		 * first be prefixed by any sign or other prefix; otherwise,
986 		 * it should be blank padded before the prefix is emitted.
987 		 * After any left-hand padding and prefixing, emit zeroes
988 		 * required by a decimal [diouxX] precision, then print the
989 		 * string proper, then emit zeroes required by any leftover
990 		 * floating precision; finally, if LADJUST, pad with blanks.
991 		 *
992 		 * Compute actual size, so we know how much to pad.
993 		 * size excludes decimal prec; realsz includes it.
994 		 */
995 		realsz = dprec > size ? dprec : size;
996 		if (sign)
997 			realsz++;
998 		if (ox[1])
999 			realsz += 2;
1000 
1001 		prsize = width > realsz ? width : realsz;
1002 		if ((unsigned)ret + prsize > INT_MAX) {
1003 			ret = EOF;
1004 			errno = EOVERFLOW;
1005 			goto error;
1006 		}
1007 
1008 		/* right-adjusting blank padding */
1009 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1010 			PAD(width - realsz, blanks);
1011 
1012 		/* prefix */
1013 		if (sign)
1014 			PRINT(&sign, 1);
1015 
1016 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1017 			ox[0] = '0';
1018 			PRINT(ox, 2);
1019 		}
1020 
1021 		/* right-adjusting zero padding */
1022 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1023 			PAD(width - realsz, zeroes);
1024 
1025 		/* the string or number proper */
1026 #ifndef NO_FLOATING_POINT
1027 		if ((flags & FPT) == 0) {
1028 #endif
1029 			/* leading zeroes from decimal precision */
1030 			PAD(dprec - size, zeroes);
1031 			if (gs.grouping) {
1032 				if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1033 					goto error;
1034 			} else {
1035 				PRINT(cp, size);
1036 			}
1037 #ifndef NO_FLOATING_POINT
1038 		} else {	/* glue together f_p fragments */
1039 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1040 				if (expt <= 0) {
1041 					PRINT(zeroes, 1);
1042 					if (prec || flags & ALT)
1043 						PRINT(decimal_point,decpt_len);
1044 					PAD(-expt, zeroes);
1045 					/* already handled initial 0's */
1046 					prec += expt;
1047 				} else {
1048 					if (gs.grouping) {
1049 						n = grouping_print(&gs, &io,
1050 						    cp, dtoaend, locale);
1051 						if (n < 0)
1052 							goto error;
1053 						cp += n;
1054 					} else {
1055 						PRINTANDPAD(cp, dtoaend,
1056 						    expt, zeroes);
1057 						cp += expt;
1058 					}
1059 					if (prec || flags & ALT)
1060 						PRINT(decimal_point,decpt_len);
1061 				}
1062 				PRINTANDPAD(cp, dtoaend, prec, zeroes);
1063 			} else {	/* %[eE] or sufficiently long %[gG] */
1064 				if (prec > 1 || flags & ALT) {
1065 					PRINT(cp++, 1);
1066 					PRINT(decimal_point, decpt_len);
1067 					PRINT(cp, ndig-1);
1068 					PAD(prec - ndig, zeroes);
1069 				} else	/* XeYYY */
1070 					PRINT(cp, 1);
1071 				PRINT(expstr, expsize);
1072 			}
1073 		}
1074 #endif
1075 		/* left-adjusting padding (always blank) */
1076 		if (flags & LADJUST)
1077 			PAD(width - realsz, blanks);
1078 
1079 		/* finally, adjust ret */
1080 		ret += prsize;
1081 
1082 		FLUSH();	/* copy out the I/O vectors */
1083 	}
1084 done:
1085 	FLUSH();
1086 error:
1087 	va_end(orgap);
1088 #ifndef NO_FLOATING_POINT
1089 	if (dtoaresult != NULL)
1090 		freedtoa(dtoaresult);
1091 #endif
1092 	if (convbuf != NULL)
1093 		free(convbuf);
1094 	if (__sferror(fp))
1095 		ret = EOF;
1096 	else
1097 		fp->_flags |= savserr;
1098 	if ((argtable != NULL) && (argtable != statargtable))
1099 		free (argtable);
1100 	return (ret);
1101 	/* NOTREACHED */
1102 }
1103 
1104