xref: /netbsd-src/lib/libc/stdio/vfprintf.c (revision 1ffa7b76c40339c17a0fb2a09fac93f287cfc046)
1 /*	$NetBSD: vfprintf.c,v 1.44 2003/01/18 11:29:59 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
41 #if 0
42 static char *sccsid = "@(#)vfprintf.c	5.50 (Berkeley) 12/16/92";
43 #else
44 __RCSID("$NetBSD: vfprintf.c,v 1.44 2003/01/18 11:29:59 thorpej Exp $");
45 #endif
46 #endif /* LIBC_SCCS and not lint */
47 
48 /*
49  * Actual printf innards.
50  *
51  * This code is large and complicated...
52  */
53 
54 #include "namespace.h"
55 #include <sys/types.h>
56 
57 #include <assert.h>
58 #include <errno.h>
59 #include <stdarg.h>
60 #include <stddef.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <wchar.h>
66 
67 #include "reentrant.h"
68 #include "local.h"
69 #include "fvwrite.h"
70 #include "extern.h"
71 
72 static int __sprint __P((FILE *, struct __suio *));
73 static int __sbprintf __P((FILE *, const char *, va_list))
74      __attribute__((__format__(__printf__, 2, 0)));
75 
76 /*
77  * Flush out all the vectors defined by the given uio,
78  * then reset it so that it can be reused.
79  */
80 static int
81 __sprint(fp, uio)
82 	FILE *fp;
83 	struct __suio *uio;
84 {
85 	int err;
86 
87 	_DIAGASSERT(fp != NULL);
88 	_DIAGASSERT(uio != NULL);
89 
90 	if (uio->uio_resid == 0) {
91 		uio->uio_iovcnt = 0;
92 		return (0);
93 	}
94 	err = __sfvwrite(fp, uio);
95 	uio->uio_resid = 0;
96 	uio->uio_iovcnt = 0;
97 	return (err);
98 }
99 
100 /*
101  * Helper function for `fprintf to unbuffered unix file': creates a
102  * temporary buffer.  We only work on write-only files; this avoids
103  * worries about ungetc buffers and so forth.
104  */
105 static int
106 __sbprintf(fp, fmt, ap)
107 	FILE *fp;
108 	const char *fmt;
109 	va_list ap;
110 {
111 	int ret;
112 	FILE fake;
113 	struct __sfileext fakeext;
114 	unsigned char buf[BUFSIZ];
115 
116 	_DIAGASSERT(fp != NULL);
117 	_DIAGASSERT(fmt != NULL);
118 
119 	_FILEEXT_SETUP(&fake, &fakeext);
120 
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 && fflush(&fake))
135 		ret = -1;
136 	if (fake._flags & __SERR)
137 		fp->_flags |= __SERR;
138 	return (ret);
139 }
140 
141 
142 #ifdef FLOATING_POINT
143 #include <locale.h>
144 #include <math.h>
145 #include "floatio.h"
146 
147 #define	BUF		(MAXEXP+MAXFRACT+1)	/* + decimal point */
148 #define	DEFPREC		6
149 
150 static char *cvt __P((double, int, int, char *, int *, int, int *));
151 static int exponent __P((char *, int, int));
152 
153 #else /* no FLOATING_POINT */
154 
155 #define	BUF		40
156 
157 #endif /* FLOATING_POINT */
158 
159 #ifdef lint
160 static __inline void *__UNCONST __P((const void *));
161 static __inline void *
162 __UNCONST(v)
163 	const void *v;
164 {
165 	/* LINTED */
166 	return (void *) v;
167 }
168 #else
169 #define __UNCONST(v)	(void *)(v)
170 #endif
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)	((char)((n) + '0'))
178 
179 /*
180  * Flags used during conversion.
181  */
182 #define	ALT		0x001		/* alternate form */
183 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
184 #define	LADJUST		0x004		/* left adjustment */
185 #define	LONGDBL		0x008		/* long double; unimplemented */
186 #define	LONGINT		0x010		/* long integer */
187 #define	QUADINT		0x020		/* quad integer */
188 #define	SHORTINT	0x040		/* short integer */
189 #define	MAXINT		0x080		/* (unsigned) intmax_t */
190 #define	PTRINT		0x100		/* (unsigned) ptrdiff_t */
191 #define	SIZEINT		0x200		/* (signed) size_t */
192 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
193 #define FPT		0x800		/* Floating point number */
194 
195 int
196 vfprintf(fp, fmt0, ap)
197 	FILE *fp;
198 	const char *fmt0;
199 	_BSD_VA_LIST_ ap;
200 {
201 	int ret;
202 
203 	FLOCKFILE(fp);
204 	ret = vfprintf_unlocked(fp, fmt0, ap);
205 	FUNLOCKFILE(fp);
206 
207 	return ret;
208 }
209 
210 
211 
212 int
213 vfprintf_unlocked(fp, fmt0, ap)
214 	FILE *fp;
215 	const char *fmt0;
216 	_BSD_VA_LIST_ ap;
217 {
218 	const char *fmt;/* format string */
219 	int ch;	/* character from fmt */
220 	int n, m;	/* handy integers (short term usage) */
221 	const char *cp;	/* handy char pointer (short term usage) */
222 	char *bp;	/* handy char pointer (short term usage) */
223 	struct __siov *iovp;/* for PRINT macro */
224 	int flags;	/* flags as above */
225 	int ret;		/* return value accumulator */
226 	int width;		/* width from format (%8d), or 0 */
227 	int prec;		/* precision from format (%.3d), or -1 */
228 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
229 	wchar_t wc;
230 	mbstate_t ps;
231 #ifdef FLOATING_POINT
232 	char *decimal_point = localeconv()->decimal_point;
233 	char softsign;		/* temporary negative sign for floats */
234 	double _double = 0;	/* double precision arguments %[eEfgG] */
235 	int expt;		/* integer value of exponent */
236 	int expsize = 0;	/* character count for expstr */
237 	int ndig;		/* actual number of digits returned by cvt */
238 	char expstr[7];		/* buffer for exponent string */
239 #endif
240 
241 #ifdef __GNUC__			/* gcc has builtin quad type (long long) SOS */
242 #define	quad_t	  long long
243 #define	u_quad_t  unsigned long long
244 #endif
245 
246 #define	INTMAX_T	intmax_t
247 #define	UINTMAX_T	uintmax_t
248 
249 	UINTMAX_T _uintmax;	/* integer arguments %[diouxX] */
250 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
251 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
252 	int realsz;		/* field size expanded by dprec */
253 	int size;		/* size of converted field or string */
254 	char *xdigs = NULL;	/* digits for [xX] conversion */
255 #define NIOV 8
256 	struct __suio uio;	/* output information: summary */
257 	struct __siov iov[NIOV];/* ... and individual io vectors */
258 	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
259 	char ox[2];		/* space for 0x hex-prefix */
260 
261 	/*
262 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
263 	 * fields occur frequently, increase PADSIZE and make the initialisers
264 	 * below longer.
265 	 */
266 #define	PADSIZE	16		/* pad chunk size */
267 	static const char blanks[PADSIZE] =
268 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
269 	static const char zeroes[PADSIZE] =
270 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
271 
272 	/*
273 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
274 	 */
275 #define	PRINT(ptr, len) { \
276 	iovp->iov_base = __UNCONST(ptr); \
277 	iovp->iov_len = (len); \
278 	uio.uio_resid += (len); \
279 	iovp++; \
280 	if (++uio.uio_iovcnt >= NIOV) { \
281 		if (__sprint(fp, &uio)) \
282 			goto error; \
283 		iovp = iov; \
284 	} \
285 }
286 #define	PAD(howmany, with) { \
287 	if ((n = (howmany)) > 0) { \
288 		while (n > PADSIZE) { \
289 			PRINT(with, PADSIZE); \
290 			n -= PADSIZE; \
291 		} \
292 		PRINT(with, n); \
293 	} \
294 }
295 #define	FLUSH() { \
296 	if (uio.uio_resid && __sprint(fp, &uio)) \
297 		goto error; \
298 	uio.uio_iovcnt = 0; \
299 	iovp = iov; \
300 }
301 
302 	/*
303 	 * To extend shorts properly, we need both signed and unsigned
304 	 * argument extraction methods.
305 	 */
306 #define	SARG() \
307 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
308 	    flags&PTRINT ? va_arg(ap, ptrdiff_t) : \
309 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
310 	    flags&QUADINT ? va_arg(ap, quad_t) : \
311 	    flags&LONGINT ? va_arg(ap, long) : \
312 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
313 	    (long)va_arg(ap, int))
314 #define	UARG() \
315 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
316 	    flags&PTRINT ? va_arg(ap, uintptr_t) : /* XXX */ \
317 	    flags&SIZEINT ? va_arg(ap, size_t) : \
318 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
319 	    flags&LONGINT ? va_arg(ap, u_long) : \
320 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
321 	    (u_long)va_arg(ap, u_int))
322 
323 	_DIAGASSERT(fp != NULL);
324 	_DIAGASSERT(fmt0 != NULL);
325 
326 	_SET_ORIENTATION(fp, -1);
327 
328 	/* sorry, fprintf(read_only_file, "") returns -1, not 0 */
329 	if (cantwrite(fp)) {
330 		errno = EBADF;
331 		return (-1);
332 	}
333 
334 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
335 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
336 	    fp->_file >= 0) {
337 		ret = __sbprintf(fp, fmt0, ap);
338 		return (ret);
339 	}
340 
341 	fmt = fmt0;
342 	uio.uio_iov = iovp = iov;
343 	uio.uio_resid = 0;
344 	uio.uio_iovcnt = 0;
345 	ret = 0;
346 
347 	memset(&ps, 0, sizeof(ps));
348 
349 	/*
350 	 * Scan the format for conversions (`%' character).
351 	 */
352 	for (;;) {
353 		cp = fmt;
354 		while ((n = mbrtowc(&wc, fmt, MB_CUR_MAX, &ps)) > 0) {
355 			fmt += n;
356 			if (wc == '%') {
357 				fmt--;
358 				break;
359 			}
360 		}
361 		if ((m = fmt - cp) != 0) {
362 			PRINT(cp, m);
363 			ret += m;
364 		}
365 		if (n <= 0)
366 			goto done;
367 		fmt++;		/* skip over '%' */
368 
369 		flags = 0;
370 		dprec = 0;
371 		width = 0;
372 		prec = -1;
373 		sign = '\0';
374 
375 rflag:		ch = *fmt++;
376 reswitch:	switch (ch) {
377 		case ' ':
378 			/*
379 			 * ``If the space and + flags both appear, the space
380 			 * flag will be ignored.''
381 			 *	-- ANSI X3J11
382 			 */
383 			if (!sign)
384 				sign = ' ';
385 			goto rflag;
386 		case '#':
387 			flags |= ALT;
388 			goto rflag;
389 		case '*':
390 			/*
391 			 * ``A negative field width argument is taken as a
392 			 * - flag followed by a positive field width.''
393 			 *	-- ANSI X3J11
394 			 * They don't exclude field widths read from args.
395 			 */
396 			if ((width = va_arg(ap, int)) >= 0)
397 				goto rflag;
398 			width = -width;
399 			/* FALLTHROUGH */
400 		case '-':
401 			flags |= LADJUST;
402 			goto rflag;
403 		case '+':
404 			sign = '+';
405 			goto rflag;
406 		case '.':
407 			if ((ch = *fmt++) == '*') {
408 				n = va_arg(ap, int);
409 				prec = n < 0 ? -1 : n;
410 				goto rflag;
411 			}
412 			n = 0;
413 			while (is_digit(ch)) {
414 				n = 10 * n + to_digit(ch);
415 				ch = *fmt++;
416 			}
417 			prec = n < 0 ? -1 : n;
418 			goto reswitch;
419 		case '0':
420 			/*
421 			 * ``Note that 0 is taken as a flag, not as the
422 			 * beginning of a field width.''
423 			 *	-- ANSI X3J11
424 			 */
425 			flags |= ZEROPAD;
426 			goto rflag;
427 		case '1': case '2': case '3': case '4':
428 		case '5': case '6': case '7': case '8': case '9':
429 			n = 0;
430 			do {
431 				n = 10 * n + to_digit(ch);
432 				ch = *fmt++;
433 			} while (is_digit(ch));
434 			width = n;
435 			goto reswitch;
436 #ifdef FLOATING_POINT
437 		case 'L':
438 			flags |= LONGDBL;
439 			goto rflag;
440 #endif
441 		case 'h':
442 			flags |= SHORTINT;
443 			goto rflag;
444 		case 'j':
445 			flags |= MAXINT;
446 			goto rflag;
447 		case 'l':
448 			if (*fmt == 'l') {
449 				fmt++;
450 				flags |= QUADINT;
451 			} else {
452 				flags |= LONGINT;
453 			}
454 			goto rflag;
455 		case 'q':
456 			flags |= QUADINT;
457 			goto rflag;
458 		case 't':
459 			flags |= PTRINT;
460 			goto rflag;
461 		case 'z':
462 			flags |= SIZEINT;
463 			goto rflag;
464 		case 'c':
465 			*buf = va_arg(ap, int);
466 			cp = buf;
467 			size = 1;
468 			sign = '\0';
469 			break;
470 		case 'D':
471 			flags |= LONGINT;
472 			/*FALLTHROUGH*/
473 		case 'd':
474 		case 'i':
475 			_uintmax = SARG();
476 			if ((intmax_t)_uintmax < 0) {
477 				_uintmax = -_uintmax;
478 				sign = '-';
479 			}
480 			base = DEC;
481 			goto number;
482 #ifdef FLOATING_POINT
483 		case 'e':
484 		case 'E':
485 		case 'f':
486 		case 'F':
487 		case 'g':
488 		case 'G':
489 			if (prec == -1) {
490 				prec = DEFPREC;
491 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
492 				prec = 1;
493 			}
494 
495 			if (flags & LONGDBL) {
496 				_double = (double) va_arg(ap, long double);
497 			} else {
498 				_double = va_arg(ap, double);
499 			}
500 
501 			/* do this before tricky precision changes */
502 			if (isinf(_double)) {
503 				if (_double < 0)
504 					sign = '-';
505 				if (ch == 'E' || ch == 'F' || ch == 'G')
506 					cp = "INF";
507 				else
508 					cp = "inf";
509 				size = 3;
510 				break;
511 			}
512 			if (isnan(_double)) {
513 				if (ch == 'E' || ch == 'F' || ch == 'G')
514 					cp = "NAN";
515 				else
516 					cp = "nan";
517 				size = 3;
518 				break;
519 			}
520 
521 			flags |= FPT;
522 			cp = cvt(_double, prec, flags, &softsign,
523 				&expt, ch, &ndig);
524 			if (ch == 'g' || ch == 'G') {
525 				if (expt <= -4 || expt > prec)
526 					ch = (ch == 'g') ? 'e' : 'E';
527 				else
528 					ch = 'g';
529 			}
530 			if (ch == 'e' || ch == 'E') {
531 				--expt;
532 				expsize = exponent(expstr, expt, ch);
533 				size = expsize + ndig;
534 				if (ndig > 1 || flags & ALT)
535 					++size;
536 			} else if (ch == 'f' || ch == 'F') {
537 				if (expt > 0) {
538 					size = expt;
539 					if (prec || flags & ALT)
540 						size += prec + 1;
541 				} else	/* "0.X" */
542 					size = prec + 2;
543 			} else if (expt >= ndig) {	/* fixed g fmt */
544 				size = expt;
545 				if (flags & ALT)
546 					++size;
547 			} else
548 				size = ndig + (expt > 0 ?
549 					1 : 2 - expt);
550 
551 			if (softsign)
552 				sign = '-';
553 			break;
554 #endif /* FLOATING_POINT */
555 		case 'n':
556 			if (flags & MAXINT)
557 				*va_arg(ap, intmax_t *) = ret;
558 			else if (flags & PTRINT)
559 				*va_arg(ap, ptrdiff_t *) = ret;
560 			else if (flags & SIZEINT)
561 				*va_arg(ap, ssize_t *) = ret;	/* XXX */
562 			else if (flags & QUADINT)
563 				*va_arg(ap, quad_t *) = ret;
564 			else if (flags & LONGINT)
565 				*va_arg(ap, long *) = ret;
566 			else if (flags & SHORTINT)
567 				*va_arg(ap, short *) = ret;
568 			else
569 				*va_arg(ap, int *) = ret;
570 			continue;	/* no output */
571 		case 'O':
572 			flags |= LONGINT;
573 			/*FALLTHROUGH*/
574 		case 'o':
575 			_uintmax = UARG();
576 			base = OCT;
577 			goto nosign;
578 		case 'p':
579 			/*
580 			 * ``The argument shall be a pointer to void.  The
581 			 * value of the pointer is converted to a sequence
582 			 * of printable characters, in an implementation-
583 			 * defined manner.''
584 			 *	-- ANSI X3J11
585 			 */
586 			/* NOSTRICT */
587 			_uintmax = (u_long)va_arg(ap, void *);
588 			base = HEX;
589 			xdigs = "0123456789abcdef";
590 			flags |= HEXPREFIX;
591 			ch = 'x';
592 			goto nosign;
593 		case 's':
594 			if ((cp = va_arg(ap, char *)) == NULL)
595 				cp = "(null)";
596 			if (prec >= 0) {
597 				/*
598 				 * can't use strlen; can only look for the
599 				 * NUL in the first `prec' characters, and
600 				 * strlen() will go further.
601 				 */
602 				char *p = memchr(cp, 0, (size_t)prec);
603 
604 				if (p != NULL) {
605 					size = p - cp;
606 					if (size > prec)
607 						size = prec;
608 				} else
609 					size = prec;
610 			} else
611 				size = strlen(cp);
612 			sign = '\0';
613 			break;
614 		case 'U':
615 			flags |= LONGINT;
616 			/*FALLTHROUGH*/
617 		case 'u':
618 			_uintmax = UARG();
619 			base = DEC;
620 			goto nosign;
621 		case 'X':
622 			xdigs = "0123456789ABCDEF";
623 			goto hex;
624 		case 'x':
625 			xdigs = "0123456789abcdef";
626 hex:			_uintmax = UARG();
627 			base = HEX;
628 			/* leading 0x/X only if non-zero */
629 			if (flags & ALT && _uintmax != 0)
630 				flags |= HEXPREFIX;
631 
632 			/* unsigned conversions */
633 nosign:			sign = '\0';
634 			/*
635 			 * ``... diouXx conversions ... if a precision is
636 			 * specified, the 0 flag will be ignored.''
637 			 *	-- ANSI X3J11
638 			 */
639 number:			if ((dprec = prec) >= 0)
640 				flags &= ~ZEROPAD;
641 
642 			/*
643 			 * ``The result of converting a zero value with an
644 			 * explicit precision of zero is no characters.''
645 			 *	-- ANSI X3J11
646 			 */
647 			bp = buf + BUF;
648 			if (_uintmax != 0 || prec != 0) {
649 				/*
650 				 * Unsigned mod is hard, and unsigned mod
651 				 * by a constant is easier than that by
652 				 * a variable; hence this switch.
653 				 */
654 				switch (base) {
655 				case OCT:
656 					do {
657 						*--bp = to_char(_uintmax & 7);
658 						_uintmax >>= 3;
659 					} while (_uintmax);
660 					/* handle octal leading 0 */
661 					if (flags & ALT && *bp != '0')
662 						*--bp = '0';
663 					break;
664 
665 				case DEC:
666 					/* many numbers are 1 digit */
667 					while (_uintmax >= 10) {
668 						*--bp = to_char(_uintmax % 10);
669 						_uintmax /= 10;
670 					}
671 					*--bp = to_char(_uintmax);
672 					break;
673 
674 				case HEX:
675 					do {
676 						*--bp = xdigs[(size_t)
677 						    (_uintmax & 15)];
678 						_uintmax >>= 4;
679 					} while (_uintmax);
680 					break;
681 
682 				default:
683 					cp = "bug in vfprintf: bad base";
684 					size = strlen(cp);
685 					goto skipsize;
686 				}
687 			}
688 			cp = bp;
689 			size = buf + BUF - bp;
690 		skipsize:
691 			break;
692 		default:	/* "%?" prints ?, unless ? is NUL */
693 			if (ch == '\0')
694 				goto done;
695 			/* pretend it was %c with argument ch */
696 			*buf = ch;
697 			cp = buf;
698 			size = 1;
699 			sign = '\0';
700 			break;
701 		}
702 
703 		/*
704 		 * All reasonable formats wind up here.  At this point, `cp'
705 		 * points to a string which (if not flags&LADJUST) should be
706 		 * padded out to `width' places.  If flags&ZEROPAD, it should
707 		 * first be prefixed by any sign or other prefix; otherwise,
708 		 * it should be blank padded before the prefix is emitted.
709 		 * After any left-hand padding and prefixing, emit zeroes
710 		 * required by a decimal [diouxX] precision, then print the
711 		 * string proper, then emit zeroes required by any leftover
712 		 * floating precision; finally, if LADJUST, pad with blanks.
713 		 *
714 		 * Compute actual size, so we know how much to pad.
715 		 * size excludes decimal prec; realsz includes it.
716 		 */
717 		realsz = dprec > size ? dprec : size;
718 		if (sign)
719 			realsz++;
720 		else if (flags & HEXPREFIX)
721 			realsz+= 2;
722 
723 		/* right-adjusting blank padding */
724 		if ((flags & (LADJUST|ZEROPAD)) == 0)
725 			PAD(width - realsz, blanks);
726 
727 		/* prefix */
728 		if (sign) {
729 			PRINT(&sign, 1);
730 		} else if (flags & HEXPREFIX) {
731 			ox[0] = '0';
732 			ox[1] = ch;
733 			PRINT(ox, 2);
734 		}
735 
736 		/* right-adjusting zero padding */
737 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
738 			PAD(width - realsz, zeroes);
739 
740 		/* leading zeroes from decimal precision */
741 		PAD(dprec - size, zeroes);
742 
743 		/* the string or number proper */
744 #ifdef FLOATING_POINT
745 		if ((flags & FPT) == 0) {
746 			PRINT(cp, size);
747 		} else {	/* glue together f_p fragments */
748 			if (ch >= 'f') {	/* 'f' or 'g' */
749 				if (_double == 0) {
750 					/* kludge for __dtoa irregularity */
751 					PRINT("0", 1);
752 					if (expt < ndig || (flags & ALT) != 0) {
753 						PRINT(decimal_point, 1);
754 						PAD(ndig - 1, zeroes);
755 					}
756 				} else if (expt <= 0) {
757 					PRINT("0", 1);
758 					PRINT(decimal_point, 1);
759 					PAD(-expt, zeroes);
760 					PRINT(cp, ndig);
761 				} else if (expt >= ndig) {
762 					PRINT(cp, ndig);
763 					PAD(expt - ndig, zeroes);
764 					if (flags & ALT)
765 						PRINT(".", 1);
766 				} else {
767 					PRINT(cp, expt);
768 					cp += expt;
769 					PRINT(".", 1);
770 					PRINT(cp, ndig-expt);
771 				}
772 			} else {	/* 'e' or 'E' */
773 				if (ndig > 1 || flags & ALT) {
774 					ox[0] = *cp++;
775 					ox[1] = '.';
776 					PRINT(ox, 2);
777 					if (_double) {
778 						PRINT(cp, ndig-1);
779 					} else	/* 0.[0..] */
780 						/* __dtoa irregularity */
781 						PAD(ndig - 1, zeroes);
782 				} else	/* XeYYY */
783 					PRINT(cp, 1);
784 				PRINT(expstr, expsize);
785 			}
786 		}
787 #else
788 		PRINT(cp, size);
789 #endif
790 		/* left-adjusting padding (always blank) */
791 		if (flags & LADJUST)
792 			PAD(width - realsz, blanks);
793 
794 		/* finally, adjust ret */
795 		ret += width > realsz ? width : realsz;
796 
797 		FLUSH();	/* copy out the I/O vectors */
798 	}
799 done:
800 	FLUSH();
801 error:
802 	if (__sferror(fp))
803 		ret = -1;
804 	return (ret);
805 }
806 
807 #ifdef FLOATING_POINT
808 
809 static char *
810 cvt(value, ndigits, flags, sign, decpt, ch, length)
811 	double value;
812 	int ndigits, flags, *decpt, ch, *length;
813 	char *sign;
814 {
815 	int mode, dsgn;
816 	char *digits, *bp, *rve;
817 
818 	_DIAGASSERT(decpt != NULL);
819 	_DIAGASSERT(length != NULL);
820 	_DIAGASSERT(sign != NULL);
821 
822 	if (ch == 'f') {
823 		mode = 3;		/* ndigits after the decimal point */
824 	} else {
825 		/* To obtain ndigits after the decimal point for the 'e'
826 		 * and 'E' formats, round to ndigits + 1 significant
827 		 * figures.
828 		 */
829 		if (ch == 'e' || ch == 'E') {
830 			ndigits++;
831 		}
832 		mode = 2;		/* ndigits significant digits */
833 	}
834 
835 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
836 	if (dsgn) {
837 		value = -value;
838 		*sign = '-';
839 	} else
840 		*sign = '\000';
841 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
842 		bp = digits + ndigits;
843 		if (ch == 'f') {
844 			if (*digits == '0' && value)
845 				*decpt = -ndigits + 1;
846 			bp += *decpt;
847 		}
848 		if (value == 0)	/* kludge for __dtoa irregularity */
849 			rve = bp;
850 		while (rve < bp)
851 			*rve++ = '0';
852 	}
853 	*length = rve - digits;
854 	return (digits);
855 }
856 
857 static int
858 exponent(p0, expon, fmtch)
859 	char *p0;
860 	int expon, fmtch;
861 {
862 	char *p, *t;
863 	char expbuf[MAXEXP];
864 
865 	_DIAGASSERT(p0 != NULL);
866 
867 	p = p0;
868 	*p++ = fmtch;
869 	if (expon < 0) {
870 		expon = -expon;
871 		*p++ = '-';
872 	}
873 	else
874 		*p++ = '+';
875 	t = expbuf + MAXEXP;
876 	if (expon > 9) {
877 		do {
878 			*--t = to_char(expon % 10);
879 		} while ((expon /= 10) > 9);
880 		*--t = to_char(expon);
881 		for (; t < expbuf + MAXEXP; *p++ = *t++);
882 	}
883 	else {
884 		*p++ = '0';
885 		*p++ = to_char(expon);
886 	}
887 	return (p - p0);
888 }
889 #endif /* FLOATING_POINT */
890