xref: /freebsd/lib/libc/stdio/vfprintf.c (revision 2e3f49888ec8851bafb22011533217487764fdb0)
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, const char *, va_list) __printflike(3, 0)
72 	__noinline;
73 static char	*__wcsconv(wchar_t *, int);
74 
75 #define	CHAR	char
76 #include "printfcommon.h"
77 
78 struct grouping_state {
79 	char *thousands_sep;	/* locale-specific thousands separator */
80 	int thousep_len;	/* length of thousands_sep */
81 	const char *grouping;	/* locale-specific numeric grouping rules */
82 	int lead;		/* sig figs before decimal or group sep */
83 	int nseps;		/* number of group separators with ' */
84 	int nrepeats;		/* number of repeats of the last group */
85 };
86 
87 /*
88  * Initialize the thousands' grouping state in preparation to print a
89  * number with ndigits digits. This routine returns the total number
90  * of bytes that will be needed.
91  */
92 static int
93 grouping_init(struct grouping_state *gs, int ndigits, locale_t loc)
94 {
95 	struct lconv *locale;
96 
97 	locale = localeconv_l(loc);
98 	gs->grouping = locale->grouping;
99 	gs->thousands_sep = locale->thousands_sep;
100 	gs->thousep_len = strlen(gs->thousands_sep);
101 
102 	gs->nseps = gs->nrepeats = 0;
103 	gs->lead = ndigits;
104 	while (*gs->grouping != CHAR_MAX) {
105 		if (gs->lead <= *gs->grouping)
106 			break;
107 		gs->lead -= *gs->grouping;
108 		if (*(gs->grouping+1)) {
109 			gs->nseps++;
110 			gs->grouping++;
111 		} else
112 			gs->nrepeats++;
113 	}
114 	return ((gs->nseps + gs->nrepeats) * gs->thousep_len);
115 }
116 
117 /*
118  * Print a number with thousands' separators.
119  */
120 static int
121 grouping_print(struct grouping_state *gs, struct io_state *iop,
122 	       const CHAR *cp, const CHAR *ep, locale_t locale)
123 {
124 	const CHAR *cp0 = cp;
125 
126 	if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
127 		return (-1);
128 	cp += gs->lead;
129 	while (gs->nseps > 0 || gs->nrepeats > 0) {
130 		if (gs->nrepeats > 0)
131 			gs->nrepeats--;
132 		else {
133 			gs->grouping--;
134 			gs->nseps--;
135 		}
136 		if (io_print(iop, gs->thousands_sep, gs->thousep_len, locale))
137 			return (-1);
138 		if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
139 			return (-1);
140 		cp += *gs->grouping;
141 	}
142 	if (cp > ep)
143 		cp = ep;
144 	return (cp - cp0);
145 }
146 
147 /*
148  * Flush out all the vectors defined by the given uio,
149  * then reset it so that it can be reused.
150  */
151 static int
152 __sprint(FILE *fp, struct __suio *uio, locale_t locale)
153 {
154 	int err;
155 
156 	if (uio->uio_resid == 0) {
157 		uio->uio_iovcnt = 0;
158 		return (0);
159 	}
160 	err = __sfvwrite(fp, uio);
161 	uio->uio_resid = 0;
162 	uio->uio_iovcnt = 0;
163 	return (err);
164 }
165 
166 /*
167  * Helper function for `fprintf to unbuffered unix file': creates a
168  * temporary buffer.  We only work on write-only files; this avoids
169  * worries about ungetc buffers and so forth.
170  */
171 static int
172 __sbprintf(FILE *fp, locale_t locale, const char *fmt, va_list ap)
173 {
174 	int ret;
175 	FILE fake = FAKE_FILE;
176 	unsigned char buf[BUFSIZ];
177 
178 	/* XXX This is probably not needed. */
179 	if (prepwrite(fp) != 0)
180 		return (EOF);
181 
182 	/* copy the important variables */
183 	fake._flags = fp->_flags & ~__SNBF;
184 	fake._file = fp->_file;
185 	fake._cookie = fp->_cookie;
186 	fake._write = fp->_write;
187 	fake._orientation = fp->_orientation;
188 	fake._mbstate = fp->_mbstate;
189 
190 	/* set up the buffer */
191 	fake._bf._base = fake._p = buf;
192 	fake._bf._size = fake._w = sizeof(buf);
193 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
194 
195 	/* do the work, then copy any error status */
196 	ret = __vfprintf(&fake, locale, fmt, ap);
197 	if (ret >= 0 && __fflush(&fake))
198 		ret = EOF;
199 	if (fake._flags & __SERR)
200 		fp->_flags |= __SERR;
201 	return (ret);
202 }
203 
204 /*
205  * Convert a wide character string argument for the %ls format to a multibyte
206  * string representation. If not -1, prec specifies the maximum number of
207  * bytes to output, and also means that we can't assume that the wide char.
208  * string ends is null-terminated.
209  */
210 static char *
211 __wcsconv(wchar_t *wcsarg, int prec)
212 {
213 	static const mbstate_t initial;
214 	mbstate_t mbs;
215 	char buf[MB_LEN_MAX];
216 	wchar_t *p;
217 	char *convbuf;
218 	size_t clen, nbytes;
219 
220 	/* Allocate space for the maximum number of bytes we could output. */
221 	if (prec < 0) {
222 		p = wcsarg;
223 		mbs = initial;
224 		nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
225 		if (nbytes == (size_t)-1)
226 			return (NULL);
227 	} else {
228 		/*
229 		 * Optimisation: if the output precision is small enough,
230 		 * just allocate enough memory for the maximum instead of
231 		 * scanning the string.
232 		 */
233 		if (prec < 128)
234 			nbytes = prec;
235 		else {
236 			nbytes = 0;
237 			p = wcsarg;
238 			mbs = initial;
239 			for (;;) {
240 				clen = wcrtomb(buf, *p++, &mbs);
241 				if (clen == 0 || clen == (size_t)-1 ||
242 				    nbytes + clen > prec)
243 					break;
244 				nbytes += clen;
245 			}
246 		}
247 	}
248 	if ((convbuf = malloc(nbytes + 1)) == NULL)
249 		return (NULL);
250 
251 	/* Fill the output buffer. */
252 	p = wcsarg;
253 	mbs = initial;
254 	if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
255 	    nbytes, &mbs)) == (size_t)-1) {
256 		free(convbuf);
257 		return (NULL);
258 	}
259 	convbuf[nbytes] = '\0';
260 	return (convbuf);
261 }
262 
263 /*
264  * MT-safe version
265  */
266 int
267 vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0,
268 		va_list ap)
269 {
270 	int ret;
271 	FIX_LOCALE(locale);
272 
273 	FLOCKFILE_CANCELSAFE(fp);
274 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
275 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
276 	    fp->_file >= 0)
277 		ret = __sbprintf(fp, locale, fmt0, ap);
278 	else
279 		ret = __vfprintf(fp, locale, fmt0, ap);
280 	FUNLOCKFILE_CANCELSAFE();
281 	return (ret);
282 }
283 int
284 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
285 {
286 	return vfprintf_l(fp, __get_locale(), fmt0, ap);
287 }
288 
289 /*
290  * The size of the buffer we use as scratch space for integer
291  * conversions, among other things.  We need enough space to
292  * write a uintmax_t in octal (plus one byte).
293  */
294 #if UINTMAX_MAX <= UINT64_MAX
295 #define	BUF	32
296 #else
297 #error "BUF must be large enough to format a uintmax_t"
298 #endif
299 
300 /*
301  * Non-MT-safe version
302  */
303 int
304 __vfprintf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
305 {
306 	char *fmt;		/* format string */
307 	int ch;			/* character from fmt */
308 	int n, n2;		/* handy integer (short term usage) */
309 	char *cp;		/* handy char pointer (short term usage) */
310 	int flags;		/* flags as above */
311 	int ret;		/* return value accumulator */
312 	int width;		/* width from format (%8d), or 0 */
313 	int prec;		/* precision from format; <0 for N/A */
314 	int saved_errno;
315 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
316 	struct grouping_state gs; /* thousands' grouping info */
317 
318 #ifndef NO_FLOATING_POINT
319 	/*
320 	 * We can decompose the printed representation of floating
321 	 * point numbers into several parts, some of which may be empty:
322 	 *
323 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
324 	 *    A       B     ---C---      D       E   F
325 	 *
326 	 * A:	'sign' holds this value if present; '\0' otherwise
327 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
328 	 * C:	cp points to the string MMMNNN.  Leading and trailing
329 	 *	zeros are not in the string and must be added.
330 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
331 	 * F:	at least two digits for decimal, at least one digit for hex
332 	 */
333 	char *decimal_point;	/* locale specific decimal point */
334 	int decpt_len;		/* length of decimal_point */
335 	int signflag;		/* true if float is negative */
336 	union {			/* floating point arguments %[aAeEfFgG] */
337 		double dbl;
338 		long double ldbl;
339 	} fparg;
340 	int expt;		/* integer value of exponent */
341 	char expchar;		/* exponent character: [eEpP\0] */
342 	char *dtoaend;		/* pointer to end of converted digits */
343 	int expsize;		/* character count for expstr */
344 	int ndig;		/* actual number of digits returned by dtoa */
345 	char expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
346 	char *dtoaresult;	/* buffer allocated by dtoa */
347 #endif
348 	u_long	ulval;		/* integer arguments %[diouxX] */
349 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
350 	int base;		/* base for [diouxX] conversion */
351 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
352 	int realsz;		/* field size expanded by dprec, sign, etc */
353 	int size;		/* size of converted field or string */
354 	int prsize;             /* max size of printed field */
355 	const char *xdigs;     	/* digits for %[xX] conversion */
356 	struct io_state io;	/* I/O buffering state */
357 	char buf[BUF];		/* buffer with space for digits of uintmax_t */
358 	char ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
359 	union arg *argtable;    /* args, built due to positional arg */
360 	union arg statargtable [STATIC_ARG_TBL_SIZE];
361 	int nextarg;            /* 1-based argument index */
362 	va_list orgap;          /* original argument pointer */
363 	char *convbuf;		/* wide to multibyte conversion result */
364 	int savserr;
365 
366 	static const char xdigs_lower[16] = "0123456789abcdef";
367 	static const char xdigs_upper[16] = "0123456789ABCDEF";
368 
369 	/* BEWARE, these `goto error' on error. */
370 #define	PRINT(ptr, len) { \
371 	if (io_print(&io, (ptr), (len), locale))	\
372 		goto error; \
373 }
374 #define	PAD(howmany, with) { \
375 	if (io_pad(&io, (howmany), (with), locale)) \
376 		goto error; \
377 }
378 #define	PRINTANDPAD(p, ep, len, with) {	\
379 	if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
380 		goto error; \
381 }
382 #define	FLUSH() { \
383 	if (io_flush(&io, locale)) \
384 		goto error; \
385 }
386 
387 	/*
388 	 * Get the argument indexed by nextarg.   If the argument table is
389 	 * built, use it to get the argument.  If its not, get the next
390 	 * argument (and arguments must be gotten sequentially).
391 	 */
392 #define GETARG(type) \
393 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
394 	    (nextarg++, va_arg(ap, type)))
395 
396 	/*
397 	 * To extend shorts properly, we need both signed and unsigned
398 	 * argument extraction methods.
399 	 */
400 #define	SARG() \
401 	(flags&LONGINT ? GETARG(long) : \
402 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
403 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
404 	    (long)GETARG(int))
405 #define	UARG() \
406 	(flags&LONGINT ? GETARG(u_long) : \
407 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
408 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
409 	    (u_long)GETARG(u_int))
410 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
411 #define SJARG() \
412 	(flags&INTMAXT ? GETARG(intmax_t) : \
413 	    flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
414 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
415 	    (intmax_t)GETARG(long long))
416 #define	UJARG() \
417 	(flags&INTMAXT ? GETARG(uintmax_t) : \
418 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
419 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
420 	    (uintmax_t)GETARG(unsigned long long))
421 
422 	/*
423 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
424 	 * that the argument can be gotten once the type is determined.
425 	 */
426 #define GETASTER(val) \
427 	n2 = 0; \
428 	cp = fmt; \
429 	while (is_digit(*cp)) { \
430 		n2 = 10 * n2 + to_digit(*cp); \
431 		cp++; \
432 	} \
433 	if (*cp == '$') { \
434 		int hold = nextarg; \
435 		if (argtable == NULL) { \
436 			argtable = statargtable; \
437 			if (__find_arguments (fmt0, orgap, &argtable)) { \
438 				ret = EOF; \
439 				goto error; \
440 			} \
441 		} \
442 		nextarg = n2; \
443 		val = GETARG (int); \
444 		nextarg = hold; \
445 		fmt = ++cp; \
446 	} else { \
447 		val = GETARG (int); \
448 	}
449 
450 	if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
451 		__use_xprintf = 1;
452 	if (__use_xprintf > 0)
453 		return (__xvprintf(fp, fmt0, ap));
454 
455 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
456 	if (prepwrite(fp) != 0) {
457 		errno = EBADF;
458 		return (EOF);
459 	}
460 
461 	savserr = fp->_flags & __SERR;
462 	fp->_flags &= ~__SERR;
463 
464 	saved_errno = errno;
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 			cp = strerror(saved_errno);
833 			size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
834 			sign = '\0';
835 			break;
836 		case 'n':
837 			/*
838 			 * Assignment-like behavior is specified if the
839 			 * value overflows or is otherwise unrepresentable.
840 			 * C99 says to use `signed char' for %hhn conversions.
841 			 */
842 			if (flags & LLONGINT)
843 				*GETARG(long long *) = ret;
844 			else if (flags & SIZET)
845 				*GETARG(ssize_t *) = (ssize_t)ret;
846 			else if (flags & PTRDIFFT)
847 				*GETARG(ptrdiff_t *) = ret;
848 			else if (flags & INTMAXT)
849 				*GETARG(intmax_t *) = ret;
850 			else if (flags & LONGINT)
851 				*GETARG(long *) = ret;
852 			else if (flags & SHORTINT)
853 				*GETARG(short *) = ret;
854 			else if (flags & CHARINT)
855 				*GETARG(signed char *) = ret;
856 			else
857 				*GETARG(int *) = ret;
858 			continue;	/* no output */
859 		case 'O':
860 			flags |= LONGINT;
861 			/*FALLTHROUGH*/
862 		case 'o':
863 			if (flags & INTMAX_SIZE)
864 				ujval = UJARG();
865 			else
866 				ulval = UARG();
867 			base = 8;
868 			goto nosign;
869 		case 'p':
870 			/*-
871 			 * ``The argument shall be a pointer to void.  The
872 			 * value of the pointer is converted to a sequence
873 			 * of printable characters, in an implementation-
874 			 * defined manner.''
875 			 *	-- ANSI X3J11
876 			 */
877 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
878 			base = 16;
879 			xdigs = xdigs_lower;
880 			flags = flags | INTMAXT;
881 			ox[1] = 'x';
882 			goto nosign;
883 		case 'S':
884 			flags |= LONGINT;
885 			/*FALLTHROUGH*/
886 		case 's':
887 			if (flags & LONGINT) {
888 				wchar_t *wcp;
889 
890 				if (convbuf != NULL)
891 					free(convbuf);
892 				if ((wcp = GETARG(wchar_t *)) == NULL)
893 					cp = "(null)";
894 				else {
895 					convbuf = __wcsconv(wcp, prec);
896 					if (convbuf == NULL) {
897 						fp->_flags |= __SERR;
898 						goto error;
899 					}
900 					cp = convbuf;
901 				}
902 			} else if ((cp = GETARG(char *)) == NULL)
903 				cp = "(null)";
904 			size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
905 			sign = '\0';
906 			break;
907 		case 'U':
908 			flags |= LONGINT;
909 			/*FALLTHROUGH*/
910 		case 'u':
911 			if (flags & INTMAX_SIZE)
912 				ujval = UJARG();
913 			else
914 				ulval = UARG();
915 			base = 10;
916 			goto nosign;
917 		case 'X':
918 			xdigs = xdigs_upper;
919 			goto hex;
920 		case 'x':
921 			xdigs = xdigs_lower;
922 hex:
923 			if (flags & INTMAX_SIZE)
924 				ujval = UJARG();
925 			else
926 				ulval = UARG();
927 			base = 16;
928 			/* leading 0x/X only if non-zero */
929 			if (flags & ALT &&
930 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
931 				ox[1] = ch;
932 
933 			flags &= ~GROUPING;
934 			/* unsigned conversions */
935 nosign:			sign = '\0';
936 			/*-
937 			 * ``... diouXx conversions ... if a precision is
938 			 * specified, the 0 flag will be ignored.''
939 			 *	-- ANSI X3J11
940 			 */
941 number:			if ((dprec = prec) >= 0)
942 				flags &= ~ZEROPAD;
943 
944 			/*-
945 			 * ``The result of converting a zero value with an
946 			 * explicit precision of zero is no characters.''
947 			 *	-- ANSI X3J11
948 			 *
949 			 * ``The C Standard is clear enough as is.  The call
950 			 * printf("%#.0o", 0) should print 0.''
951 			 *	-- Defect Report #151
952 			 */
953 			cp = buf + BUF;
954 			if (flags & INTMAX_SIZE) {
955 				if (ujval != 0 || prec != 0 ||
956 				    (flags & ALT && base == 8))
957 					cp = __ujtoa(ujval, cp, base,
958 					    flags & ALT, xdigs);
959 			} else {
960 				if (ulval != 0 || prec != 0 ||
961 				    (flags & ALT && base == 8))
962 					cp = __ultoa(ulval, cp, base,
963 					    flags & ALT, xdigs);
964 			}
965 			size = buf + BUF - cp;
966 			if (size > BUF)	/* should never happen */
967 				abort();
968 			if ((flags & GROUPING) && size != 0)
969 				size += grouping_init(&gs, size, locale);
970 			break;
971 		default:	/* "%?" prints ?, unless ? is NUL */
972 			if (ch == '\0')
973 				goto done;
974 invalid:
975 			/* pretend it was %c with argument ch */
976 			cp = buf;
977 			*cp = ch;
978 			size = 1;
979 			sign = '\0';
980 			break;
981 		}
982 
983 		/*
984 		 * All reasonable formats wind up here.  At this point, `cp'
985 		 * points to a string which (if not flags&LADJUST) should be
986 		 * padded out to `width' places.  If flags&ZEROPAD, it should
987 		 * first be prefixed by any sign or other prefix; otherwise,
988 		 * it should be blank padded before the prefix is emitted.
989 		 * After any left-hand padding and prefixing, emit zeroes
990 		 * required by a decimal [diouxX] precision, then print the
991 		 * string proper, then emit zeroes required by any leftover
992 		 * floating precision; finally, if LADJUST, pad with blanks.
993 		 *
994 		 * Compute actual size, so we know how much to pad.
995 		 * size excludes decimal prec; realsz includes it.
996 		 */
997 		realsz = dprec > size ? dprec : size;
998 		if (sign)
999 			realsz++;
1000 		if (ox[1])
1001 			realsz += 2;
1002 
1003 		prsize = width > realsz ? width : realsz;
1004 		if ((unsigned)ret + prsize > INT_MAX) {
1005 			ret = EOF;
1006 			errno = EOVERFLOW;
1007 			goto error;
1008 		}
1009 
1010 		/* right-adjusting blank padding */
1011 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1012 			PAD(width - realsz, blanks);
1013 
1014 		/* prefix */
1015 		if (sign)
1016 			PRINT(&sign, 1);
1017 
1018 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1019 			ox[0] = '0';
1020 			PRINT(ox, 2);
1021 		}
1022 
1023 		/* right-adjusting zero padding */
1024 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1025 			PAD(width - realsz, zeroes);
1026 
1027 		/* the string or number proper */
1028 #ifndef NO_FLOATING_POINT
1029 		if ((flags & FPT) == 0) {
1030 #endif
1031 			/* leading zeroes from decimal precision */
1032 			PAD(dprec - size, zeroes);
1033 			if (gs.grouping) {
1034 				if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1035 					goto error;
1036 			} else {
1037 				PRINT(cp, size);
1038 			}
1039 #ifndef NO_FLOATING_POINT
1040 		} else {	/* glue together f_p fragments */
1041 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1042 				if (expt <= 0) {
1043 					PRINT(zeroes, 1);
1044 					if (prec || flags & ALT)
1045 						PRINT(decimal_point,decpt_len);
1046 					PAD(-expt, zeroes);
1047 					/* already handled initial 0's */
1048 					prec += expt;
1049 				} else {
1050 					if (gs.grouping) {
1051 						n = grouping_print(&gs, &io,
1052 						    cp, dtoaend, locale);
1053 						if (n < 0)
1054 							goto error;
1055 						cp += n;
1056 					} else {
1057 						PRINTANDPAD(cp, dtoaend,
1058 						    expt, zeroes);
1059 						cp += expt;
1060 					}
1061 					if (prec || flags & ALT)
1062 						PRINT(decimal_point,decpt_len);
1063 				}
1064 				PRINTANDPAD(cp, dtoaend, prec, zeroes);
1065 			} else {	/* %[eE] or sufficiently long %[gG] */
1066 				if (prec > 1 || flags & ALT) {
1067 					PRINT(cp++, 1);
1068 					PRINT(decimal_point, decpt_len);
1069 					PRINT(cp, ndig-1);
1070 					PAD(prec - ndig, zeroes);
1071 				} else	/* XeYYY */
1072 					PRINT(cp, 1);
1073 				PRINT(expstr, expsize);
1074 			}
1075 		}
1076 #endif
1077 		/* left-adjusting padding (always blank) */
1078 		if (flags & LADJUST)
1079 			PAD(width - realsz, blanks);
1080 
1081 		/* finally, adjust ret */
1082 		ret += prsize;
1083 
1084 		FLUSH();	/* copy out the I/O vectors */
1085 	}
1086 done:
1087 	FLUSH();
1088 error:
1089 	va_end(orgap);
1090 #ifndef NO_FLOATING_POINT
1091 	if (dtoaresult != NULL)
1092 		freedtoa(dtoaresult);
1093 #endif
1094 	if (convbuf != NULL)
1095 		free(convbuf);
1096 	if (__sferror(fp))
1097 		ret = EOF;
1098 	else
1099 		fp->_flags |= savserr;
1100 	if ((argtable != NULL) && (argtable != statargtable))
1101 		free (argtable);
1102 	return (ret);
1103 	/* NOTREACHED */
1104 }
1105 
1106