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