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