1219820Sjeff/*	$OpenBSD: vfprintf.c,v 1.82 2023/10/06 16:41:02 millert Exp $	*/
2219820Sjeff/*-
3272407Shselasky * Copyright (c) 1990 The Regents of the University of California.
4219820Sjeff * All rights reserved.
5219820Sjeff *
6219820Sjeff * This code is derived from software contributed to Berkeley by
7219820Sjeff * Chris Torek.
8219820Sjeff *
9219820Sjeff * Redistribution and use in source and binary forms, with or without
10219820Sjeff * modification, are permitted provided that the following conditions
11219820Sjeff * are met:
12219820Sjeff * 1. Redistributions of source code must retain the above copyright
13219820Sjeff *    notice, this list of conditions and the following disclaimer.
14219820Sjeff * 2. Redistributions in binary form must reproduce the above copyright
15219820Sjeff *    notice, this list of conditions and the following disclaimer in the
16219820Sjeff *    documentation and/or other materials provided with the distribution.
17219820Sjeff * 3. Neither the name of the University nor the names of its contributors
18219820Sjeff *    may be used to endorse or promote products derived from this software
19219820Sjeff *    without specific prior written permission.
20219820Sjeff *
21219820Sjeff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22219820Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23219820Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24219820Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25219820Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26219820Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27219820Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28219820Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29219820Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30219820Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31219820Sjeff * SUCH DAMAGE.
32219820Sjeff */
33219820Sjeff
34219820Sjeff/*
35219820Sjeff * Actual printf innards.
36219820Sjeff *
37272407Shselasky * This code is large and complicated...
38219820Sjeff */
39219820Sjeff
40219820Sjeff#include <sys/types.h>
41219820Sjeff#include <sys/mman.h>
42219820Sjeff
43219820Sjeff#include <errno.h>
44219820Sjeff#include <langinfo.h>
45219820Sjeff#include <limits.h>
46219820Sjeff#include <stdarg.h>
47219820Sjeff#include <stddef.h>
48219820Sjeff#include <stdio.h>
49219820Sjeff#include <stdint.h>
50219820Sjeff#include <stdlib.h>
51219820Sjeff#include <string.h>
52219820Sjeff#include <unistd.h>
53219820Sjeff#include <syslog.h>
54219820Sjeff#include <wchar.h>
55219820Sjeff
56219820Sjeff#include "local.h"
57219820Sjeff#include "fvwrite.h"
58219820Sjeff
59219820Sjeffunion arg {
60219820Sjeff	int			intarg;
61219820Sjeff	unsigned int		uintarg;
62219820Sjeff	long			longarg;
63219820Sjeff	unsigned long		ulongarg;
64219820Sjeff	long long		longlongarg;
65219820Sjeff	unsigned long long	ulonglongarg;
66219820Sjeff	ptrdiff_t		ptrdiffarg;
67219820Sjeff	size_t			sizearg;
68219820Sjeff	ssize_t			ssizearg;
69219820Sjeff	intmax_t		intmaxarg;
70219820Sjeff	uintmax_t		uintmaxarg;
71219820Sjeff	void			*pvoidarg;
72219820Sjeff	char			*pchararg;
73272407Shselasky	signed char		*pschararg;
74219820Sjeff	short			*pshortarg;
75272407Shselasky	int			*pintarg;
76219820Sjeff	long			*plongarg;
77219820Sjeff	long long		*plonglongarg;
78219820Sjeff	ptrdiff_t		*pptrdiffarg;
79219820Sjeff	ssize_t			*pssizearg;
80255932Salfred	intmax_t		*pintmaxarg;
81219820Sjeff#ifdef FLOATING_POINT
82219820Sjeff	double			doublearg;
83219820Sjeff	long double		longdoublearg;
84219820Sjeff#endif
85219820Sjeff#ifdef PRINTF_WIDE_CHAR
86219820Sjeff	wint_t			wintarg;
87255932Salfred	wchar_t			*pwchararg;
88255932Salfred#endif
89219820Sjeff};
90219820Sjeff
91219820Sjeffstatic int __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
92219820Sjeff    size_t *argtablesiz);
93219820Sjeffstatic int __grow_type_table(unsigned char **typetable, int *tablesize);
94219820Sjeff
95219820Sjeff/*
96219820Sjeff * Flush out all the vectors defined by the given uio,
97219820Sjeff * then reset it so that it can be reused.
98219820Sjeff */
99255932Salfredstatic int
100219820Sjeff__sprint(FILE *fp, struct __suio *uio)
101219820Sjeff{
102219820Sjeff	int err;
103219820Sjeff
104219820Sjeff	if (uio->uio_resid == 0) {
105219820Sjeff		uio->uio_iovcnt = 0;
106219820Sjeff		return (0);
107219820Sjeff	}
108255932Salfred	err = __sfvwrite(fp, uio);
109255932Salfred	uio->uio_resid = 0;
110219820Sjeff	uio->uio_iovcnt = 0;
111255932Salfred	return (err);
112219820Sjeff}
113255932Salfred
114219820Sjeff/*
115219820Sjeff * Helper function for `fprintf to unbuffered unix file': creates a
116219820Sjeff * temporary buffer.  We only work on write-only files; this avoids
117219820Sjeff * worries about ungetc buffers and so forth.
118219820Sjeff */
119255932Salfredstatic int
120219820Sjeff__sbprintf(FILE *fp, const char *fmt, va_list ap)
121219820Sjeff{
122219820Sjeff	int ret;
123219820Sjeff	FILE fake;
124255932Salfred	struct __sfileext fakeext;
125219820Sjeff	unsigned char buf[BUFSIZ];
126219820Sjeff
127219820Sjeff	_FILEEXT_SETUP(&fake, &fakeext);
128255932Salfred	/* copy the important variables */
129219820Sjeff	fake._flags = fp->_flags & ~__SNBF;
130219820Sjeff	fake._file = fp->_file;
131219820Sjeff	fake._cookie = fp->_cookie;
132219820Sjeff	fake._write = fp->_write;
133219820Sjeff
134219820Sjeff	/* set up the buffer */
135219820Sjeff	fake._bf._base = fake._p = buf;
136219820Sjeff	fake._bf._size = fake._w = sizeof(buf);
137219820Sjeff	fake._lbfsize = 0;	/* not actually used, but Just In Case */
138219820Sjeff
139219820Sjeff	/* do the work, then copy any error status */
140219820Sjeff	ret = __vfprintf(&fake, fmt, ap);
141219820Sjeff	if (ret >= 0 && __sflush(&fake))
142219820Sjeff		ret = EOF;
143219820Sjeff	if (fake._flags & __SERR)
144219820Sjeff		fp->_flags |= __SERR;
145219820Sjeff	return (ret);
146219820Sjeff}
147219820Sjeff
148219820Sjeff#ifdef PRINTF_WIDE_CHAR
149219820Sjeff/*
150219820Sjeff * Convert a wide character string argument for the %ls format to a multibyte
151272407Shselasky * string representation. If not -1, prec specifies the maximum number of
152272407Shselasky * bytes to output, and also means that we can't assume that the wide char
153219820Sjeff * string is null-terminated.
154219820Sjeff */
155219820Sjeffstatic char *
156219820Sjeff__wcsconv(wchar_t *wcsarg, int prec)
157272407Shselasky{
158272407Shselasky	mbstate_t mbs;
159272407Shselasky	char buf[MB_LEN_MAX];
160272407Shselasky	wchar_t *p;
161272407Shselasky	char *convbuf;
162255932Salfred	size_t clen, nbytes;
163219820Sjeff
164219820Sjeff	/* Allocate space for the maximum number of bytes we could output. */
165219820Sjeff	if (prec < 0) {
166219820Sjeff		memset(&mbs, 0, sizeof(mbs));
167219820Sjeff		p = wcsarg;
168219820Sjeff		nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
169219820Sjeff		if (nbytes == (size_t)-1)
170255932Salfred			return (NULL);
171255932Salfred	} else {
172255932Salfred		/*
173219820Sjeff		 * Optimisation: if the output precision is small enough,
174219820Sjeff		 * just allocate enough memory for the maximum instead of
175219820Sjeff		 * scanning the string.
176219820Sjeff		 */
177219820Sjeff		if (prec < 128)
178255932Salfred			nbytes = prec;
179255932Salfred		else {
180255932Salfred			nbytes = 0;
181219820Sjeff			p = wcsarg;
182219820Sjeff			memset(&mbs, 0, sizeof(mbs));
183219820Sjeff			for (;;) {
184219820Sjeff				clen = wcrtomb(buf, *p++, &mbs);
185219820Sjeff				if (clen == 0 || clen == (size_t)-1 ||
186219820Sjeff				    nbytes + clen > (size_t)prec)
187219820Sjeff					break;
188219820Sjeff				nbytes += clen;
189219820Sjeff			}
190219820Sjeff			if (clen == (size_t)-1)
191219820Sjeff				return (NULL);
192219820Sjeff		}
193255932Salfred	}
194219820Sjeff	if ((convbuf = malloc(nbytes + 1)) == NULL)
195219820Sjeff		return (NULL);
196219820Sjeff
197219820Sjeff	/* Fill the output buffer. */
198219820Sjeff	p = wcsarg;
199219820Sjeff	memset(&mbs, 0, sizeof(mbs));
200219820Sjeff	if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
201219820Sjeff	    nbytes, &mbs)) == (size_t)-1) {
202219820Sjeff		free(convbuf);
203219820Sjeff		return (NULL);
204219820Sjeff	}
205219820Sjeff	convbuf[nbytes] = '\0';
206219820Sjeff	return (convbuf);
207219820Sjeff}
208219820Sjeff#endif
209219820Sjeff
210219820Sjeff#ifdef FLOATING_POINT
211219820Sjeff#include <float.h>
212219820Sjeff#include <locale.h>
213219820Sjeff#include <math.h>
214219820Sjeff#include "floatio.h"
215219820Sjeff#include "gdtoa.h"
216219820Sjeff
217219820Sjeff#define	DEFPREC		6
218219820Sjeff
219219820Sjeffstatic int exponent(char *, int, int);
220219820Sjeff#endif /* FLOATING_POINT */
221219820Sjeff
222219820Sjeff/*
223219820Sjeff * The size of the buffer we use as scratch space for integer
224219820Sjeff * conversions, among other things.  Technically, we would need the
225219820Sjeff * most space for base 10 conversions with thousands' grouping
226219820Sjeff * characters between each pair of digits.  100 bytes is a
227219820Sjeff * conservative overestimate even for a 128-bit uintmax_t.
228219820Sjeff */
229219820Sjeff#define BUF	100
230219820Sjeff
231219820Sjeff#define STATIC_ARG_TBL_SIZE 8	/* Size of static argument table. */
232219820Sjeff
233219820Sjeff
234219820Sjeff/*
235219820Sjeff * Macros for converting digits to letters and vice versa
236219820Sjeff */
237219820Sjeff#define	to_digit(c)	((c) - '0')
238219820Sjeff#define is_digit(c)	((unsigned)to_digit(c) <= 9)
239255932Salfred#define	to_char(n)	((n) + '0')
240219820Sjeff
241219820Sjeff/*
242219820Sjeff * Flags used during conversion.
243219820Sjeff */
244219820Sjeff#define	ALT		0x0001		/* alternate form */
245219820Sjeff#define	LADJUST		0x0004		/* left adjustment */
246219820Sjeff#define	LONGDBL		0x0008		/* long double */
247219820Sjeff#define	LONGINT		0x0010		/* long integer */
248219820Sjeff#define	LLONGINT	0x0020		/* long long integer */
249219820Sjeff#define	SHORTINT	0x0040		/* short integer */
250219820Sjeff#define	ZEROPAD		0x0080		/* zero (as opposed to blank) pad */
251219820Sjeff#define FPT		0x0100		/* Floating point number */
252219820Sjeff#define PTRINT		0x0200		/* (unsigned) ptrdiff_t */
253219820Sjeff#define SIZEINT		0x0400		/* (signed) size_t */
254219820Sjeff#define CHARINT		0x0800		/* 8 bit integer */
255219820Sjeff#define MAXINT		0x1000		/* largest integer size (intmax_t) */
256219820Sjeff
257219820Sjeffint
258219820Sjeffvfprintf(FILE *fp, const char *fmt0, __va_list ap)
259219820Sjeff{
260219820Sjeff	int ret;
261219820Sjeff
262219820Sjeff	FLOCKFILE(fp);
263219820Sjeff	ret = __vfprintf(fp, fmt0, ap);
264219820Sjeff	FUNLOCKFILE(fp);
265219820Sjeff	return (ret);
266219820Sjeff}
267219820SjeffDEF_STRONG(vfprintf);
268219820Sjeff
269219820Sjeffint
270219820Sjeff__vfprintf(FILE *fp, const char *fmt0, __va_list ap)
271219820Sjeff{
272219820Sjeff	char *fmt;		/* format string */
273219820Sjeff	int ch;			/* character from fmt */
274219820Sjeff	int n, n2;		/* handy integers (short term usage) */
275219820Sjeff	char *cp;		/* handy char pointer (short term usage) */
276219820Sjeff	struct __siov *iovp;	/* for PRINT macro */
277219820Sjeff	int flags;		/* flags as above */
278219820Sjeff	int ret;		/* return value accumulator */
279219820Sjeff	int width;		/* width from format (%8d), or 0 */
280219820Sjeff	int prec;		/* precision from format; <0 for N/A */
281219820Sjeff	char sign;		/* sign prefix (' ', '+', '-', or \0) */
282219820Sjeff#ifdef FLOATING_POINT
283219820Sjeff	/*
284219820Sjeff	 * We can decompose the printed representation of floating
285219820Sjeff	 * point numbers into several parts, some of which may be empty:
286219820Sjeff	 *
287219820Sjeff	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
288219820Sjeff	 *    A       B     ---C---      D       E   F
289219820Sjeff	 *
290219820Sjeff	 * A:	'sign' holds this value if present; '\0' otherwise
291219820Sjeff	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
292219820Sjeff	 * C:	cp points to the string MMMNNN.  Leading and trailing
293219820Sjeff	 *	zeros are not in the string and must be added.
294219820Sjeff	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
295219820Sjeff	 * F:	at least two digits for decimal, at least one digit for hex
296219820Sjeff	 */
297219820Sjeff	char *decimal_point = NULL;
298219820Sjeff	int signflag;		/* true if float is negative */
299219820Sjeff	union {			/* floating point arguments %[aAeEfFgG] */
300219820Sjeff		double dbl;
301219820Sjeff		long double ldbl;
302219820Sjeff	} fparg;
303219820Sjeff	int expt;		/* integer value of exponent */
304219820Sjeff	char expchar;		/* exponent character: [eEpP\0] */
305219820Sjeff	char *dtoaend;		/* pointer to end of converted digits */
306219820Sjeff	int expsize;		/* character count for expstr */
307219820Sjeff	int lead;		/* sig figs before decimal or group sep */
308219820Sjeff	int ndig;		/* actual number of digits returned by dtoa */
309219820Sjeff	char expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
310219820Sjeff	char *dtoaresult = NULL;
311219820Sjeff#endif
312219820Sjeff
313219820Sjeff	uintmax_t _umax;	/* integer arguments %[diouxX] */
314219820Sjeff	enum { OCT, DEC, HEX } base;	/* base for %[diouxX] conversion */
315219820Sjeff	int dprec;		/* a copy of prec if %[diouxX], 0 otherwise */
316219820Sjeff	int realsz;		/* field size expanded by dprec */
317219820Sjeff	int size;		/* size of converted field or string */
318219820Sjeff	const char *xdigs;	/* digits for %[xX] conversion */
319219820Sjeff#define NIOV 8
320219820Sjeff	struct __suio uio;	/* output information: summary */
321219820Sjeff	struct __siov iov[NIOV];/* ... and individual io vectors */
322219820Sjeff	char buf[BUF];		/* buffer with space for digits of uintmax_t */
323219820Sjeff	char ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
324219820Sjeff	union arg *argtable;	/* args, built due to positional arg */
325219820Sjeff	union arg statargtable[STATIC_ARG_TBL_SIZE];
326219820Sjeff	size_t argtablesiz;
327219820Sjeff	int nextarg;		/* 1-based argument index */
328219820Sjeff	va_list orgap;		/* original argument pointer */
329219820Sjeff#ifdef PRINTF_WIDE_CHAR
330219820Sjeff	char *convbuf;		/* buffer for wide to multi-byte conversion */
331219820Sjeff#endif
332219820Sjeff
333219820Sjeff	/*
334219820Sjeff	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
335219820Sjeff	 * fields occur frequently, increase PADSIZE and make the initialisers
336219820Sjeff	 * below longer.
337219820Sjeff	 */
338219820Sjeff#define	PADSIZE	16		/* pad chunk size */
339219820Sjeff	static char blanks[PADSIZE] =
340219820Sjeff	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
341219820Sjeff	static char zeroes[PADSIZE] =
342219820Sjeff	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
343219820Sjeff
344219820Sjeff	static const char xdigs_lower[16] = "0123456789abcdef";
345219820Sjeff	static const char xdigs_upper[16] = "0123456789ABCDEF";
346219820Sjeff
347219820Sjeff	/*
348219820Sjeff	 * BEWARE, these `goto error' on error, and PAD uses `n'.
349219820Sjeff	 */
350219820Sjeff#define	PRINT(ptr, len) do { \
351219820Sjeff	iovp->iov_base = (ptr); \
352219820Sjeff	iovp->iov_len = (len); \
353219820Sjeff	uio.uio_resid += (len); \
354219820Sjeff	iovp++; \
355219820Sjeff	if (++uio.uio_iovcnt >= NIOV) { \
356219820Sjeff		if (__sprint(fp, &uio)) \
357219820Sjeff			goto error; \
358219820Sjeff		iovp = iov; \
359219820Sjeff	} \
360219820Sjeff} while (0)
361219820Sjeff#define	PAD(howmany, with) do { \
362219820Sjeff	if ((n = (howmany)) > 0) { \
363219820Sjeff		while (n > PADSIZE) { \
364219820Sjeff			PRINT(with, PADSIZE); \
365219820Sjeff			n -= PADSIZE; \
366219820Sjeff		} \
367219820Sjeff		PRINT(with, n); \
368219820Sjeff	} \
369219820Sjeff} while (0)
370219820Sjeff#define	PRINTANDPAD(p, ep, len, with) do {	\
371219820Sjeff	n2 = (ep) - (p);       			\
372219820Sjeff	if (n2 > (len))				\
373219820Sjeff		n2 = (len);			\
374219820Sjeff	if (n2 > 0)				\
375219820Sjeff		PRINT((p), n2);			\
376219820Sjeff	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
377219820Sjeff} while(0)
378219820Sjeff#define	FLUSH() do { \
379219820Sjeff	if (uio.uio_resid && __sprint(fp, &uio)) \
380219820Sjeff		goto error; \
381219820Sjeff	uio.uio_iovcnt = 0; \
382219820Sjeff	iovp = iov; \
383219820Sjeff} while (0)
384219820Sjeff
385219820Sjeff	/*
386219820Sjeff	 * To extend shorts properly, we need both signed and unsigned
387219820Sjeff	 * argument extraction methods.
388219820Sjeff	 */
389219820Sjeff#define	SARG() \
390219820Sjeff	((intmax_t)(flags&MAXINT ? GETARG(intmax_t) : \
391219820Sjeff	    flags&LLONGINT ? GETARG(long long) : \
392219820Sjeff	    flags&LONGINT ? GETARG(long) : \
393219820Sjeff	    flags&PTRINT ? GETARG(ptrdiff_t) : \
394219820Sjeff	    flags&SIZEINT ? GETARG(ssize_t) : \
395219820Sjeff	    flags&SHORTINT ? (short)GETARG(int) : \
396219820Sjeff	    flags&CHARINT ? (signed char)GETARG(int) : \
397219820Sjeff	    GETARG(int)))
398219820Sjeff#define	UARG() \
399219820Sjeff	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
400219820Sjeff	    flags&LLONGINT ? GETARG(unsigned long long) : \
401219820Sjeff	    flags&LONGINT ? GETARG(unsigned long) : \
402219820Sjeff	    flags&PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
403219820Sjeff	    flags&SIZEINT ? GETARG(size_t) : \
404219820Sjeff	    flags&SHORTINT ? (unsigned short)GETARG(int) : \
405219820Sjeff	    flags&CHARINT ? (unsigned char)GETARG(int) : \
406219820Sjeff	    GETARG(unsigned int)))
407219820Sjeff
408219820Sjeff	/*
409219820Sjeff	 * Append a digit to a value and check for overflow.
410219820Sjeff	 */
411219820Sjeff#define APPEND_DIGIT(val, dig) do { \
412219820Sjeff	if ((val) > INT_MAX / 10) \
413219820Sjeff		goto overflow; \
414219820Sjeff	(val) *= 10; \
415219820Sjeff	if ((val) > INT_MAX - to_digit((dig))) \
416219820Sjeff		goto overflow; \
417219820Sjeff	(val) += to_digit((dig)); \
418219820Sjeff} while (0)
419219820Sjeff
420219820Sjeff	 /*
421219820Sjeff	  * Get * arguments, including the form *nn$.  Preserve the nextarg
422219820Sjeff	  * that the argument can be gotten once the type is determined.
423219820Sjeff	  */
424219820Sjeff#define GETASTER(val) \
425219820Sjeff	n2 = 0; \
426219820Sjeff	cp = fmt; \
427219820Sjeff	while (is_digit(*cp)) { \
428219820Sjeff		APPEND_DIGIT(n2, *cp); \
429219820Sjeff		cp++; \
430219820Sjeff	} \
431219820Sjeff	if (*cp == '$') { \
432219820Sjeff		int hold = nextarg; \
433219820Sjeff		if (argtable == NULL) { \
434219820Sjeff			argtable = statargtable; \
435219820Sjeff			if (__find_arguments(fmt0, orgap, &argtable, \
436219820Sjeff			    &argtablesiz) == -1) { \
437219820Sjeff				ret = -1; \
438219820Sjeff				goto error; \
439219820Sjeff			} \
440219820Sjeff		} \
441219820Sjeff		nextarg = n2; \
442219820Sjeff		val = GETARG(int); \
443219820Sjeff		nextarg = hold; \
444219820Sjeff		fmt = ++cp; \
445219820Sjeff	} else { \
446219820Sjeff		val = GETARG(int); \
447219820Sjeff	}
448219820Sjeff
449219820Sjeff/*
450219820Sjeff* Get the argument indexed by nextarg.   If the argument table is
451219820Sjeff* built, use it to get the argument.  If its not, get the next
452219820Sjeff* argument (and arguments must be gotten sequentially).
453219820Sjeff*/
454219820Sjeff#define GETARG(type) \
455219820Sjeff	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
456		(nextarg++, va_arg(ap, type)))
457
458	_SET_ORIENTATION(fp, -1);
459	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
460	if (cantwrite(fp))
461		return (EOF);
462
463	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
464	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
465	    fp->_file >= 0)
466		return (__sbprintf(fp, fmt0, ap));
467
468	fmt = (char *)fmt0;
469	argtable = NULL;
470	nextarg = 1;
471	va_copy(orgap, ap);
472	uio.uio_iov = iovp = iov;
473	uio.uio_resid = 0;
474	uio.uio_iovcnt = 0;
475	ret = 0;
476#ifdef PRINTF_WIDE_CHAR
477	convbuf = NULL;
478#endif
479
480	/*
481	 * Scan the format for conversions (`%' character).
482	 */
483	for (;;) {
484		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
485			continue;
486
487		if (fmt != cp) {
488			ptrdiff_t m = fmt - cp;
489			if (m < 0 || m > INT_MAX - ret)
490				goto overflow;
491			PRINT(cp, m);
492			ret += m;
493		}
494		if (ch == '\0')
495			goto done;
496		fmt++;		/* skip over '%' */
497
498		flags = 0;
499		dprec = 0;
500		width = 0;
501		prec = -1;
502		sign = '\0';
503		ox[1] = '\0';
504
505rflag:		ch = *fmt++;
506reswitch:	switch (ch) {
507		case ' ':
508			/*
509			 * ``If the space and + flags both appear, the space
510			 * flag will be ignored.''
511			 *	-- ANSI X3J11
512			 */
513			if (!sign)
514				sign = ' ';
515			goto rflag;
516		case '#':
517			flags |= ALT;
518			goto rflag;
519		case '\'':
520			/* grouping not implemented */
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			if (width == INT_MIN)
533				goto overflow;
534			width = -width;
535			/* FALLTHROUGH */
536		case '-':
537			flags |= LADJUST;
538			goto rflag;
539		case '+':
540			sign = '+';
541			goto rflag;
542		case '.':
543			if ((ch = *fmt++) == '*') {
544				GETASTER(n);
545				prec = n < 0 ? -1 : n;
546				goto rflag;
547			}
548			n = 0;
549			while (is_digit(ch)) {
550				APPEND_DIGIT(n, ch);
551				ch = *fmt++;
552			}
553			if (ch == '$') {
554				nextarg = n;
555				if (argtable == NULL) {
556					argtable = statargtable;
557					if (__find_arguments(fmt0, orgap,
558					    &argtable, &argtablesiz) == -1) {
559						ret = -1;
560						goto error;
561					}
562				}
563				goto rflag;
564			}
565			prec = n;
566			goto reswitch;
567		case '0':
568			/*
569			 * ``Note that 0 is taken as a flag, not as the
570			 * beginning of a field width.''
571			 *	-- ANSI X3J11
572			 */
573			flags |= ZEROPAD;
574			goto rflag;
575		case '1': case '2': case '3': case '4':
576		case '5': case '6': case '7': case '8': case '9':
577			n = 0;
578			do {
579				APPEND_DIGIT(n, ch);
580				ch = *fmt++;
581			} while (is_digit(ch));
582			if (ch == '$') {
583				nextarg = n;
584				if (argtable == NULL) {
585					argtable = statargtable;
586					if (__find_arguments(fmt0, orgap,
587					    &argtable, &argtablesiz) == -1) {
588						ret = -1;
589						goto error;
590					}
591				}
592				goto rflag;
593			}
594			width = n;
595			goto reswitch;
596#ifdef FLOATING_POINT
597		case 'L':
598			flags |= LONGDBL;
599			goto rflag;
600#endif
601		case 'h':
602			if (*fmt == 'h') {
603				fmt++;
604				flags |= CHARINT;
605			} else {
606				flags |= SHORTINT;
607			}
608			goto rflag;
609		case 'j':
610			flags |= MAXINT;
611			goto rflag;
612		case 'l':
613			if (*fmt == 'l') {
614				fmt++;
615				flags |= LLONGINT;
616			} else {
617				flags |= LONGINT;
618			}
619			goto rflag;
620		case 'q':
621			flags |= LLONGINT;
622			goto rflag;
623		case 't':
624			flags |= PTRINT;
625			goto rflag;
626		case 'z':
627			flags |= SIZEINT;
628			goto rflag;
629		case 'c':
630#ifdef PRINTF_WIDE_CHAR
631			if (flags & LONGINT) {
632				mbstate_t mbs;
633				size_t mbseqlen;
634
635				memset(&mbs, 0, sizeof(mbs));
636				mbseqlen = wcrtomb(buf,
637				    (wchar_t)GETARG(wint_t), &mbs);
638				if (mbseqlen == (size_t)-1) {
639					ret = -1;
640					goto error;
641				}
642				cp = buf;
643				size = (int)mbseqlen;
644			} else {
645#endif
646				*(cp = buf) = GETARG(int);
647				size = 1;
648#ifdef PRINTF_WIDE_CHAR
649			}
650#endif
651			sign = '\0';
652			break;
653		case 'D':
654			flags |= LONGINT;
655			/*FALLTHROUGH*/
656		case 'd':
657		case 'i':
658			_umax = SARG();
659			if ((intmax_t)_umax < 0) {
660				_umax = -_umax;
661				sign = '-';
662			}
663			base = DEC;
664			goto number;
665#ifdef FLOATING_POINT
666		case 'a':
667		case 'A':
668			if (ch == 'a') {
669				ox[1] = 'x';
670				xdigs = xdigs_lower;
671				expchar = 'p';
672			} else {
673				ox[1] = 'X';
674				xdigs = xdigs_upper;
675				expchar = 'P';
676			}
677			if (prec >= 0)
678				prec++;
679			if (dtoaresult)
680				__freedtoa(dtoaresult);
681			if (flags & LONGDBL) {
682				fparg.ldbl = GETARG(long double);
683				dtoaresult = cp =
684				    __hldtoa(fparg.ldbl, xdigs, prec,
685				    &expt, &signflag, &dtoaend);
686				if (dtoaresult == NULL) {
687					errno = ENOMEM;
688					goto error;
689				}
690			} else {
691				fparg.dbl = GETARG(double);
692				dtoaresult = cp =
693				    __hdtoa(fparg.dbl, xdigs, prec,
694				    &expt, &signflag, &dtoaend);
695				if (dtoaresult == NULL) {
696					errno = ENOMEM;
697					goto error;
698				}
699			}
700			if (prec < 0)
701				prec = dtoaend - cp;
702			if (expt == INT_MAX)
703				ox[1] = '\0';
704			goto fp_common;
705		case 'e':
706		case 'E':
707			expchar = ch;
708			if (prec < 0)	/* account for digit before decpt */
709				prec = DEFPREC + 1;
710			else
711				prec++;
712			goto fp_begin;
713		case 'f':
714		case 'F':
715			expchar = '\0';
716			goto fp_begin;
717		case 'g':
718		case 'G':
719			expchar = ch - ('g' - 'e');
720 			if (prec == 0)
721 				prec = 1;
722fp_begin:
723			if (prec < 0)
724				prec = DEFPREC;
725			if (dtoaresult)
726				__freedtoa(dtoaresult);
727			if (flags & LONGDBL) {
728				fparg.ldbl = GETARG(long double);
729				dtoaresult = cp =
730				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
731				    &expt, &signflag, &dtoaend);
732				if (dtoaresult == NULL) {
733					errno = ENOMEM;
734					goto error;
735				}
736			} else {
737				fparg.dbl = GETARG(double);
738				dtoaresult = cp =
739				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
740				    &expt, &signflag, &dtoaend);
741				if (dtoaresult == NULL) {
742					errno = ENOMEM;
743					goto error;
744				}
745				if (expt == 9999)
746					expt = INT_MAX;
747 			}
748fp_common:
749			if (signflag)
750				sign = '-';
751			if (expt == INT_MAX) {	/* inf or nan */
752				if (*cp == 'N')
753					cp = (ch >= 'a') ? "nan" : "NAN";
754				else
755					cp = (ch >= 'a') ? "inf" : "INF";
756 				size = 3;
757				flags &= ~ZEROPAD;
758 				break;
759 			}
760			flags |= FPT;
761			ndig = dtoaend - cp;
762 			if (ch == 'g' || ch == 'G') {
763				if (expt > -4 && expt <= prec) {
764					/* Make %[gG] smell like %[fF] */
765					expchar = '\0';
766					if (flags & ALT)
767						prec -= expt;
768					else
769						prec = ndig - expt;
770					if (prec < 0)
771						prec = 0;
772				} else {
773					/*
774					 * Make %[gG] smell like %[eE], but
775					 * trim trailing zeroes if no # flag.
776					 */
777					if (!(flags & ALT))
778						prec = ndig;
779				}
780 			}
781			if (expchar) {
782				expsize = exponent(expstr, expt - 1, expchar);
783				size = expsize + prec;
784				if (prec > 1 || flags & ALT)
785 					++size;
786			} else {
787				/* space for digits before decimal point */
788				if (expt > 0)
789					size = expt;
790				else	/* "0" */
791					size = 1;
792				/* space for decimal pt and following digits */
793				if (prec || flags & ALT)
794					size += prec + 1;
795				lead = expt;
796			}
797			break;
798#endif /* FLOATING_POINT */
799		case 'n': {
800			static const char n_msg[] = ": *printf used %n, aborting: ";
801			char buf[1024], *p;
802
803			/* <10> is LOG_CRIT */
804			strlcpy(buf, "<10>", sizeof buf);
805
806			/* Make sure progname does not fill the whole buffer */
807			strlcat(buf, __progname, sizeof(buf) - sizeof n_msg);
808			strlcat(buf, n_msg, sizeof buf);
809			strlcat(buf, fmt0, sizeof buf);
810			if ((p = strchr(buf, '\n')))
811				*p = '\0';
812			sendsyslog(buf, strlen(buf), LOG_CONS);
813			abort();
814			break;
815			}
816		case 'O':
817			flags |= LONGINT;
818			/*FALLTHROUGH*/
819		case 'o':
820			_umax = UARG();
821			base = OCT;
822			goto nosign;
823		case 'p':
824			/*
825			 * ``The argument shall be a pointer to void.  The
826			 * value of the pointer is converted to a sequence
827			 * of printable characters, in an implementation-
828			 * defined manner.''
829			 *	-- ANSI X3J11
830			 */
831			_umax = (u_long)GETARG(void *);
832			base = HEX;
833			xdigs = xdigs_lower;
834			ox[1] = 'x';
835			goto nosign;
836		case 's': {
837			size_t len;
838
839#ifdef PRINTF_WIDE_CHAR
840			if (flags & LONGINT) {
841				wchar_t *wcp;
842
843				free(convbuf);
844				convbuf = NULL;
845				if ((wcp = GETARG(wchar_t *)) == NULL) {
846					struct syslog_data sdata = SYSLOG_DATA_INIT;
847					int save_errno = errno;
848
849					syslog_r(LOG_CRIT | LOG_CONS, &sdata,
850					    "vfprintf %%ls NULL in \"%s\"", fmt0);
851					errno = save_errno;
852
853					cp = "(null)";
854				} else {
855					convbuf = __wcsconv(wcp, prec);
856					if (convbuf == NULL) {
857						ret = -1;
858						goto error;
859					}
860					cp = convbuf;
861				}
862			} else
863#endif /* PRINTF_WIDE_CHAR */
864
865			if ((cp = GETARG(char *)) == NULL) {
866				struct syslog_data sdata = SYSLOG_DATA_INIT;
867				int save_errno = errno;
868
869				syslog_r(LOG_CRIT | LOG_CONS, &sdata,
870				    "vfprintf %%s NULL in \"%s\"", fmt0);
871				errno = save_errno;
872
873				cp = "(null)";
874			}
875			len = prec >= 0 ? strnlen(cp, prec) : strlen(cp);
876			if (len > INT_MAX)
877				goto overflow;
878			size = (int)len;
879			sign = '\0';
880			}
881			break;
882		case 'U':
883			flags |= LONGINT;
884			/*FALLTHROUGH*/
885		case 'u':
886			_umax = UARG();
887			base = DEC;
888			goto nosign;
889		case 'X':
890			xdigs = xdigs_upper;
891			goto hex;
892		case 'x':
893			xdigs = xdigs_lower;
894hex:			_umax = UARG();
895			base = HEX;
896			/* leading 0x/X only if non-zero */
897			if (flags & ALT && _umax != 0)
898				ox[1] = ch;
899
900			/* unsigned conversions */
901nosign:			sign = '\0';
902			/*
903			 * ``... diouXx conversions ... if a precision is
904			 * specified, the 0 flag will be ignored.''
905			 *	-- ANSI X3J11
906			 */
907number:			if ((dprec = prec) >= 0)
908				flags &= ~ZEROPAD;
909
910			/*
911			 * ``The result of converting a zero value with an
912			 * explicit precision of zero is no characters.''
913			 *	-- ANSI X3J11
914			 */
915			cp = buf + BUF;
916			if (_umax != 0 || prec != 0) {
917				/*
918				 * Unsigned mod is hard, and unsigned mod
919				 * by a constant is easier than that by
920				 * a variable; hence this switch.
921				 */
922				switch (base) {
923				case OCT:
924					do {
925						*--cp = to_char(_umax & 7);
926						_umax >>= 3;
927					} while (_umax);
928					/* handle octal leading 0 */
929					if (flags & ALT && *cp != '0')
930						*--cp = '0';
931					break;
932
933				case DEC:
934					/* many numbers are 1 digit */
935					while (_umax >= 10) {
936						*--cp = to_char(_umax % 10);
937						_umax /= 10;
938					}
939					*--cp = to_char(_umax);
940					break;
941
942				case HEX:
943					do {
944						*--cp = xdigs[_umax & 15];
945						_umax >>= 4;
946					} while (_umax);
947					break;
948
949				default:
950					cp = "bug in vfprintf: bad base";
951					size = strlen(cp);
952					goto skipsize;
953				}
954			}
955			size = buf + BUF - cp;
956			if (size > BUF)	/* should never happen */
957				abort();
958		skipsize:
959			break;
960		default:	/* "%?" prints ?, unless ? is NUL */
961			if (ch == '\0')
962				goto done;
963			/* pretend it was %c with argument ch */
964			cp = buf;
965			*cp = ch;
966			size = 1;
967			sign = '\0';
968			break;
969		}
970
971		/*
972		 * All reasonable formats wind up here.  At this point, `cp'
973		 * points to a string which (if not flags&LADJUST) should be
974		 * padded out to `width' places.  If flags&ZEROPAD, it should
975		 * first be prefixed by any sign or other prefix; otherwise,
976		 * it should be blank padded before the prefix is emitted.
977		 * After any left-hand padding and prefixing, emit zeroes
978		 * required by a decimal %[diouxX] precision, then print the
979		 * string proper, then emit zeroes required by any leftover
980		 * floating precision; finally, if LADJUST, pad with blanks.
981		 *
982		 * Compute actual size, so we know how much to pad.
983		 * size excludes decimal prec; realsz includes it.
984		 */
985		realsz = dprec > size ? dprec : size;
986		if (sign)
987			realsz++;
988		if (ox[1])
989			realsz+= 2;
990
991		/* right-adjusting blank padding */
992		if ((flags & (LADJUST|ZEROPAD)) == 0)
993			PAD(width - realsz, blanks);
994
995		/* prefix */
996		if (sign)
997			PRINT(&sign, 1);
998		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
999			ox[0] = '0';
1000			PRINT(ox, 2);
1001		}
1002
1003		/* right-adjusting zero padding */
1004		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1005			PAD(width - realsz, zeroes);
1006
1007		/* leading zeroes from decimal precision */
1008		PAD(dprec - size, zeroes);
1009
1010		/* the string or number proper */
1011#ifdef FLOATING_POINT
1012		if ((flags & FPT) == 0) {
1013			PRINT(cp, size);
1014		} else {	/* glue together f_p fragments */
1015			if (decimal_point == NULL)
1016				decimal_point = nl_langinfo(RADIXCHAR);
1017			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1018				if (expt <= 0) {
1019					PRINT(zeroes, 1);
1020					if (prec || flags & ALT)
1021						PRINT(decimal_point, 1);
1022					PAD(-expt, zeroes);
1023					/* already handled initial 0's */
1024					prec += expt;
1025 				} else {
1026					PRINTANDPAD(cp, dtoaend, lead, zeroes);
1027					cp += lead;
1028					if (prec || flags & ALT)
1029						PRINT(decimal_point, 1);
1030				}
1031				PRINTANDPAD(cp, dtoaend, prec, zeroes);
1032			} else {	/* %[eE] or sufficiently long %[gG] */
1033				if (prec > 1 || flags & ALT) {
1034					buf[0] = *cp++;
1035					buf[1] = *decimal_point;
1036					PRINT(buf, 2);
1037					PRINT(cp, ndig-1);
1038					PAD(prec - ndig, zeroes);
1039				} else { /* XeYYY */
1040					PRINT(cp, 1);
1041				}
1042				PRINT(expstr, expsize);
1043			}
1044		}
1045#else
1046		PRINT(cp, size);
1047#endif
1048		/* left-adjusting padding (always blank) */
1049		if (flags & LADJUST)
1050			PAD(width - realsz, blanks);
1051
1052		/* finally, adjust ret */
1053		if (width < realsz)
1054			width = realsz;
1055		if (width > INT_MAX - ret)
1056			goto overflow;
1057		ret += width;
1058
1059		FLUSH();	/* copy out the I/O vectors */
1060	}
1061done:
1062	FLUSH();
1063error:
1064	va_end(orgap);
1065	if (__sferror(fp))
1066		ret = -1;
1067	goto finish;
1068
1069overflow:
1070	errno = EOVERFLOW;
1071	ret = -1;
1072
1073finish:
1074#ifdef PRINTF_WIDE_CHAR
1075	free(convbuf);
1076#endif
1077#ifdef FLOATING_POINT
1078	if (dtoaresult)
1079		__freedtoa(dtoaresult);
1080#endif
1081	if (argtable != NULL && argtable != statargtable) {
1082		munmap(argtable, argtablesiz);
1083		argtable = NULL;
1084	}
1085	return (ret);
1086}
1087
1088/*
1089 * Type ids for argument type table.
1090 */
1091#define T_UNUSED	0
1092#define T_SHORT		1
1093#define T_U_SHORT	2
1094#define TP_SHORT	3
1095#define T_INT		4
1096#define T_U_INT		5
1097#define TP_INT		6
1098#define T_LONG		7
1099#define T_U_LONG	8
1100#define TP_LONG		9
1101#define T_LLONG		10
1102#define T_U_LLONG	11
1103#define TP_LLONG	12
1104#define T_DOUBLE	13
1105#define T_LONG_DOUBLE	14
1106#define TP_CHAR		15
1107#define TP_VOID		16
1108#define T_PTRINT	17
1109#define TP_PTRINT	18
1110#define T_SIZEINT	19
1111#define T_SSIZEINT	20
1112#define TP_SSIZEINT	21
1113#define T_MAXINT	22
1114#define T_MAXUINT	23
1115#define TP_MAXINT	24
1116#define T_CHAR		25
1117#define T_U_CHAR	26
1118#define T_WINT		27
1119#define TP_WCHAR	28
1120
1121/*
1122 * Find all arguments when a positional parameter is encountered.  Returns a
1123 * table, indexed by argument number, of pointers to each arguments.  The
1124 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1125 * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1126 * used since we are attempting to make snprintf thread safe, and alloca is
1127 * problematic since we have nested functions..)
1128 */
1129static int
1130__find_arguments(const char *fmt0, va_list ap, union arg **argtable,
1131    size_t *argtablesiz)
1132{
1133	char *fmt;		/* format string */
1134	int ch;			/* character from fmt */
1135	int n, n2;		/* handy integer (short term usage) */
1136	char *cp;		/* handy char pointer (short term usage) */
1137	int flags;		/* flags as above */
1138	unsigned char *typetable; /* table of types */
1139	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1140	int tablesize;		/* current size of type table */
1141	int tablemax;		/* largest used index in table */
1142	int nextarg;		/* 1-based argument index */
1143	int ret = 0;		/* return value */
1144
1145	/*
1146	 * Add an argument type to the table, expanding if necessary.
1147	 */
1148#define ADDTYPE(type) \
1149	((nextarg >= tablesize) ? \
1150		__grow_type_table(&typetable, &tablesize) : 0, \
1151	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1152	typetable[nextarg++] = type)
1153
1154#define	ADDSARG() \
1155        ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
1156	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1157	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
1158	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1159	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
1160	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
1161	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
1162
1163#define	ADDUARG() \
1164        ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
1165	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1166	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
1167	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1168	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
1169	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
1170	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
1171
1172	/*
1173	 * Add * arguments to the type array.
1174	 */
1175#define ADDASTER() \
1176	n2 = 0; \
1177	cp = fmt; \
1178	while (is_digit(*cp)) { \
1179		APPEND_DIGIT(n2, *cp); \
1180		cp++; \
1181	} \
1182	if (*cp == '$') { \
1183		int hold = nextarg; \
1184		nextarg = n2; \
1185		ADDTYPE(T_INT); \
1186		nextarg = hold; \
1187		fmt = ++cp; \
1188	} else { \
1189		ADDTYPE(T_INT); \
1190	}
1191	fmt = (char *)fmt0;
1192	typetable = stattypetable;
1193	tablesize = STATIC_ARG_TBL_SIZE;
1194	tablemax = 0;
1195	nextarg = 1;
1196	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1197
1198	/*
1199	 * Scan the format for conversions (`%' character).
1200	 */
1201	for (;;) {
1202		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1203			continue;
1204		if (ch == '\0')
1205			goto done;
1206		fmt++;		/* skip over '%' */
1207
1208		flags = 0;
1209
1210rflag:		ch = *fmt++;
1211reswitch:	switch (ch) {
1212		case ' ':
1213		case '#':
1214		case '\'':
1215			goto rflag;
1216		case '*':
1217			ADDASTER();
1218			goto rflag;
1219		case '-':
1220		case '+':
1221			goto rflag;
1222		case '.':
1223			if ((ch = *fmt++) == '*') {
1224				ADDASTER();
1225				goto rflag;
1226			}
1227			while (is_digit(ch)) {
1228				ch = *fmt++;
1229			}
1230			goto reswitch;
1231		case '0':
1232			goto rflag;
1233		case '1': case '2': case '3': case '4':
1234		case '5': case '6': case '7': case '8': case '9':
1235			n = 0;
1236			do {
1237				APPEND_DIGIT(n ,ch);
1238				ch = *fmt++;
1239			} while (is_digit(ch));
1240			if (ch == '$') {
1241				nextarg = n;
1242				goto rflag;
1243			}
1244			goto reswitch;
1245#ifdef FLOATING_POINT
1246		case 'L':
1247			flags |= LONGDBL;
1248			goto rflag;
1249#endif
1250		case 'h':
1251			if (*fmt == 'h') {
1252				fmt++;
1253				flags |= CHARINT;
1254			} else {
1255				flags |= SHORTINT;
1256			}
1257			goto rflag;
1258		case 'j':
1259			flags |= MAXINT;
1260			goto rflag;
1261		case 'l':
1262			if (*fmt == 'l') {
1263				fmt++;
1264				flags |= LLONGINT;
1265			} else {
1266				flags |= LONGINT;
1267			}
1268			goto rflag;
1269		case 'q':
1270			flags |= LLONGINT;
1271			goto rflag;
1272		case 't':
1273			flags |= PTRINT;
1274			goto rflag;
1275		case 'z':
1276			flags |= SIZEINT;
1277			goto rflag;
1278		case 'c':
1279#ifdef PRINTF_WIDE_CHAR
1280			if (flags & LONGINT)
1281				ADDTYPE(T_WINT);
1282			else
1283#endif
1284				ADDTYPE(T_INT);
1285			break;
1286		case 'D':
1287			flags |= LONGINT;
1288			/*FALLTHROUGH*/
1289		case 'd':
1290		case 'i':
1291			ADDSARG();
1292			break;
1293#ifdef FLOATING_POINT
1294		case 'a':
1295		case 'A':
1296		case 'e':
1297		case 'E':
1298		case 'f':
1299		case 'F':
1300		case 'g':
1301		case 'G':
1302			if (flags & LONGDBL)
1303				ADDTYPE(T_LONG_DOUBLE);
1304			else
1305				ADDTYPE(T_DOUBLE);
1306			break;
1307#endif /* FLOATING_POINT */
1308		case 'n':
1309			if (flags & LLONGINT)
1310				ADDTYPE(TP_LLONG);
1311			else if (flags & LONGINT)
1312				ADDTYPE(TP_LONG);
1313			else if (flags & SHORTINT)
1314				ADDTYPE(TP_SHORT);
1315			else if (flags & PTRINT)
1316				ADDTYPE(TP_PTRINT);
1317			else if (flags & SIZEINT)
1318				ADDTYPE(TP_SSIZEINT);
1319			else if (flags & MAXINT)
1320				ADDTYPE(TP_MAXINT);
1321			else
1322				ADDTYPE(TP_INT);
1323			continue;	/* no output */
1324		case 'O':
1325			flags |= LONGINT;
1326			/*FALLTHROUGH*/
1327		case 'o':
1328			ADDUARG();
1329			break;
1330		case 'p':
1331			ADDTYPE(TP_VOID);
1332			break;
1333		case 's':
1334#ifdef PRINTF_WIDE_CHAR
1335			if (flags & LONGINT)
1336				ADDTYPE(TP_WCHAR);
1337			else
1338#endif
1339				ADDTYPE(TP_CHAR);
1340			break;
1341		case 'U':
1342			flags |= LONGINT;
1343			/*FALLTHROUGH*/
1344		case 'u':
1345		case 'X':
1346		case 'x':
1347			ADDUARG();
1348			break;
1349		default:	/* "%?" prints ?, unless ? is NUL */
1350			if (ch == '\0')
1351				goto done;
1352			break;
1353		}
1354	}
1355done:
1356	/*
1357	 * Build the argument table.
1358	 */
1359	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1360		*argtablesiz = sizeof(union arg) * (tablemax + 1);
1361		*argtable = mmap(NULL, *argtablesiz,
1362		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
1363		if (*argtable == MAP_FAILED)
1364			return (-1);
1365	}
1366
1367	for (n = 1; n <= tablemax; n++) {
1368		switch (typetable[n]) {
1369		case T_UNUSED:
1370		case T_CHAR:
1371		case T_U_CHAR:
1372		case T_SHORT:
1373		case T_U_SHORT:
1374		case T_INT:
1375			(*argtable)[n].intarg = va_arg(ap, int);
1376			break;
1377		case TP_SHORT:
1378			(*argtable)[n].pshortarg = va_arg(ap, short *);
1379			break;
1380		case T_U_INT:
1381			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
1382			break;
1383		case TP_INT:
1384			(*argtable)[n].pintarg = va_arg(ap, int *);
1385			break;
1386		case T_LONG:
1387			(*argtable)[n].longarg = va_arg(ap, long);
1388			break;
1389		case T_U_LONG:
1390			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1391			break;
1392		case TP_LONG:
1393			(*argtable)[n].plongarg = va_arg(ap, long *);
1394			break;
1395		case T_LLONG:
1396			(*argtable)[n].longlongarg = va_arg(ap, long long);
1397			break;
1398		case T_U_LLONG:
1399			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1400			break;
1401		case TP_LLONG:
1402			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
1403			break;
1404#ifdef FLOATING_POINT
1405		case T_DOUBLE:
1406			(*argtable)[n].doublearg = va_arg(ap, double);
1407			break;
1408		case T_LONG_DOUBLE:
1409			(*argtable)[n].longdoublearg = va_arg(ap, long double);
1410			break;
1411#endif
1412		case TP_CHAR:
1413			(*argtable)[n].pchararg = va_arg(ap, char *);
1414			break;
1415		case TP_VOID:
1416			(*argtable)[n].pvoidarg = va_arg(ap, void *);
1417			break;
1418		case T_PTRINT:
1419			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1420			break;
1421		case TP_PTRINT:
1422			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
1423			break;
1424		case T_SIZEINT:
1425			(*argtable)[n].sizearg = va_arg(ap, size_t);
1426			break;
1427		case T_SSIZEINT:
1428			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
1429			break;
1430		case TP_SSIZEINT:
1431			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
1432			break;
1433		case T_MAXINT:
1434			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1435			break;
1436		case T_MAXUINT:
1437			(*argtable)[n].uintmaxarg = va_arg(ap, uintmax_t);
1438			break;
1439		case TP_MAXINT:
1440			(*argtable)[n].pintmaxarg = va_arg(ap, intmax_t *);
1441			break;
1442#ifdef PRINTF_WIDE_CHAR
1443		case T_WINT:
1444			(*argtable)[n].wintarg = va_arg(ap, wint_t);
1445			break;
1446		case TP_WCHAR:
1447			(*argtable)[n].pwchararg = va_arg(ap, wchar_t *);
1448			break;
1449#endif
1450		}
1451	}
1452	goto finish;
1453
1454overflow:
1455	errno = EOVERFLOW;
1456	ret = -1;
1457
1458finish:
1459	if (typetable != NULL && typetable != stattypetable) {
1460		munmap(typetable, *argtablesiz);
1461		typetable = NULL;
1462	}
1463	return (ret);
1464}
1465
1466/*
1467 * Increase the size of the type table.
1468 */
1469static int
1470__grow_type_table(unsigned char **typetable, int *tablesize)
1471{
1472	unsigned char *oldtable = *typetable;
1473	int newsize = *tablesize * 2;
1474
1475	if (newsize < getpagesize())
1476		newsize = getpagesize();
1477
1478	if (*tablesize == STATIC_ARG_TBL_SIZE) {
1479		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1480		    MAP_ANON|MAP_PRIVATE, -1, 0);
1481		if (*typetable == MAP_FAILED)
1482			return (-1);
1483		bcopy(oldtable, *typetable, *tablesize);
1484	} else {
1485		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1486		    MAP_ANON|MAP_PRIVATE, -1, 0);
1487		if (new == MAP_FAILED)
1488			return (-1);
1489		memmove(new, *typetable, *tablesize);
1490		munmap(*typetable, *tablesize);
1491		*typetable = new;
1492	}
1493	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
1494
1495	*tablesize = newsize;
1496	return (0);
1497}
1498
1499
1500#ifdef FLOATING_POINT
1501static int
1502exponent(char *p0, int exp, int fmtch)
1503{
1504	char *p, *t;
1505	char expbuf[MAXEXPDIG];
1506
1507	p = p0;
1508	*p++ = fmtch;
1509	if (exp < 0) {
1510		exp = -exp;
1511		*p++ = '-';
1512	} else
1513		*p++ = '+';
1514	t = expbuf + MAXEXPDIG;
1515	if (exp > 9) {
1516		do {
1517			*--t = to_char(exp % 10);
1518		} while ((exp /= 10) > 9);
1519		*--t = to_char(exp);
1520		for (; t < expbuf + MAXEXPDIG; *p++ = *t++)
1521			/* nothing */;
1522	} else {
1523		/*
1524		 * Exponents for decimal floating point conversions
1525		 * (%[eEgG]) must be at least two characters long,
1526		 * whereas exponents for hexadecimal conversions can
1527		 * be only one character long.
1528		 */
1529		if (fmtch == 'e' || fmtch == 'E')
1530			*p++ = '0';
1531		*p++ = to_char(exp);
1532	}
1533	return (p - p0);
1534}
1535#endif /* FLOATING_POINT */
1536