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