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