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