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