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