xref: /openbsd-src/lib/libc/stdio/vfprintf.c (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1 /*	$OpenBSD: vfprintf.c,v 1.58 2009/11/09 00:18:27 kurt Exp $	*/
2 /*-
3  * Copyright (c) 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Chris Torek.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Actual printf innards.
36  *
37  * This code is large and complicated...
38  */
39 
40 #include <sys/types.h>
41 #include <sys/mman.h>
42 
43 #include <errno.h>
44 #include <limits.h>
45 #include <stdarg.h>
46 #include <stddef.h>
47 #include <stdio.h>
48 #include <stdint.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #include "local.h"
54 #include "fvwrite.h"
55 
56 union arg {
57 	int			intarg;
58 	unsigned int		uintarg;
59 	long			longarg;
60 	unsigned long		ulongarg;
61 	long long		longlongarg;
62 	unsigned long long	ulonglongarg;
63 	ptrdiff_t		ptrdiffarg;
64 	size_t			sizearg;
65 	size_t			ssizearg;
66 	intmax_t		intmaxarg;
67 	uintmax_t		uintmaxarg;
68 	void			*pvoidarg;
69 	char			*pchararg;
70 	signed char		*pschararg;
71 	short			*pshortarg;
72 	int			*pintarg;
73 	long			*plongarg;
74 	long long		*plonglongarg;
75 	ptrdiff_t		*pptrdiffarg;
76 	ssize_t			*pssizearg;
77 	intmax_t		*pintmaxarg;
78 #ifdef FLOATING_POINT
79 	double			doublearg;
80 	long double		longdoublearg;
81 #endif
82 };
83 
84 static int __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
85     size_t *argtablesiz);
86 static int __grow_type_table(unsigned char **typetable, int *tablesize);
87 
88 /*
89  * Flush out all the vectors defined by the given uio,
90  * then reset it so that it can be reused.
91  */
92 static int
93 __sprint(FILE *fp, struct __suio *uio)
94 {
95 	int err;
96 
97 	if (uio->uio_resid == 0) {
98 		uio->uio_iovcnt = 0;
99 		return (0);
100 	}
101 	err = __sfvwrite(fp, uio);
102 	uio->uio_resid = 0;
103 	uio->uio_iovcnt = 0;
104 	return (err);
105 }
106 
107 /*
108  * Helper function for `fprintf to unbuffered unix file': creates a
109  * temporary buffer.  We only work on write-only files; this avoids
110  * worries about ungetc buffers and so forth.
111  */
112 static int
113 __sbprintf(FILE *fp, const char *fmt, va_list ap)
114 {
115 	int ret;
116 	FILE fake;
117 	struct __sfileext fakeext;
118 	unsigned char buf[BUFSIZ];
119 
120 	_FILEEXT_SETUP(&fake, &fakeext);
121 	/* copy the important variables */
122 	fake._flags = fp->_flags & ~__SNBF;
123 	fake._file = fp->_file;
124 	fake._cookie = fp->_cookie;
125 	fake._write = fp->_write;
126 
127 	/* set up the buffer */
128 	fake._bf._base = fake._p = buf;
129 	fake._bf._size = fake._w = sizeof(buf);
130 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
131 
132 	/* do the work, then copy any error status */
133 	ret = __vfprintf(&fake, fmt, ap);
134 	if (ret >= 0 && __sflush(&fake))
135 		ret = EOF;
136 	if (fake._flags & __SERR)
137 		fp->_flags |= __SERR;
138 	return (ret);
139 }
140 
141 
142 #ifdef FLOATING_POINT
143 #include <float.h>
144 #include <locale.h>
145 #include <math.h>
146 #include "floatio.h"
147 
148 #define	DEFPREC		6
149 
150 extern char *__dtoa(double, int, int, int *, int *, char **);
151 extern void  __freedtoa(char *);
152 static int exponent(char *, int, int);
153 #endif /* FLOATING_POINT */
154 
155 /*
156  * The size of the buffer we use as scratch space for integer
157  * conversions, among other things.  Technically, we would need the
158  * most space for base 10 conversions with thousands' grouping
159  * characters between each pair of digits.  100 bytes is a
160  * conservative overestimate even for a 128-bit uintmax_t.
161  */
162 #define BUF	100
163 
164 #define STATIC_ARG_TBL_SIZE 8	/* Size of static argument table. */
165 
166 
167 /*
168  * Macros for converting digits to letters and vice versa
169  */
170 #define	to_digit(c)	((c) - '0')
171 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
172 #define	to_char(n)	((n) + '0')
173 
174 /*
175  * Flags used during conversion.
176  */
177 #define	ALT		0x0001		/* alternate form */
178 #define	LADJUST		0x0004		/* left adjustment */
179 #define	LONGDBL		0x0008		/* long double; unimplemented */
180 #define	LONGINT		0x0010		/* long integer */
181 #define	LLONGINT	0x0020		/* long long integer */
182 #define	SHORTINT	0x0040		/* short integer */
183 #define	ZEROPAD		0x0080		/* zero (as opposed to blank) pad */
184 #define FPT		0x0100		/* Floating point number */
185 #define PTRINT		0x0200		/* (unsigned) ptrdiff_t */
186 #define SIZEINT		0x0400		/* (signed) size_t */
187 #define CHARINT		0x0800		/* 8 bit integer */
188 #define MAXINT		0x1000		/* largest integer size (intmax_t) */
189 
190 int
191 vfprintf(FILE *fp, const char *fmt0, __va_list ap)
192 {
193 	int ret;
194 
195 	FLOCKFILE(fp);
196 	ret = __vfprintf(fp, fmt0, ap);
197 	FUNLOCKFILE(fp);
198 	return (ret);
199 }
200 
201 int
202 __vfprintf(FILE *fp, const char *fmt0, __va_list ap)
203 {
204 	char *fmt;		/* format string */
205 	int ch;			/* character from fmt */
206 	int n, n2;		/* handy integers (short term usage) */
207 	char *cp;		/* handy char pointer (short term usage) */
208 	struct __siov *iovp;	/* for PRINT macro */
209 	int flags;		/* flags as above */
210 	int ret;		/* return value accumulator */
211 	int width;		/* width from format (%8d), or 0 */
212 	int prec;		/* precision from format; <0 for N/A */
213 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
214 	wchar_t wc;
215 	mbstate_t ps;
216 #ifdef FLOATING_POINT
217 	/*
218 	 * We can decompose the printed representation of floating
219 	 * point numbers into several parts, some of which may be empty:
220 	 *
221 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
222 	 *    A       B     ---C---      D       E   F
223 	 *
224 	 * A:	'sign' holds this value if present; '\0' otherwise
225 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
226 	 * C:	cp points to the string MMMNNN.  Leading and trailing
227 	 *	zeros are not in the string and must be added.
228 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
229 	 * F:	at least two digits for decimal, at least one digit for hex
230 	 */
231 	char *decimal_point = localeconv()->decimal_point;
232 	int signflag;		/* true if float is negative */
233 	union {			/* floating point arguments %[aAeEfFgG] */
234 		double dbl;
235 		long double ldbl;
236 	} fparg;
237 	int expt;		/* integer value of exponent */
238 	char expchar;		/* exponent character: [eEpP\0] */
239 	char *dtoaend;		/* pointer to end of converted digits */
240 	int expsize;		/* character count for expstr */
241 	int lead;		/* sig figs before decimal or group sep */
242 	int ndig;		/* actual number of digits returned by dtoa */
243 	char expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
244 	char *dtoaresult = NULL;
245 #endif
246 
247 	uintmax_t _umax;	/* integer arguments %[diouxX] */
248 	enum { OCT, DEC, HEX } base;	/* base for %[diouxX] conversion */
249 	int dprec;		/* a copy of prec if %[diouxX], 0 otherwise */
250 	int realsz;		/* field size expanded by dprec */
251 	int size;		/* size of converted field or string */
252 	const char *xdigs;	/* digits for %[xX] conversion */
253 #define NIOV 8
254 	struct __suio uio;	/* output information: summary */
255 	struct __siov iov[NIOV];/* ... and individual io vectors */
256 	char buf[BUF];		/* buffer with space for digits of uintmax_t */
257 	char ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
258 	union arg *argtable;	/* args, built due to positional arg */
259 	union arg statargtable[STATIC_ARG_TBL_SIZE];
260 	size_t argtablesiz;
261 	int nextarg;		/* 1-based argument index */
262 	va_list orgap;		/* original argument pointer */
263 
264 	/*
265 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
266 	 * fields occur frequently, increase PADSIZE and make the initialisers
267 	 * below longer.
268 	 */
269 #define	PADSIZE	16		/* pad chunk size */
270 	static char blanks[PADSIZE] =
271 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
272 	static char zeroes[PADSIZE] =
273 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
274 
275 	static const char xdigs_lower[16] = "0123456789abcdef";
276 	static const char xdigs_upper[16] = "0123456789ABCDEF";
277 
278 	/*
279 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
280 	 */
281 #define	PRINT(ptr, len) do { \
282 	iovp->iov_base = (ptr); \
283 	iovp->iov_len = (len); \
284 	uio.uio_resid += (len); \
285 	iovp++; \
286 	if (++uio.uio_iovcnt >= NIOV) { \
287 		if (__sprint(fp, &uio)) \
288 			goto error; \
289 		iovp = iov; \
290 	} \
291 } while (0)
292 #define	PAD(howmany, with) do { \
293 	if ((n = (howmany)) > 0) { \
294 		while (n > PADSIZE) { \
295 			PRINT(with, PADSIZE); \
296 			n -= PADSIZE; \
297 		} \
298 		PRINT(with, n); \
299 	} \
300 } while (0)
301 #define	PRINTANDPAD(p, ep, len, with) do {	\
302 	n2 = (ep) - (p);       			\
303 	if (n2 > (len))				\
304 		n2 = (len);			\
305 	if (n2 > 0)				\
306 		PRINT((p), n2);			\
307 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
308 } while(0)
309 #define	FLUSH() do { \
310 	if (uio.uio_resid && __sprint(fp, &uio)) \
311 		goto error; \
312 	uio.uio_iovcnt = 0; \
313 	iovp = iov; \
314 } while (0)
315 
316 	/*
317 	 * To extend shorts properly, we need both signed and unsigned
318 	 * argument extraction methods.
319 	 */
320 #define	SARG() \
321 	((intmax_t)(flags&MAXINT ? GETARG(intmax_t) : \
322 	    flags&LLONGINT ? GETARG(long long) : \
323 	    flags&LONGINT ? GETARG(long) : \
324 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
325 	    flags&SIZEINT ? GETARG(ssize_t) : \
326 	    flags&SHORTINT ? (short)GETARG(int) : \
327 	    flags&CHARINT ? (__signed char)GETARG(int) : \
328 	    GETARG(int)))
329 #define	UARG() \
330 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
331 	    flags&LLONGINT ? GETARG(unsigned long long) : \
332 	    flags&LONGINT ? GETARG(unsigned long) : \
333 	    flags&PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
334 	    flags&SIZEINT ? GETARG(size_t) : \
335 	    flags&SHORTINT ? (unsigned short)GETARG(int) : \
336 	    flags&CHARINT ? (unsigned char)GETARG(int) : \
337 	    GETARG(unsigned int)))
338 
339 	/*
340 	 * Append a digit to a value and check for overflow.
341 	 */
342 #define APPEND_DIGIT(val, dig) do { \
343 	if ((val) > INT_MAX / 10) \
344 		goto overflow; \
345 	(val) *= 10; \
346 	if ((val) > INT_MAX - to_digit((dig))) \
347 		goto overflow; \
348 	(val) += to_digit((dig)); \
349 } while (0)
350 
351 	 /*
352 	  * Get * arguments, including the form *nn$.  Preserve the nextarg
353 	  * that the argument can be gotten once the type is determined.
354 	  */
355 #define GETASTER(val) \
356 	n2 = 0; \
357 	cp = fmt; \
358 	while (is_digit(*cp)) { \
359 		APPEND_DIGIT(n2, *cp); \
360 		cp++; \
361 	} \
362 	if (*cp == '$') { \
363 		int hold = nextarg; \
364 		if (argtable == NULL) { \
365 			argtable = statargtable; \
366 			__find_arguments(fmt0, orgap, &argtable, &argtablesiz); \
367 		} \
368 		nextarg = n2; \
369 		val = GETARG(int); \
370 		nextarg = hold; \
371 		fmt = ++cp; \
372 	} else { \
373 		val = GETARG(int); \
374 	}
375 
376 /*
377 * Get the argument indexed by nextarg.   If the argument table is
378 * built, use it to get the argument.  If its not, get the next
379 * argument (and arguments must be gotten sequentially).
380 */
381 #define GETARG(type) \
382 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
383 		(nextarg++, va_arg(ap, type)))
384 
385 	_SET_ORIENTATION(fp, -1);
386 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
387 	if (cantwrite(fp)) {
388 		errno = EBADF;
389 		return (EOF);
390 	}
391 
392 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
393 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
394 	    fp->_file >= 0)
395 		return (__sbprintf(fp, fmt0, ap));
396 
397 	fmt = (char *)fmt0;
398 	argtable = NULL;
399 	nextarg = 1;
400 	va_copy(orgap, ap);
401 	uio.uio_iov = iovp = iov;
402 	uio.uio_resid = 0;
403 	uio.uio_iovcnt = 0;
404 	ret = 0;
405 
406 	memset(&ps, 0, sizeof(ps));
407 	/*
408 	 * Scan the format for conversions (`%' character).
409 	 */
410 	for (;;) {
411 		cp = fmt;
412 		while ((n = mbrtowc(&wc, fmt, MB_CUR_MAX, &ps)) > 0) {
413 			fmt += n;
414 			if (wc == '%') {
415 				fmt--;
416 				break;
417 			}
418 		}
419 		if (fmt != cp) {
420 			ptrdiff_t m = fmt - cp;
421 			if (m < 0 || m > INT_MAX - ret)
422 				goto overflow;
423 			PRINT(cp, m);
424 			ret += m;
425 		}
426 		if (n <= 0)
427 			goto done;
428 		fmt++;		/* skip over '%' */
429 
430 		flags = 0;
431 		dprec = 0;
432 		width = 0;
433 		prec = -1;
434 		sign = '\0';
435 		ox[1] = '\0';
436 
437 rflag:		ch = *fmt++;
438 reswitch:	switch (ch) {
439 		case ' ':
440 			/*
441 			 * ``If the space and + flags both appear, the space
442 			 * flag will be ignored.''
443 			 *	-- ANSI X3J11
444 			 */
445 			if (!sign)
446 				sign = ' ';
447 			goto rflag;
448 		case '#':
449 			flags |= ALT;
450 			goto rflag;
451 		case '\'':
452 			/* grouping not implemented */
453 			goto rflag;
454 		case '*':
455 			/*
456 			 * ``A negative field width argument is taken as a
457 			 * - flag followed by a positive field width.''
458 			 *	-- ANSI X3J11
459 			 * They don't exclude field widths read from args.
460 			 */
461 			GETASTER(width);
462 			if (width >= 0)
463 				goto rflag;
464 			if (width == INT_MIN)
465 				goto overflow;
466 			width = -width;
467 			/* FALLTHROUGH */
468 		case '-':
469 			flags |= LADJUST;
470 			goto rflag;
471 		case '+':
472 			sign = '+';
473 			goto rflag;
474 		case '.':
475 			if ((ch = *fmt++) == '*') {
476 				GETASTER(n);
477 				prec = n < 0 ? -1 : n;
478 				goto rflag;
479 			}
480 			n = 0;
481 			while (is_digit(ch)) {
482 				APPEND_DIGIT(n, ch);
483 				ch = *fmt++;
484 			}
485 			if (ch == '$') {
486 				nextarg = n;
487 				if (argtable == NULL) {
488 					argtable = statargtable;
489 					__find_arguments(fmt0, orgap,
490 					    &argtable, &argtablesiz);
491 				}
492 				goto rflag;
493 			}
494 			prec = n;
495 			goto reswitch;
496 		case '0':
497 			/*
498 			 * ``Note that 0 is taken as a flag, not as the
499 			 * beginning of a field width.''
500 			 *	-- ANSI X3J11
501 			 */
502 			flags |= ZEROPAD;
503 			goto rflag;
504 		case '1': case '2': case '3': case '4':
505 		case '5': case '6': case '7': case '8': case '9':
506 			n = 0;
507 			do {
508 				APPEND_DIGIT(n, ch);
509 				ch = *fmt++;
510 			} while (is_digit(ch));
511 			if (ch == '$') {
512 				nextarg = n;
513 				if (argtable == NULL) {
514 					argtable = statargtable;
515 					__find_arguments(fmt0, orgap,
516 					    &argtable, &argtablesiz);
517 				}
518 				goto rflag;
519 			}
520 			width = n;
521 			goto reswitch;
522 #ifdef FLOATING_POINT
523 		case 'L':
524 			flags |= LONGDBL;
525 			goto rflag;
526 #endif
527 		case 'h':
528 			if (*fmt == 'h') {
529 				fmt++;
530 				flags |= CHARINT;
531 			} else {
532 				flags |= SHORTINT;
533 			}
534 			goto rflag;
535 		case 'j':
536 			flags |= MAXINT;
537 			goto rflag;
538 		case 'l':
539 			if (*fmt == 'l') {
540 				fmt++;
541 				flags |= LLONGINT;
542 			} else {
543 				flags |= LONGINT;
544 			}
545 			goto rflag;
546 		case 'q':
547 			flags |= LLONGINT;
548 			goto rflag;
549 		case 't':
550 			flags |= PTRINT;
551 			goto rflag;
552 		case 'z':
553 			flags |= SIZEINT;
554 			goto rflag;
555 		case 'c':
556 			*(cp = buf) = GETARG(int);
557 			size = 1;
558 			sign = '\0';
559 			break;
560 		case 'D':
561 			flags |= LONGINT;
562 			/*FALLTHROUGH*/
563 		case 'd':
564 		case 'i':
565 			_umax = SARG();
566 			if ((intmax_t)_umax < 0) {
567 				_umax = -_umax;
568 				sign = '-';
569 			}
570 			base = DEC;
571 			goto number;
572 #ifdef FLOATING_POINT
573 		case 'a':
574 		case 'A':
575 			if (ch == 'a') {
576 				ox[1] = 'x';
577 				xdigs = xdigs_lower;
578 				expchar = 'p';
579 			} else {
580 				ox[1] = 'X';
581 				xdigs = xdigs_upper;
582 				expchar = 'P';
583 			}
584 			if (prec >= 0)
585 				prec++;
586 			if (dtoaresult)
587 				__freedtoa(dtoaresult);
588 			if (flags & LONGDBL) {
589 				fparg.ldbl = GETARG(long double);
590 				dtoaresult = cp =
591 				    __hldtoa(fparg.ldbl, xdigs, prec,
592 				    &expt, &signflag, &dtoaend);
593 				if (dtoaresult == NULL) {
594 					errno = ENOMEM;
595 					goto error;
596 				}
597 			} else {
598 				fparg.dbl = GETARG(double);
599 				dtoaresult = cp =
600 				    __hdtoa(fparg.dbl, xdigs, prec,
601 				    &expt, &signflag, &dtoaend);
602 				if (dtoaresult == NULL) {
603 					errno = ENOMEM;
604 					goto error;
605 				}
606 			}
607 			if (prec < 0)
608 				prec = dtoaend - cp;
609 			if (expt == INT_MAX)
610 				ox[1] = '\0';
611 			goto fp_common;
612 		case 'e':
613 		case 'E':
614 			expchar = ch;
615 			if (prec < 0)	/* account for digit before decpt */
616 				prec = DEFPREC + 1;
617 			else
618 				prec++;
619 			goto fp_begin;
620 		case 'f':
621 		case 'F':
622 			expchar = '\0';
623 			goto fp_begin;
624 		case 'g':
625 		case 'G':
626 			expchar = ch - ('g' - 'e');
627  			if (prec == 0)
628  				prec = 1;
629 fp_begin:
630 			if (prec < 0)
631 				prec = DEFPREC;
632 			if (dtoaresult)
633 				__freedtoa(dtoaresult);
634 			if (flags & LONGDBL) {
635 				fparg.ldbl = GETARG(long double);
636 				dtoaresult = cp =
637 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
638 				    &expt, &signflag, &dtoaend);
639 				if (dtoaresult == NULL) {
640 					errno = ENOMEM;
641 					goto error;
642 				}
643 			} else {
644 				fparg.dbl = GETARG(double);
645 				dtoaresult = cp =
646 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
647 				    &expt, &signflag, &dtoaend);
648 				if (dtoaresult == NULL) {
649 					errno = ENOMEM;
650 					goto error;
651 				}
652 				if (expt == 9999)
653 					expt = INT_MAX;
654  			}
655 fp_common:
656 			if (signflag)
657 				sign = '-';
658 			if (expt == INT_MAX) {	/* inf or nan */
659 				if (*cp == 'N') {
660 					cp = (ch >= 'a') ? "nan" : "NAN";
661 					sign = '\0';
662 				} else
663 					cp = (ch >= 'a') ? "inf" : "INF";
664  				size = 3;
665 				flags &= ~ZEROPAD;
666  				break;
667  			}
668 			flags |= FPT;
669 			ndig = dtoaend - cp;
670  			if (ch == 'g' || ch == 'G') {
671 				if (expt > -4 && expt <= prec) {
672 					/* Make %[gG] smell like %[fF] */
673 					expchar = '\0';
674 					if (flags & ALT)
675 						prec -= expt;
676 					else
677 						prec = ndig - expt;
678 					if (prec < 0)
679 						prec = 0;
680 				} else {
681 					/*
682 					 * Make %[gG] smell like %[eE], but
683 					 * trim trailing zeroes if no # flag.
684 					 */
685 					if (!(flags & ALT))
686 						prec = ndig;
687 				}
688  			}
689 			if (expchar) {
690 				expsize = exponent(expstr, expt - 1, expchar);
691 				size = expsize + prec;
692 				if (prec > 1 || flags & ALT)
693  					++size;
694 			} else {
695 				/* space for digits before decimal point */
696 				if (expt > 0)
697 					size = expt;
698 				else	/* "0" */
699 					size = 1;
700 				/* space for decimal pt and following digits */
701 				if (prec || flags & ALT)
702 					size += prec + 1;
703 				lead = expt;
704 			}
705 			break;
706 #endif /* FLOATING_POINT */
707 		case 'n':
708 			if (flags & LLONGINT)
709 				*GETARG(long long *) = ret;
710 			else if (flags & LONGINT)
711 				*GETARG(long *) = ret;
712 			else if (flags & SHORTINT)
713 				*GETARG(short *) = ret;
714 			else if (flags & CHARINT)
715 				*GETARG(__signed char *) = ret;
716 			else if (flags & PTRINT)
717 				*GETARG(ptrdiff_t *) = ret;
718 			else if (flags & SIZEINT)
719 				*GETARG(ssize_t *) = ret;
720 			else if (flags & MAXINT)
721 				*GETARG(intmax_t *) = ret;
722 			else
723 				*GETARG(int *) = ret;
724 			continue;	/* no output */
725 		case 'O':
726 			flags |= LONGINT;
727 			/*FALLTHROUGH*/
728 		case 'o':
729 			_umax = UARG();
730 			base = OCT;
731 			goto nosign;
732 		case 'p':
733 			/*
734 			 * ``The argument shall be a pointer to void.  The
735 			 * value of the pointer is converted to a sequence
736 			 * of printable characters, in an implementation-
737 			 * defined manner.''
738 			 *	-- ANSI X3J11
739 			 */
740 			/* NOSTRICT */
741 			_umax = (u_long)GETARG(void *);
742 			base = HEX;
743 			xdigs = xdigs_lower;
744 			ox[1] = 'x';
745 			goto nosign;
746 		case 's':
747 			if ((cp = GETARG(char *)) == NULL)
748 				cp = "(null)";
749 			if (prec >= 0) {
750 				/*
751 				 * can't use strlen; can only look for the
752 				 * NUL in the first `prec' characters, and
753 				 * strlen() will go further.
754 				 */
755 				char *p = memchr(cp, 0, prec);
756 
757 				size = p ? (p - cp) : prec;
758 			} else {
759 				size_t len;
760 
761 				if ((len = strlen(cp)) > INT_MAX)
762 					goto overflow;
763 				size = (int)len;
764 			}
765 			sign = '\0';
766 			break;
767 		case 'U':
768 			flags |= LONGINT;
769 			/*FALLTHROUGH*/
770 		case 'u':
771 			_umax = UARG();
772 			base = DEC;
773 			goto nosign;
774 		case 'X':
775 			xdigs = xdigs_upper;
776 			goto hex;
777 		case 'x':
778 			xdigs = xdigs_lower;
779 hex:			_umax = UARG();
780 			base = HEX;
781 			/* leading 0x/X only if non-zero */
782 			if (flags & ALT && _umax != 0)
783 				ox[1] = ch;
784 
785 			/* unsigned conversions */
786 nosign:			sign = '\0';
787 			/*
788 			 * ``... diouXx conversions ... if a precision is
789 			 * specified, the 0 flag will be ignored.''
790 			 *	-- ANSI X3J11
791 			 */
792 number:			if ((dprec = prec) >= 0)
793 				flags &= ~ZEROPAD;
794 
795 			/*
796 			 * ``The result of converting a zero value with an
797 			 * explicit precision of zero is no characters.''
798 			 *	-- ANSI X3J11
799 			 */
800 			cp = buf + BUF;
801 			if (_umax != 0 || prec != 0) {
802 				/*
803 				 * Unsigned mod is hard, and unsigned mod
804 				 * by a constant is easier than that by
805 				 * a variable; hence this switch.
806 				 */
807 				switch (base) {
808 				case OCT:
809 					do {
810 						*--cp = to_char(_umax & 7);
811 						_umax >>= 3;
812 					} while (_umax);
813 					/* handle octal leading 0 */
814 					if (flags & ALT && *cp != '0')
815 						*--cp = '0';
816 					break;
817 
818 				case DEC:
819 					/* many numbers are 1 digit */
820 					while (_umax >= 10) {
821 						*--cp = to_char(_umax % 10);
822 						_umax /= 10;
823 					}
824 					*--cp = to_char(_umax);
825 					break;
826 
827 				case HEX:
828 					do {
829 						*--cp = xdigs[_umax & 15];
830 						_umax >>= 4;
831 					} while (_umax);
832 					break;
833 
834 				default:
835 					cp = "bug in vfprintf: bad base";
836 					size = strlen(cp);
837 					goto skipsize;
838 				}
839 			}
840 			size = buf + BUF - cp;
841 			if (size > BUF)	/* should never happen */
842 				abort();
843 		skipsize:
844 			break;
845 		default:	/* "%?" prints ?, unless ? is NUL */
846 			if (ch == '\0')
847 				goto done;
848 			/* pretend it was %c with argument ch */
849 			cp = buf;
850 			*cp = ch;
851 			size = 1;
852 			sign = '\0';
853 			break;
854 		}
855 
856 		/*
857 		 * All reasonable formats wind up here.  At this point, `cp'
858 		 * points to a string which (if not flags&LADJUST) should be
859 		 * padded out to `width' places.  If flags&ZEROPAD, it should
860 		 * first be prefixed by any sign or other prefix; otherwise,
861 		 * it should be blank padded before the prefix is emitted.
862 		 * After any left-hand padding and prefixing, emit zeroes
863 		 * required by a decimal %[diouxX] precision, then print the
864 		 * string proper, then emit zeroes required by any leftover
865 		 * floating precision; finally, if LADJUST, pad with blanks.
866 		 *
867 		 * Compute actual size, so we know how much to pad.
868 		 * size excludes decimal prec; realsz includes it.
869 		 */
870 		realsz = dprec > size ? dprec : size;
871 		if (sign)
872 			realsz++;
873 		if (ox[1])
874 			realsz+= 2;
875 
876 		/* right-adjusting blank padding */
877 		if ((flags & (LADJUST|ZEROPAD)) == 0)
878 			PAD(width - realsz, blanks);
879 
880 		/* prefix */
881 		if (sign)
882 			PRINT(&sign, 1);
883 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
884 			ox[0] = '0';
885 			PRINT(ox, 2);
886 		}
887 
888 		/* right-adjusting zero padding */
889 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
890 			PAD(width - realsz, zeroes);
891 
892 		/* leading zeroes from decimal precision */
893 		PAD(dprec - size, zeroes);
894 
895 		/* the string or number proper */
896 #ifdef FLOATING_POINT
897 		if ((flags & FPT) == 0) {
898 			PRINT(cp, size);
899 		} else {	/* glue together f_p fragments */
900 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
901 				if (expt <= 0) {
902 					PRINT(zeroes, 1);
903 					if (prec || flags & ALT)
904 						PRINT(decimal_point, 1);
905 					PAD(-expt, zeroes);
906 					/* already handled initial 0's */
907 					prec += expt;
908  				} else {
909 					PRINTANDPAD(cp, dtoaend, lead, zeroes);
910 					cp += lead;
911 					if (prec || flags & ALT)
912 						PRINT(decimal_point, 1);
913 				}
914 				PRINTANDPAD(cp, dtoaend, prec, zeroes);
915 			} else {	/* %[eE] or sufficiently long %[gG] */
916 				if (prec > 1 || flags & ALT) {
917 					buf[0] = *cp++;
918 					buf[1] = *decimal_point;
919 					PRINT(buf, 2);
920 					PRINT(cp, ndig-1);
921 					PAD(prec - ndig, zeroes);
922 				} else { /* XeYYY */
923 					PRINT(cp, 1);
924 				}
925 				PRINT(expstr, expsize);
926 			}
927 		}
928 #else
929 		PRINT(cp, size);
930 #endif
931 		/* left-adjusting padding (always blank) */
932 		if (flags & LADJUST)
933 			PAD(width - realsz, blanks);
934 
935 		/* finally, adjust ret */
936 		if (width < realsz)
937 			width = realsz;
938 		if (width > INT_MAX - ret)
939 			goto overflow;
940 		ret += width;
941 
942 		FLUSH();	/* copy out the I/O vectors */
943 	}
944 done:
945 	FLUSH();
946 error:
947 	va_end(orgap);
948 	if (__sferror(fp))
949 		ret = -1;
950 	goto finish;
951 
952 overflow:
953 	errno = ENOMEM;
954 	ret = -1;
955 
956 finish:
957 #ifdef FLOATING_POINT
958 	if (dtoaresult)
959 		__freedtoa(dtoaresult);
960 #endif
961 	if (argtable != NULL && argtable != statargtable) {
962 		munmap(argtable, argtablesiz);
963 		argtable = NULL;
964 	}
965 	return (ret);
966 }
967 
968 /*
969  * Type ids for argument type table.
970  */
971 #define T_UNUSED	0
972 #define T_SHORT		1
973 #define T_U_SHORT	2
974 #define TP_SHORT	3
975 #define T_INT		4
976 #define T_U_INT		5
977 #define TP_INT		6
978 #define T_LONG		7
979 #define T_U_LONG	8
980 #define TP_LONG		9
981 #define T_LLONG		10
982 #define T_U_LLONG	11
983 #define TP_LLONG	12
984 #define T_DOUBLE	13
985 #define T_LONG_DOUBLE	14
986 #define TP_CHAR		15
987 #define TP_VOID		16
988 #define T_PTRINT	17
989 #define TP_PTRINT	18
990 #define T_SIZEINT	19
991 #define T_SSIZEINT	20
992 #define TP_SSIZEINT	21
993 #define T_MAXINT	22
994 #define T_MAXUINT	23
995 #define TP_MAXINT	24
996 #define T_CHAR		25
997 #define T_U_CHAR	26
998 
999 /*
1000  * Find all arguments when a positional parameter is encountered.  Returns a
1001  * table, indexed by argument number, of pointers to each arguments.  The
1002  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1003  * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1004  * used since we are attempting to make snprintf thread safe, and alloca is
1005  * problematic since we have nested functions..)
1006  */
1007 static int
1008 __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
1009     size_t *argtablesiz)
1010 {
1011 	char *fmt;		/* format string */
1012 	int ch;			/* character from fmt */
1013 	int n, n2;		/* handy integer (short term usage) */
1014 	char *cp;		/* handy char pointer (short term usage) */
1015 	int flags;		/* flags as above */
1016 	unsigned char *typetable; /* table of types */
1017 	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1018 	int tablesize;		/* current size of type table */
1019 	int tablemax;		/* largest used index in table */
1020 	int nextarg;		/* 1-based argument index */
1021 	int ret = 0;		/* return value */
1022 	wchar_t wc;
1023 	mbstate_t ps;
1024 
1025 	/*
1026 	 * Add an argument type to the table, expanding if necessary.
1027 	 */
1028 #define ADDTYPE(type) \
1029 	((nextarg >= tablesize) ? \
1030 		__grow_type_table(&typetable, &tablesize) : 0, \
1031 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1032 	typetable[nextarg++] = type)
1033 
1034 #define	ADDSARG() \
1035         ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
1036 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1037 	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
1038 	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1039 	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
1040 	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
1041 	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
1042 
1043 #define	ADDUARG() \
1044         ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
1045 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1046 	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
1047 	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1048 	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
1049 	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
1050 	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
1051 
1052 	/*
1053 	 * Add * arguments to the type array.
1054 	 */
1055 #define ADDASTER() \
1056 	n2 = 0; \
1057 	cp = fmt; \
1058 	while (is_digit(*cp)) { \
1059 		APPEND_DIGIT(n2, *cp); \
1060 		cp++; \
1061 	} \
1062 	if (*cp == '$') { \
1063 		int hold = nextarg; \
1064 		nextarg = n2; \
1065 		ADDTYPE(T_INT); \
1066 		nextarg = hold; \
1067 		fmt = ++cp; \
1068 	} else { \
1069 		ADDTYPE(T_INT); \
1070 	}
1071 	fmt = (char *)fmt0;
1072 	typetable = stattypetable;
1073 	tablesize = STATIC_ARG_TBL_SIZE;
1074 	tablemax = 0;
1075 	nextarg = 1;
1076 	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1077 	memset(&ps, 0, sizeof(ps));
1078 
1079 	/*
1080 	 * Scan the format for conversions (`%' character).
1081 	 */
1082 	for (;;) {
1083 		cp = fmt;
1084 		while ((n = mbrtowc(&wc, fmt, MB_CUR_MAX, &ps)) > 0) {
1085 			fmt += n;
1086 			if (wc == '%') {
1087 				fmt--;
1088 				break;
1089 			}
1090 		}
1091 		if (n <= 0)
1092 			goto done;
1093 		fmt++;		/* skip over '%' */
1094 
1095 		flags = 0;
1096 
1097 rflag:		ch = *fmt++;
1098 reswitch:	switch (ch) {
1099 		case ' ':
1100 		case '#':
1101 		case '\'':
1102 			goto rflag;
1103 		case '*':
1104 			ADDASTER();
1105 			goto rflag;
1106 		case '-':
1107 		case '+':
1108 			goto rflag;
1109 		case '.':
1110 			if ((ch = *fmt++) == '*') {
1111 				ADDASTER();
1112 				goto rflag;
1113 			}
1114 			while (is_digit(ch)) {
1115 				ch = *fmt++;
1116 			}
1117 			goto reswitch;
1118 		case '0':
1119 			goto rflag;
1120 		case '1': case '2': case '3': case '4':
1121 		case '5': case '6': case '7': case '8': case '9':
1122 			n = 0;
1123 			do {
1124 				APPEND_DIGIT(n ,ch);
1125 				ch = *fmt++;
1126 			} while (is_digit(ch));
1127 			if (ch == '$') {
1128 				nextarg = n;
1129 				goto rflag;
1130 			}
1131 			goto reswitch;
1132 #ifdef FLOATING_POINT
1133 		case 'L':
1134 			flags |= LONGDBL;
1135 			goto rflag;
1136 #endif
1137 		case 'h':
1138 			if (*fmt == 'h') {
1139 				fmt++;
1140 				flags |= CHARINT;
1141 			} else {
1142 				flags |= SHORTINT;
1143 			}
1144 			goto rflag;
1145 		case 'l':
1146 			if (*fmt == 'l') {
1147 				fmt++;
1148 				flags |= LLONGINT;
1149 			} else {
1150 				flags |= LONGINT;
1151 			}
1152 			goto rflag;
1153 		case 'q':
1154 			flags |= LLONGINT;
1155 			goto rflag;
1156 		case 't':
1157 			flags |= PTRINT;
1158 			goto rflag;
1159 		case 'z':
1160 			flags |= SIZEINT;
1161 			goto rflag;
1162 		case 'c':
1163 			ADDTYPE(T_INT);
1164 			break;
1165 		case 'D':
1166 			flags |= LONGINT;
1167 			/*FALLTHROUGH*/
1168 		case 'd':
1169 		case 'i':
1170 			ADDSARG();
1171 			break;
1172 #ifdef FLOATING_POINT
1173 		case 'a':
1174 		case 'A':
1175 		case 'e':
1176 		case 'E':
1177 		case 'f':
1178 		case 'F':
1179 		case 'g':
1180 		case 'G':
1181 			if (flags & LONGDBL)
1182 				ADDTYPE(T_LONG_DOUBLE);
1183 			else
1184 				ADDTYPE(T_DOUBLE);
1185 			break;
1186 #endif /* FLOATING_POINT */
1187 		case 'n':
1188 			if (flags & LLONGINT)
1189 				ADDTYPE(TP_LLONG);
1190 			else if (flags & LONGINT)
1191 				ADDTYPE(TP_LONG);
1192 			else if (flags & SHORTINT)
1193 				ADDTYPE(TP_SHORT);
1194 			else if (flags & PTRINT)
1195 				ADDTYPE(TP_PTRINT);
1196 			else if (flags & SIZEINT)
1197 				ADDTYPE(TP_SSIZEINT);
1198 			else if (flags & MAXINT)
1199 				ADDTYPE(TP_MAXINT);
1200 			else
1201 				ADDTYPE(TP_INT);
1202 			continue;	/* no output */
1203 		case 'O':
1204 			flags |= LONGINT;
1205 			/*FALLTHROUGH*/
1206 		case 'o':
1207 			ADDUARG();
1208 			break;
1209 		case 'p':
1210 			ADDTYPE(TP_VOID);
1211 			break;
1212 		case 's':
1213 			ADDTYPE(TP_CHAR);
1214 			break;
1215 		case 'U':
1216 			flags |= LONGINT;
1217 			/*FALLTHROUGH*/
1218 		case 'u':
1219 		case 'X':
1220 		case 'x':
1221 			ADDUARG();
1222 			break;
1223 		default:	/* "%?" prints ?, unless ? is NUL */
1224 			if (ch == '\0')
1225 				goto done;
1226 			break;
1227 		}
1228 	}
1229 done:
1230 	/*
1231 	 * Build the argument table.
1232 	 */
1233 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1234 		*argtablesiz = sizeof(union arg) * (tablemax + 1);
1235 		*argtable = mmap(NULL, *argtablesiz,
1236 		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
1237 		if (*argtable == MAP_FAILED)
1238 			return (-1);
1239 	}
1240 
1241 #if 0
1242 	/* XXX is this required? */
1243 	(*argtable)[0].intarg = 0;
1244 #endif
1245 	for (n = 1; n <= tablemax; n++) {
1246 		switch (typetable[n]) {
1247 		case T_UNUSED:
1248 		case T_CHAR:
1249 		case T_U_CHAR:
1250 		case T_SHORT:
1251 		case T_U_SHORT:
1252 		case T_INT:
1253 			(*argtable)[n].intarg = va_arg(ap, int);
1254 			break;
1255 		case TP_SHORT:
1256 			(*argtable)[n].pshortarg = va_arg(ap, short *);
1257 			break;
1258 		case T_U_INT:
1259 			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
1260 			break;
1261 		case TP_INT:
1262 			(*argtable)[n].pintarg = va_arg(ap, int *);
1263 			break;
1264 		case T_LONG:
1265 			(*argtable)[n].longarg = va_arg(ap, long);
1266 			break;
1267 		case T_U_LONG:
1268 			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1269 			break;
1270 		case TP_LONG:
1271 			(*argtable)[n].plongarg = va_arg(ap, long *);
1272 			break;
1273 		case T_LLONG:
1274 			(*argtable)[n].longlongarg = va_arg(ap, long long);
1275 			break;
1276 		case T_U_LLONG:
1277 			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1278 			break;
1279 		case TP_LLONG:
1280 			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
1281 			break;
1282 #ifdef FLOATING_POINT
1283 		case T_DOUBLE:
1284 			(*argtable)[n].doublearg = va_arg(ap, double);
1285 			break;
1286 		case T_LONG_DOUBLE:
1287 			(*argtable)[n].longdoublearg = va_arg(ap, long double);
1288 			break;
1289 #endif
1290 		case TP_CHAR:
1291 			(*argtable)[n].pchararg = va_arg(ap, char *);
1292 			break;
1293 		case TP_VOID:
1294 			(*argtable)[n].pvoidarg = va_arg(ap, void *);
1295 			break;
1296 		case T_PTRINT:
1297 			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1298 			break;
1299 		case TP_PTRINT:
1300 			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
1301 			break;
1302 		case T_SIZEINT:
1303 			(*argtable)[n].sizearg = va_arg(ap, size_t);
1304 			break;
1305 		case T_SSIZEINT:
1306 			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
1307 			break;
1308 		case TP_SSIZEINT:
1309 			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
1310 			break;
1311 		case TP_MAXINT:
1312 			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1313 			break;
1314 		}
1315 	}
1316 	goto finish;
1317 
1318 overflow:
1319 	errno = ENOMEM;
1320 	ret = -1;
1321 
1322 finish:
1323 	if (typetable != NULL && typetable != stattypetable) {
1324 		munmap(typetable, *argtablesiz);
1325 		typetable = NULL;
1326 	}
1327 	return (ret);
1328 }
1329 
1330 /*
1331  * Increase the size of the type table.
1332  */
1333 static int
1334 __grow_type_table(unsigned char **typetable, int *tablesize)
1335 {
1336 	unsigned char *oldtable = *typetable;
1337 	int newsize = *tablesize * 2;
1338 
1339 	if (newsize < getpagesize())
1340 		newsize = getpagesize();
1341 
1342 	if (*tablesize == STATIC_ARG_TBL_SIZE) {
1343 		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1344 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1345 		if (*typetable == MAP_FAILED)
1346 			return (-1);
1347 		bcopy(oldtable, *typetable, *tablesize);
1348 	} else {
1349 		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1350 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1351 		if (new == MAP_FAILED)
1352 			return (-1);
1353 		memmove(new, *typetable, *tablesize);
1354 		munmap(*typetable, *tablesize);
1355 		*typetable = new;
1356 	}
1357 	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
1358 
1359 	*tablesize = newsize;
1360 	return (0);
1361 }
1362 
1363 
1364 #ifdef FLOATING_POINT
1365 static int
1366 exponent(char *p0, int exp, int fmtch)
1367 {
1368 	char *p, *t;
1369 	char expbuf[MAXEXPDIG];
1370 
1371 	p = p0;
1372 	*p++ = fmtch;
1373 	if (exp < 0) {
1374 		exp = -exp;
1375 		*p++ = '-';
1376 	} else
1377 		*p++ = '+';
1378 	t = expbuf + MAXEXPDIG;
1379 	if (exp > 9) {
1380 		do {
1381 			*--t = to_char(exp % 10);
1382 		} while ((exp /= 10) > 9);
1383 		*--t = to_char(exp);
1384 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++)
1385 			/* nothing */;
1386 	} else {
1387 		/*
1388 		 * Exponents for decimal floating point conversions
1389 		 * (%[eEgG]) must be at least two characters long,
1390 		 * whereas exponents for hexadecimal conversions can
1391 		 * be only one character long.
1392 		 */
1393 		if (fmtch == 'e' || fmtch == 'E')
1394 			*p++ = '0';
1395 		*p++ = to_char(exp);
1396 	}
1397 	return (p - p0);
1398 }
1399 #endif /* FLOATING_POINT */
1400