vm: fix failed alloc condition
[minix.git] / lib / libc / stdio / vfwprintf.c
blob143afc03ab79a293649eb76eac16d008cf668d37
1 /* $NetBSD: vfwprintf.c,v 1.23 2010/12/16 17:42:27 wiz Exp $ */
3 /*-
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Chris Torek.
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.
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.
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
39 __FBSDID("$FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.27 2007/01/09 00:28:08 imp Exp $");
40 #else
41 __RCSID("$NetBSD: vfwprintf.c,v 1.23 2010/12/16 17:42:27 wiz Exp $");
42 #endif
43 #endif /* LIBC_SCCS and not lint */
46 * Actual {w,}printf innards.
49 #include "namespace.h"
50 #include <sys/types.h>
52 #include <assert.h>
53 #include <ctype.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <stdarg.h>
57 #include <stddef.h>
58 #include <stdint.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <errno.h>
63 #include <wchar.h>
64 #include <wctype.h>
66 #include "reentrant.h"
67 #include "local.h"
68 #include "extern.h"
69 #include "fvwrite.h"
71 #ifndef NARROW
72 #define MCHAR_T char
73 #define CHAR_T wchar_t
74 #define STRLEN(a) wcslen(a)
75 #define MEMCHR(a, b, c) wmemchr(a, b, c)
76 #define SCONV(a, b) __mbsconv(a, b)
77 #define STRCONST(a) L ## a
78 #define WDECL(a, b) a ## w ## b
79 #define END_OF_FILE WEOF
80 #define MULTI 0
81 #else
82 #define MCHAR_T wchar_t
83 #define CHAR_T char
84 #define STRLEN(a) strlen(a)
85 #define MEMCHR(a, b, c) memchr(a, b, c)
86 #define SCONV(a, b) __wcsconv(a, b)
87 #define STRCONST(a) a
88 #define WDECL(a, b) a ## b
89 #define END_OF_FILE EOF
90 #define MULTI LONGINT
91 #endif
93 union arg {
94 int intarg;
95 u_int uintarg;
96 long longarg;
97 u_long ulongarg;
98 long long longlongarg;
99 unsigned long long ulonglongarg;
100 ptrdiff_t ptrdiffarg;
101 ssize_t ssizearg;
102 size_t sizearg;
103 intmax_t intmaxarg;
104 uintmax_t uintmaxarg;
105 void *pvoidarg;
106 char *pchararg;
107 signed char *pschararg;
108 short *pshortarg;
109 int *pintarg;
110 long *plongarg;
111 long long *plonglongarg;
112 ptrdiff_t *pptrdiffarg;
113 size_t *psizearg;
114 intmax_t *pintmaxarg;
115 #ifndef NO_FLOATING_POINT
116 double doublearg;
117 long double longdoublearg;
118 #endif
119 wint_t wintarg;
120 wchar_t *pwchararg;
124 * Type ids for argument type table.
126 enum typeid {
127 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
128 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
129 T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SIZET,
130 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
131 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
134 static int __sbprintf(FILE *, const CHAR_T *, va_list);
135 static CHAR_T *__ujtoa(uintmax_t, CHAR_T *, int, int, const char *, int,
136 char, const char *);
137 static CHAR_T *__ultoa(u_long, CHAR_T *, int, int, const char *, int,
138 char, const char *);
139 #ifndef NARROW
140 static CHAR_T *__mbsconv(char *, int);
141 static wint_t __xfputwc(CHAR_T, FILE *);
142 #else
143 static char *__wcsconv(wchar_t *, int);
144 static int __sprint(FILE *, struct __suio *);
145 #endif
146 static int __find_arguments(const CHAR_T *, va_list, union arg **);
147 static int __grow_type_table(int, enum typeid **, int *);
150 * Helper function for `fprintf to unbuffered unix file': creates a
151 * temporary buffer. We only work on write-only files; this avoids
152 * worries about ungetc buffers and so forth.
154 static int
155 __sbprintf(FILE *fp, const CHAR_T *fmt, va_list ap)
157 int ret;
158 FILE fake;
159 struct __sfileext fakeext;
160 unsigned char buf[BUFSIZ];
162 _DIAGASSERT(fp != NULL);
163 _DIAGASSERT(fmt != NULL);
165 _FILEEXT_SETUP(&fake, &fakeext);
166 memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
168 /* copy the important variables */
169 fake._flags = fp->_flags & ~__SNBF;
170 fake._file = fp->_file;
171 fake._cookie = fp->_cookie;
172 fake._write = fp->_write;
174 /* set up the buffer */
175 fake._bf._base = fake._p = buf;
176 fake._bf._size = fake._w = sizeof(buf);
177 fake._lbfsize = 0; /* not actually used, but Just In Case */
179 /* do the work, then copy any error status */
180 ret = WDECL(__vf,printf_unlocked)(&fake, fmt, ap);
181 if (ret >= 0 && fflush(&fake))
182 ret = END_OF_FILE;
183 if (fake._flags & __SERR)
184 fp->_flags |= __SERR;
185 return (ret);
188 #ifndef NARROW
190 * Like __fputwc, but handles fake string (__SSTR) files properly.
191 * File must already be locked.
193 static wint_t
194 __xfputwc(wchar_t wc, FILE *fp)
196 static const mbstate_t initial;
197 mbstate_t mbs;
198 char buf[MB_LEN_MAX];
199 struct __suio uio;
200 struct __siov iov;
201 size_t len;
203 if ((fp->_flags & __SSTR) == 0)
204 return (__fputwc_unlock(wc, fp));
206 mbs = initial;
207 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
208 fp->_flags |= __SERR;
209 return (END_OF_FILE);
211 uio.uio_iov = &iov;
212 uio.uio_resid = len;
213 uio.uio_iovcnt = 1;
214 iov.iov_base = buf;
215 iov.iov_len = len;
216 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE);
218 #else
220 * Flush out all the vectors defined by the given uio,
221 * then reset it so that it can be reused.
223 static int
224 __sprint(FILE *fp, struct __suio *uio)
226 int err;
228 _DIAGASSERT(fp != NULL);
229 _DIAGASSERT(uio != NULL);
231 if (uio->uio_resid == 0) {
232 uio->uio_iovcnt = 0;
233 return (0);
235 err = __sfvwrite(fp, uio);
236 uio->uio_resid = 0;
237 uio->uio_iovcnt = 0;
238 return (err);
240 #endif
243 * Macros for converting digits to letters and vice versa
245 #define to_digit(c) ((c) - '0')
246 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
247 #define to_char(n) (CHAR_T)((n) + '0')
250 * Convert an unsigned long to ASCII for printf purposes, returning
251 * a pointer to the first character of the string representation.
252 * Octal numbers can be forced to have a leading zero; hex numbers
253 * use the given digits.
255 static CHAR_T *
256 __ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs,
257 int needgrp, char thousep, const char *grp)
259 CHAR_T *cp = endp;
260 long sval;
261 int ndig;
264 * Handle the three cases separately, in the hope of getting
265 * better/faster code.
267 switch (base) {
268 case 10:
269 if (val < 10) { /* many numbers are 1 digit */
270 *--cp = to_char(val);
271 return (cp);
273 ndig = 0;
275 * On many machines, unsigned arithmetic is harder than
276 * signed arithmetic, so we do at most one unsigned mod and
277 * divide; this is sufficient to reduce the range of
278 * the incoming value to where signed arithmetic works.
280 if (val > LONG_MAX) {
281 *--cp = to_char(val % 10);
282 ndig++;
283 sval = val / 10;
284 } else
285 sval = val;
286 do {
287 *--cp = to_char(sval % 10);
288 ndig++;
290 * If (*grp == CHAR_MAX) then no more grouping
291 * should be performed.
293 if (needgrp && ndig == *grp && *grp != CHAR_MAX
294 && sval > 9) {
295 *--cp = thousep;
296 ndig = 0;
298 * If (*(grp+1) == '\0') then we have to
299 * use *grp character (last grouping rule)
300 * for all next cases
302 if (*(grp+1) != '\0')
303 grp++;
305 sval /= 10;
306 } while (sval != 0);
307 break;
309 case 8:
310 do {
311 *--cp = to_char(val & 7);
312 val >>= 3;
313 } while (val);
314 if (octzero && *cp != '0')
315 *--cp = '0';
316 break;
318 case 16:
319 do {
320 *--cp = xdigs[(size_t)val & 15];
321 val >>= 4;
322 } while (val);
323 break;
325 default: /* oops */
326 abort();
328 return (cp);
331 /* Identical to __ultoa, but for intmax_t. */
332 static CHAR_T *
333 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero,
334 const char *xdigs, int needgrp, char thousep, const char *grp)
336 CHAR_T *cp = endp;
337 intmax_t sval;
338 int ndig;
340 /* quick test for small values; __ultoa is typically much faster */
341 /* (perhaps instead we should run until small, then call __ultoa?) */
342 if (val <= ULONG_MAX)
343 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
344 needgrp, thousep, grp));
345 switch (base) {
346 case 10:
347 if (val < 10) {
348 *--cp = to_char(val % 10);
349 return (cp);
351 ndig = 0;
352 if (val > INTMAX_MAX) {
353 *--cp = to_char(val % 10);
354 ndig++;
355 sval = val / 10;
356 } else
357 sval = val;
358 do {
359 *--cp = to_char(sval % 10);
360 ndig++;
362 * If (*grp == CHAR_MAX) then no more grouping
363 * should be performed.
365 if (needgrp && *grp != CHAR_MAX && ndig == *grp
366 && sval > 9) {
367 *--cp = thousep;
368 ndig = 0;
370 * If (*(grp+1) == '\0') then we have to
371 * use *grp character (last grouping rule)
372 * for all next cases
374 if (*(grp+1) != '\0')
375 grp++;
377 sval /= 10;
378 } while (sval != 0);
379 break;
381 case 8:
382 do {
383 *--cp = to_char(val & 7);
384 val >>= 3;
385 } while (val);
386 if (octzero && *cp != '0')
387 *--cp = '0';
388 break;
390 case 16:
391 do {
392 *--cp = xdigs[(size_t)val & 15];
393 val >>= 4;
394 } while (val);
395 break;
397 default:
398 abort();
400 return (cp);
403 #ifndef NARROW
405 * Convert a multibyte character string argument for the %s format to a wide
406 * string representation. ``prec'' specifies the maximum number of bytes
407 * to output. If ``prec'' is greater than or equal to zero, we can't assume
408 * that the multibyte char. string ends in a null character.
410 static wchar_t *
411 __mbsconv(char *mbsarg, int prec)
413 static const mbstate_t initial;
414 mbstate_t mbs;
415 wchar_t *convbuf, *wcp;
416 const char *p;
417 size_t insize, nchars, nconv;
419 if (mbsarg == NULL)
420 return (NULL);
423 * Supplied argument is a multibyte string; convert it to wide
424 * characters first.
426 if (prec >= 0) {
428 * String is not guaranteed to be NUL-terminated. Find the
429 * number of characters to print.
431 p = mbsarg;
432 insize = nchars = nconv = 0;
433 mbs = initial;
434 while (nchars != (size_t)prec) {
435 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
436 if (nconv == 0 || nconv == (size_t)-1 ||
437 nconv == (size_t)-2)
438 break;
439 p += nconv;
440 nchars++;
441 insize += nconv;
443 if (nconv == (size_t)-1 || nconv == (size_t)-2)
444 return (NULL);
445 } else
446 insize = strlen(mbsarg);
449 * Allocate buffer for the result and perform the conversion,
450 * converting at most `size' bytes of the input multibyte string to
451 * wide characters for printing.
453 convbuf = malloc((insize + 1) * sizeof(*convbuf));
454 if (convbuf == NULL)
455 return (NULL);
456 wcp = convbuf;
457 p = mbsarg;
458 mbs = initial;
459 nconv = 0;
460 while (insize != 0) {
461 nconv = mbrtowc(wcp, p, insize, &mbs);
462 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
463 break;
464 wcp++;
465 p += nconv;
466 insize -= nconv;
468 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
469 free(convbuf);
470 return (NULL);
472 *wcp = L'\0';
474 return (convbuf);
476 #else
478 * Convert a wide-character string argument for the %ls format to a multibyte
479 * string representation. If not -1, prec specifies the maximum number of
480 * bytes to output, and also means that we can't assume that the wide-char.
481 * string ends is null-terminated.
483 static char *
484 __wcsconv(wchar_t *wcsarg, int prec)
486 static const mbstate_t initial;
487 mbstate_t mbs;
488 char buf[MB_LEN_MAX];
489 wchar_t *p;
490 char *convbuf;
491 size_t clen, nbytes;
493 /* Allocate space for the maximum number of bytes we could output. */
494 if (prec < 0) {
495 p = wcsarg;
496 mbs = initial;
497 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
498 if (nbytes == (size_t)-1)
499 return (NULL);
500 } else {
502 * Optimisation: if the output precision is small enough,
503 * just allocate enough memory for the maximum instead of
504 * scanning the string.
506 if (prec < 128)
507 nbytes = prec;
508 else {
509 nbytes = 0;
510 p = wcsarg;
511 mbs = initial;
512 for (;;) {
513 clen = wcrtomb(buf, *p++, &mbs);
514 if (clen == 0 || clen == (size_t)-1 ||
515 nbytes + clen > (size_t)prec)
516 break;
517 nbytes += clen;
521 if ((convbuf = malloc(nbytes + 1)) == NULL)
522 return (NULL);
524 /* Fill the output buffer. */
525 p = wcsarg;
526 mbs = initial;
527 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
528 nbytes, &mbs)) == (size_t)-1) {
529 free(convbuf);
530 return (NULL);
532 convbuf[nbytes] = '\0';
533 return (convbuf);
535 #endif
538 * MT-safe version
541 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap)
543 int ret;
545 FLOCKFILE(fp);
546 ret = WDECL(__vf,printf_unlocked)(fp, fmt0, ap);
547 FUNLOCKFILE(fp);
548 return (ret);
551 #ifndef NO_FLOATING_POINT
553 #include <float.h>
554 #include <math.h>
555 #include "floatio.h"
557 #define DEFPREC 6
559 static int exponent(CHAR_T *, int, int);
560 #ifndef WIDE_DOUBLE
561 static char *cvt(double, int, int, char *, int *, int, int *);
562 #endif
564 #endif /* !NO_FLOATING_POINT */
567 * The size of the buffer we use as scratch space for integer
568 * conversions, among other things. Technically, we would need the
569 * most space for base 10 conversions with thousands' grouping
570 * characters between each pair of digits. 100 bytes is a
571 * conservative overestimate even for a 128-bit uintmax_t.
573 #define BUF 100
575 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
578 * Flags used during conversion.
580 #define ALT 0x001 /* alternate form */
581 #define LADJUST 0x004 /* left adjustment */
582 #define LONGDBL 0x008 /* long double */
583 #define LONGINT 0x010 /* long integer */
584 #define LLONGINT 0x020 /* long long integer */
585 #define SHORTINT 0x040 /* short integer */
586 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
587 #define FPT 0x100 /* Floating point number */
588 #define GROUPING 0x200 /* use grouping ("'" flag) */
589 /* C99 additional size modifiers: */
590 #define SIZET 0x400 /* size_t */
591 #define PTRDIFFT 0x800 /* ptrdiff_t */
592 #define INTMAXT 0x1000 /* intmax_t */
593 #define CHARINT 0x2000 /* print char using int format */
596 * Non-MT-safe version
599 WDECL(__vf,printf_unlocked)(FILE *fp, const CHAR_T *fmt0, va_list ap)
601 CHAR_T *fmt; /* format string */
602 int ch; /* character from fmt */
603 int n, n2; /* handy integer (short term usage) */
604 CHAR_T *cp; /* handy char pointer (short term usage) */
605 int flags; /* flags as above */
606 int ret; /* return value accumulator */
607 int width; /* width from format (%8d), or 0 */
608 int prec; /* precision from format; <0 for N/A */
609 CHAR_T sign; /* sign prefix (' ', '+', '-', or \0) */
610 char thousands_sep; /* locale specific thousands separator */
611 const char *grouping; /* locale specific numeric grouping rules */
612 #ifndef NO_FLOATING_POINT
614 * We can decompose the printed representation of floating
615 * point numbers into several parts, some of which may be empty:
617 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
618 * A B ---C--- D E F
620 * A: 'sign' holds this value if present; '\0' otherwise
621 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
622 * C: cp points to the string MMMNNN. Leading and trailing
623 * zeros are not in the string and must be added.
624 * D: expchar holds this character; '\0' if no exponent, e.g. %f
625 * F: at least two digits for decimal, at least one digit for hex
627 char *decimal_point; /* locale specific decimal point */
628 #ifdef WIDE_DOUBLE
629 int signflag; /* true if float is negative */
630 union { /* floating point arguments %[aAeEfFgG] */
631 double dbl;
632 long double ldbl;
633 } fparg;
634 char *dtoaend; /* pointer to end of converted digits */
635 #else
636 double _double; /* double precision arguments %[eEfgG] */
637 char softsign; /* temporary negative sign for floats */
638 #endif
639 char *dtoaresult; /* buffer allocated by dtoa */
640 int expt; /* integer value of exponent */
641 char expchar; /* exponent character: [eEpP\0] */
642 int expsize; /* character count for expstr */
643 int lead; /* sig figs before decimal or group sep */
644 int ndig; /* actual number of digits returned by dtoa */
645 CHAR_T expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
646 int nseps; /* number of group separators with ' */
647 int nrepeats; /* number of repeats of the last group */
648 #endif
649 u_long ulval; /* integer arguments %[diouxX] */
650 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
651 int base; /* base for [diouxX] conversion */
652 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
653 int realsz; /* field size expanded by dprec, sign, etc */
654 int size; /* size of converted field or string */
655 int prsize; /* max size of printed field */
656 const char *xdigs; /* digits for %[xX] conversion */
657 #ifdef NARROW
658 #define NIOV 8
659 struct __siov *iovp; /* for PRINT macro */
660 struct __suio uio; /* output information: summary */
661 struct __siov iov[NIOV];/* ... and individual io vectors */
662 #else
663 int n3;
664 #endif
665 CHAR_T buf[BUF]; /* buffer with space for digits of uintmax_t */
666 CHAR_T ox[2]; /* space for 0x hex-prefix */
667 union arg *argtable; /* args, built due to positional arg */
668 union arg statargtable [STATIC_ARG_TBL_SIZE];
669 int nextarg; /* 1-based argument index */
670 va_list orgap; /* original argument pointer */
671 CHAR_T *convbuf; /* multibyte to wide conversion result */
674 * Choose PADSIZE to trade efficiency vs. size. If larger printf
675 * fields occur frequently, increase PADSIZE and make the initialisers
676 * below longer.
678 #define PADSIZE 16 /* pad chunk size */
679 static CHAR_T blanks[PADSIZE] =
680 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
681 static CHAR_T zeroes[PADSIZE] =
682 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
684 static const char xdigs_lower[16] = "0123456789abcdef";
685 static const char xdigs_upper[16] = "0123456789ABCDEF";
688 * BEWARE, these `goto error' on error, PRINT uses `n2' and
689 * PAD uses `n'.
691 #ifndef NARROW
692 #define PRINT(ptr, len) do { \
693 for (n3 = 0; n3 < (len); n3++) \
694 __xfputwc((ptr)[n3], fp); \
695 } while (/*CONSTCOND*/0)
696 #define FLUSH()
697 #else
698 #define PRINT(ptr, len) do { \
699 iovp->iov_base = __UNCONST(ptr); \
700 iovp->iov_len = (len); \
701 uio.uio_resid += (len); \
702 iovp++; \
703 if (++uio.uio_iovcnt >= NIOV) { \
704 if (__sprint(fp, &uio)) \
705 goto error; \
706 iovp = iov; \
708 } while (/*CONSTCOND*/0)
709 #define FLUSH() do { \
710 if (uio.uio_resid && __sprint(fp, &uio)) \
711 goto error; \
712 uio.uio_iovcnt = 0; \
713 iovp = iov; \
714 } while (/*CONSTCOND*/0)
715 #endif /* NARROW */
717 #define PAD(howmany, with) do { \
718 if ((n = (howmany)) > 0) { \
719 while (n > PADSIZE) { \
720 PRINT(with, PADSIZE); \
721 n -= PADSIZE; \
723 PRINT(with, n); \
725 } while (/*CONSTCOND*/0)
726 #define PRINTANDPAD(p, ep, len, with) do { \
727 n2 = (ep) - (p); \
728 if (n2 > (len)) \
729 n2 = (len); \
730 if (n2 > 0) \
731 PRINT((p), n2); \
732 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
733 } while(/*CONSTCOND*/0)
736 * Get the argument indexed by nextarg. If the argument table is
737 * built, use it to get the argument. If its not, get the next
738 * argument (and arguments must be gotten sequentially).
740 #define GETARG(type) \
741 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
742 (nextarg++, va_arg(ap, type)))
745 * To extend shorts properly, we need both signed and unsigned
746 * argument extraction methods.
748 #define SARG() \
749 (flags&LONGINT ? GETARG(long) : \
750 flags&SHORTINT ? (long)(short)GETARG(int) : \
751 flags&CHARINT ? (long)(signed char)GETARG(int) : \
752 (long)GETARG(int))
753 #define UARG() \
754 (flags&LONGINT ? GETARG(u_long) : \
755 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
756 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
757 (u_long)GETARG(u_int))
758 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
759 #define SJARG() \
760 (flags&INTMAXT ? GETARG(intmax_t) : \
761 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
762 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
763 (intmax_t)GETARG(long long))
764 #define UJARG() \
765 (flags&INTMAXT ? GETARG(uintmax_t) : \
766 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
767 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
768 (uintmax_t)GETARG(unsigned long long))
771 * Get * arguments, including the form *nn$. Preserve the nextarg
772 * that the argument can be gotten once the type is determined.
774 #define GETASTER(val) \
775 n2 = 0; \
776 cp = fmt; \
777 while (is_digit(*cp)) { \
778 n2 = 10 * n2 + to_digit(*cp); \
779 cp++; \
781 if (*cp == '$') { \
782 int hold = nextarg; \
783 if (argtable == NULL) { \
784 argtable = statargtable; \
785 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
786 goto oomem; \
788 nextarg = n2; \
789 val = GETARG (int); \
790 nextarg = hold; \
791 fmt = ++cp; \
792 } else { \
793 val = GETARG (int); \
796 _DIAGASSERT(fp != NULL);
797 _DIAGASSERT(fmt0 != NULL);
799 _SET_ORIENTATION(fp, -1);
801 ndig = -1; /* XXX gcc */
803 thousands_sep = '\0';
804 grouping = NULL;
805 #ifndef NO_FLOATING_POINT
806 decimal_point = localeconv()->decimal_point;
807 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
808 #endif
809 convbuf = NULL;
810 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
811 if (cantwrite(fp)) {
812 errno = EBADF;
813 return (END_OF_FILE);
816 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
817 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
818 __sfileno(fp) != -1)
819 return (__sbprintf(fp, fmt0, ap));
821 fmt = (CHAR_T *)__UNCONST(fmt0);
822 argtable = NULL;
823 nextarg = 1;
824 va_copy(orgap, ap);
825 #ifdef NARROW
826 uio.uio_iov = iovp = iov;
827 uio.uio_resid = 0;
828 uio.uio_iovcnt = 0;
829 #endif
830 ret = 0;
833 * Scan the format for conversions (`%' character).
835 for (;;) {
836 const CHAR_T *result;
838 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
839 continue;
840 if ((n = fmt - cp) != 0) {
841 if ((unsigned)ret + n > INT_MAX) {
842 ret = END_OF_FILE;
843 goto error;
845 PRINT(cp, n);
846 ret += n;
848 if (ch == '\0')
849 goto done;
850 fmt++; /* skip over '%' */
852 flags = 0;
853 dprec = 0;
854 width = 0;
855 prec = -1;
856 sign = '\0';
857 ox[1] = '\0';
858 expchar = '\0';
859 lead = 0;
860 nseps = nrepeats = 0;
861 ulval = 0;
862 ujval = 0;
863 xdigs = NULL;
865 rflag: ch = *fmt++;
866 reswitch: switch (ch) {
867 case ' ':
869 * ``If the space and + flags both appear, the space
870 * flag will be ignored.''
871 * -- ANSI X3J11
873 if (!sign)
874 sign = ' ';
875 goto rflag;
876 case '#':
877 flags |= ALT;
878 goto rflag;
879 case '*':
881 * ``A negative field width argument is taken as a
882 * - flag followed by a positive field width.''
883 * -- ANSI X3J11
884 * They don't exclude field widths read from args.
886 GETASTER (width);
887 if (width >= 0)
888 goto rflag;
889 width = -width;
890 /* FALLTHROUGH */
891 case '-':
892 flags |= LADJUST;
893 goto rflag;
894 case '+':
895 sign = '+';
896 goto rflag;
897 case '\'':
898 flags |= GROUPING;
899 thousands_sep = *(localeconv()->thousands_sep);
900 grouping = localeconv()->grouping;
901 /* If the locale doesn't define the above, use sane
902 * defaults - otherwise silly things happen! */
903 if (thousands_sep == 0)
904 thousands_sep = ',';
905 if (!grouping || !*grouping)
906 grouping = "\3";
907 goto rflag;
908 case '.':
909 if ((ch = *fmt++) == '*') {
910 GETASTER (prec);
911 goto rflag;
913 prec = 0;
914 while (is_digit(ch)) {
915 prec = 10 * prec + to_digit(ch);
916 ch = *fmt++;
918 goto reswitch;
919 case '0':
921 * ``Note that 0 is taken as a flag, not as the
922 * beginning of a field width.''
923 * -- ANSI X3J11
925 flags |= ZEROPAD;
926 goto rflag;
927 case '1': case '2': case '3': case '4':
928 case '5': case '6': case '7': case '8': case '9':
929 n = 0;
930 do {
931 n = 10 * n + to_digit(ch);
932 ch = *fmt++;
933 } while (is_digit(ch));
934 if (ch == '$') {
935 nextarg = n;
936 if (argtable == NULL) {
937 argtable = statargtable;
938 if (__find_arguments(fmt0, orgap,
939 &argtable) == -1)
940 goto oomem;
942 goto rflag;
944 width = n;
945 goto reswitch;
946 #ifndef NO_FLOATING_POINT
947 case 'L':
948 flags |= LONGDBL;
949 goto rflag;
950 #endif
951 case 'h':
952 if (flags & SHORTINT) {
953 flags &= ~SHORTINT;
954 flags |= CHARINT;
955 } else
956 flags |= SHORTINT;
957 goto rflag;
958 case 'j':
959 flags |= INTMAXT;
960 goto rflag;
961 case 'l':
962 if (flags & LONGINT) {
963 flags &= ~LONGINT;
964 flags |= LLONGINT;
965 } else
966 flags |= LONGINT;
967 goto rflag;
968 case 'q':
969 flags |= LLONGINT; /* not necessarily */
970 goto rflag;
971 case 't':
972 flags |= PTRDIFFT;
973 goto rflag;
974 case 'z':
975 flags |= SIZET;
976 goto rflag;
977 case 'C':
978 flags |= LONGINT;
979 /*FALLTHROUGH*/
980 case 'c':
981 #ifdef NARROW
982 if (flags & LONGINT) {
983 static const mbstate_t initial;
984 mbstate_t mbs;
985 size_t mbseqlen;
987 mbs = initial;
988 mbseqlen = wcrtomb(buf,
989 (wchar_t)GETARG(wint_t), &mbs);
990 if (mbseqlen == (size_t)-1) {
991 fp->_flags |= __SERR;
992 goto error;
994 size = (int)mbseqlen;
995 } else {
996 *buf = GETARG(int);
997 size = 1;
999 #else
1000 if (flags & LONGINT)
1001 *buf = (wchar_t)GETARG(wint_t);
1002 else
1003 *buf = (wchar_t)btowc(GETARG(int));
1004 size = 1;
1005 #endif
1006 result = buf;
1007 sign = '\0';
1008 break;
1009 case 'D':
1010 flags |= LONGINT;
1011 /*FALLTHROUGH*/
1012 case 'd':
1013 case 'i':
1014 if (flags & INTMAX_SIZE) {
1015 ujval = SJARG();
1016 if ((intmax_t)ujval < 0) {
1017 ujval = -ujval;
1018 sign = '-';
1020 } else {
1021 ulval = SARG();
1022 if ((long)ulval < 0) {
1023 ulval = -ulval;
1024 sign = '-';
1027 base = 10;
1028 goto number;
1029 #ifndef NO_FLOATING_POINT
1030 #ifdef WIDE_DOUBLE
1031 case 'a':
1032 case 'A':
1033 if (ch == 'a') {
1034 ox[1] = 'x';
1035 xdigs = xdigs_lower;
1036 expchar = 'p';
1037 } else {
1038 ox[1] = 'X';
1039 xdigs = xdigs_upper;
1040 expchar = 'P';
1042 if (prec >= 0)
1043 prec++;
1044 if (flags & LONGDBL) {
1045 fparg.ldbl = GETARG(long double);
1046 dtoaresult =
1047 __hldtoa(fparg.ldbl, xdigs, prec,
1048 &expt, &signflag, &dtoaend);
1049 } else {
1050 fparg.dbl = GETARG(double);
1051 dtoaresult =
1052 __hdtoa(fparg.dbl, xdigs, prec,
1053 &expt, &signflag, &dtoaend);
1055 if (dtoaresult == NULL)
1056 goto oomem;
1058 if (prec < 0)
1059 prec = dtoaend - dtoaresult;
1060 if (expt == INT_MAX)
1061 ox[1] = '\0';
1062 ndig = dtoaend - dtoaresult;
1063 if (convbuf != NULL)
1064 free(convbuf);
1065 #ifndef NARROW
1066 result = convbuf = __mbsconv(dtoaresult, -1);
1067 #else
1068 /*XXX inefficient*/
1069 result = convbuf = strdup(dtoaresult);
1070 #endif
1071 if (result == NULL)
1072 goto oomem;
1073 __freedtoa(dtoaresult);
1074 goto fp_common;
1075 case 'e':
1076 case 'E':
1077 expchar = ch;
1078 if (prec < 0) /* account for digit before decpt */
1079 prec = DEFPREC + 1;
1080 else
1081 prec++;
1082 goto fp_begin;
1083 case 'f':
1084 case 'F':
1085 expchar = '\0';
1086 goto fp_begin;
1087 case 'g':
1088 case 'G':
1089 expchar = ch - ('g' - 'e');
1090 if (prec == 0)
1091 prec = 1;
1092 fp_begin:
1093 if (prec < 0)
1094 prec = DEFPREC;
1095 if (flags & LONGDBL) {
1096 fparg.ldbl = GETARG(long double);
1097 dtoaresult =
1098 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
1099 &expt, &signflag, &dtoaend);
1100 } else {
1101 fparg.dbl = GETARG(double);
1102 dtoaresult =
1103 __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
1104 &expt, &signflag, &dtoaend);
1105 if (expt == 9999)
1106 expt = INT_MAX;
1108 if (dtoaresult == NULL)
1109 goto oomem;
1110 ndig = dtoaend - dtoaresult;
1111 if (convbuf != NULL)
1112 free(convbuf);
1113 #ifndef NARROW
1114 result = convbuf = __mbsconv(dtoaresult, -1);
1115 #else
1116 /*XXX inefficient*/
1117 result = convbuf = strdup(dtoaresult);
1118 #endif
1119 if (result == NULL)
1120 goto oomem;
1121 __freedtoa(dtoaresult);
1122 fp_common:
1123 if (signflag)
1124 sign = '-';
1125 if (expt == INT_MAX) { /* inf or nan */
1126 if (*result == 'N') {
1127 result = (ch >= 'a') ? STRCONST("nan") :
1128 STRCONST("NAN");
1129 sign = '\0';
1130 } else
1131 result = (ch >= 'a') ? STRCONST("inf") :
1132 STRCONST("INF");
1133 size = 3;
1134 flags &= ~ZEROPAD;
1135 break;
1137 #else
1138 case 'e':
1139 case 'E':
1140 case 'f':
1141 case 'F':
1142 case 'g':
1143 case 'G':
1144 if (prec == -1) {
1145 prec = DEFPREC;
1146 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
1147 prec = 1;
1150 if (flags & LONGDBL) {
1151 _double = (double) GETARG(long double);
1152 } else {
1153 _double = GETARG(double);
1156 /* do this before tricky precision changes */
1157 if (isinf(_double)) {
1158 if (_double < 0)
1159 sign = '-';
1160 if (ch == 'E' || ch == 'F' || ch == 'G')
1161 result = STRCONST("INF");
1162 else
1163 result = STRCONST("inf");
1164 size = 3;
1165 flags &= ~ZEROPAD;
1166 break;
1168 if (isnan(_double)) {
1169 if (ch == 'E' || ch == 'F' || ch == 'G')
1170 result = STRCONST("NAN");
1171 else
1172 result = STRCONST("nan");
1173 size = 3;
1174 flags &= ~ZEROPAD;
1175 break;
1178 flags |= FPT;
1179 dtoaresult = cvt(_double, prec, flags, &softsign,
1180 &expt, ch, &ndig);
1181 if (dtoaresult == NULL)
1182 goto oomem;
1183 if (convbuf != NULL)
1184 free(convbuf);
1185 #ifndef NARROW
1186 result = convbuf = __mbsconv(dtoaresult, -1);
1187 #else
1188 /*XXX inefficient*/
1189 result = convbuf = strdup(dtoaresult);
1190 #endif
1191 if (result == NULL)
1192 goto oomem;
1193 __freedtoa(dtoaresult);
1194 if (softsign)
1195 sign = '-';
1196 #endif
1197 flags |= FPT;
1198 if (ch == 'g' || ch == 'G') {
1199 if (expt > -4 && expt <= prec) {
1200 /* Make %[gG] smell like %[fF] */
1201 expchar = '\0';
1202 if (flags & ALT)
1203 prec -= expt;
1204 else
1205 prec = ndig - expt;
1206 if (prec < 0)
1207 prec = 0;
1208 } else {
1210 * Make %[gG] smell like %[eE], but
1211 * trim trailing zeroes if no # flag.
1213 if (!(flags & ALT))
1214 prec = ndig;
1217 if (expchar) {
1218 expsize = exponent(expstr, expt - 1, expchar);
1219 size = expsize + prec;
1220 if (prec > 1 || flags & ALT)
1221 ++size;
1222 } else {
1223 /* space for digits before decimal point */
1224 if (expt > 0)
1225 size = expt;
1226 else /* "0" */
1227 size = 1;
1228 /* space for decimal pt and following digits */
1229 if (prec || flags & ALT)
1230 size += prec + 1;
1231 if (grouping && expt > 0) {
1232 /* space for thousands' grouping */
1233 nseps = nrepeats = 0;
1234 lead = expt;
1235 while (*grouping != CHAR_MAX) {
1236 if (lead <= *grouping)
1237 break;
1238 lead -= *grouping;
1239 if (*(grouping+1)) {
1240 nseps++;
1241 grouping++;
1242 } else
1243 nrepeats++;
1245 size += nseps + nrepeats;
1246 } else
1247 lead = expt;
1249 break;
1250 #endif /* !NO_FLOATING_POINT */
1251 case 'n':
1253 * Assignment-like behavior is specified if the
1254 * value overflows or is otherwise unrepresentable.
1255 * C99 says to use `signed char' for %hhn conversions.
1257 if (flags & LLONGINT)
1258 *GETARG(long long *) = ret;
1259 else if (flags & SIZET)
1260 *GETARG(ssize_t *) = (ssize_t)ret;
1261 else if (flags & PTRDIFFT)
1262 *GETARG(ptrdiff_t *) = ret;
1263 else if (flags & INTMAXT)
1264 *GETARG(intmax_t *) = ret;
1265 else if (flags & LONGINT)
1266 *GETARG(long *) = ret;
1267 else if (flags & SHORTINT)
1268 *GETARG(short *) = ret;
1269 else if (flags & CHARINT)
1270 *GETARG(signed char *) = ret;
1271 else
1272 *GETARG(int *) = ret;
1273 continue; /* no output */
1274 case 'O':
1275 flags |= LONGINT;
1276 /*FALLTHROUGH*/
1277 case 'o':
1278 if (flags & INTMAX_SIZE)
1279 ujval = UJARG();
1280 else
1281 ulval = UARG();
1282 base = 8;
1283 goto nosign;
1284 case 'p':
1286 * ``The argument shall be a pointer to void. The
1287 * value of the pointer is converted to a sequence
1288 * of printable characters, in an implementation-
1289 * defined manner.''
1290 * -- ANSI X3J11
1292 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1293 base = 16;
1294 xdigs = xdigs_lower;
1295 flags = flags | INTMAXT;
1296 ox[1] = 'x';
1297 goto nosign;
1298 case 'S':
1299 flags |= LONGINT;
1300 /*FALLTHROUGH*/
1301 case 's':
1302 if ((flags & LONGINT) != MULTI) {
1303 if ((result = GETARG(CHAR_T *)) == NULL)
1304 result = STRCONST("(null)");
1305 } else {
1306 MCHAR_T *mc;
1308 if (convbuf != NULL)
1309 free(convbuf);
1310 if ((mc = GETARG(MCHAR_T *)) == NULL)
1311 result = STRCONST("(null)");
1312 else {
1313 convbuf = SCONV(mc, prec);
1314 if (convbuf == NULL) {
1315 fp->_flags |= __SERR;
1316 goto error;
1318 result = convbuf;
1322 if (prec >= 0) {
1324 * can't use STRLEN; can only look for the
1325 * NUL in the first `prec' characters, and
1326 * STRLEN() will go further.
1328 CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
1330 if (p != NULL) {
1331 size = p - result;
1332 if (size > prec)
1333 size = prec;
1334 } else
1335 size = prec;
1336 } else
1337 size = STRLEN(result);
1338 sign = '\0';
1339 break;
1340 case 'U':
1341 flags |= LONGINT;
1342 /*FALLTHROUGH*/
1343 case 'u':
1344 if (flags & INTMAX_SIZE)
1345 ujval = UJARG();
1346 else
1347 ulval = UARG();
1348 base = 10;
1349 goto nosign;
1350 case 'X':
1351 xdigs = xdigs_upper;
1352 goto hex;
1353 case 'x':
1354 xdigs = xdigs_lower;
1355 hex:
1356 if (flags & INTMAX_SIZE)
1357 ujval = UJARG();
1358 else
1359 ulval = UARG();
1360 base = 16;
1361 /* leading 0x/X only if non-zero */
1362 if (flags & ALT &&
1363 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1364 ox[1] = ch;
1366 flags &= ~GROUPING;
1367 /* unsigned conversions */
1368 nosign: sign = '\0';
1370 * ``... diouXx conversions ... if a precision is
1371 * specified, the 0 flag will be ignored.''
1372 * -- ANSI X3J11
1374 number: if ((dprec = prec) >= 0)
1375 flags &= ~ZEROPAD;
1378 * ``The result of converting a zero value with an
1379 * explicit precision of zero is no characters.''
1380 * -- ANSI X3J11
1382 * ``The C Standard is clear enough as is. The call
1383 * printf("%#.0o", 0) should print 0.''
1384 * -- Defect Report #151
1386 result = cp = buf + BUF;
1387 if (flags & INTMAX_SIZE) {
1388 if (ujval != 0 || prec != 0 ||
1389 (flags & ALT && base == 8))
1390 result = __ujtoa(ujval, cp, base,
1391 flags & ALT, xdigs,
1392 flags & GROUPING, thousands_sep,
1393 grouping);
1394 } else {
1395 if (ulval != 0 || prec != 0 ||
1396 (flags & ALT && base == 8))
1397 result = __ultoa(ulval, cp, base,
1398 flags & ALT, xdigs,
1399 flags & GROUPING, thousands_sep,
1400 grouping);
1402 size = buf + BUF - result;
1403 if (size > BUF) /* should never happen */
1404 abort();
1405 break;
1406 default: /* "%?" prints ?, unless ? is NUL */
1407 if (ch == '\0')
1408 goto done;
1409 /* pretend it was %c with argument ch */
1410 *buf = ch;
1411 result = buf;
1412 size = 1;
1413 sign = '\0';
1414 break;
1418 * All reasonable formats wind up here. At this point, `result'
1419 * points to a string which (if not flags&LADJUST) should be
1420 * padded out to `width' places. If flags&ZEROPAD, it should
1421 * first be prefixed by any sign or other prefix; otherwise,
1422 * it should be blank padded before the prefix is emitted.
1423 * After any left-hand padding and prefixing, emit zeroes
1424 * required by a decimal [diouxX] precision, then print the
1425 * string proper, then emit zeroes required by any leftover
1426 * floating precision; finally, if LADJUST, pad with blanks.
1428 * Compute actual size, so we know how much to pad.
1429 * size excludes decimal prec; realsz includes it.
1431 realsz = dprec > size ? dprec : size;
1432 if (sign)
1433 realsz++;
1434 if (ox[1])
1435 realsz += 2;
1437 prsize = width > realsz ? width : realsz;
1438 if ((unsigned)ret + prsize > INT_MAX) {
1439 ret = END_OF_FILE;
1440 goto error;
1443 /* right-adjusting blank padding */
1444 if ((flags & (LADJUST|ZEROPAD)) == 0)
1445 PAD(width - realsz, blanks);
1447 /* prefix */
1448 if (sign)
1449 PRINT(&sign, 1);
1451 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1452 ox[0] = '0';
1453 PRINT(ox, 2);
1456 /* right-adjusting zero padding */
1457 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1458 PAD(width - realsz, zeroes);
1460 /* leading zeroes from decimal precision */
1461 PAD(dprec - size, zeroes);
1463 /* the string or number proper */
1464 #ifndef NO_FLOATING_POINT
1465 if ((flags & FPT) == 0) {
1466 PRINT(result, size);
1467 } else { /* glue together f_p fragments */
1468 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1469 if (expt <= 0) {
1470 PRINT(zeroes, 1);
1471 if (prec || flags & ALT)
1472 PRINT(decimal_point, 1);
1473 PAD(-expt, zeroes);
1474 /* already handled initial 0's */
1475 prec += expt;
1476 } else {
1477 PRINTANDPAD(result, convbuf + ndig,
1478 lead, zeroes);
1479 result += lead;
1480 if (grouping) {
1481 while (nseps>0 || nrepeats>0) {
1482 if (nrepeats > 0)
1483 nrepeats--;
1484 else {
1485 grouping--;
1486 nseps--;
1488 PRINT(&thousands_sep,
1490 PRINTANDPAD(result,
1491 convbuf + ndig,
1492 *grouping, zeroes);
1493 result += *grouping;
1495 if (result > convbuf + ndig)
1496 result = convbuf + ndig;
1498 if (prec || flags & ALT) {
1499 buf[0] = *decimal_point;
1500 PRINT(buf, 1);
1503 PRINTANDPAD(result, convbuf + ndig, prec,
1504 zeroes);
1505 } else { /* %[eE] or sufficiently long %[gG] */
1506 if (prec > 1 || flags & ALT) {
1507 buf[0] = *result++;
1508 buf[1] = *decimal_point;
1509 PRINT(buf, 2);
1510 PRINT(result, ndig-1);
1511 PAD(prec - ndig, zeroes);
1512 } else /* XeYYY */
1513 PRINT(result, 1);
1514 PRINT(expstr, expsize);
1517 #else
1518 PRINT(result, size);
1519 #endif
1520 /* left-adjusting padding (always blank) */
1521 if (flags & LADJUST)
1522 PAD(width - realsz, blanks);
1524 /* finally, adjust ret */
1525 ret += prsize;
1526 FLUSH();
1528 done:
1529 FLUSH();
1530 error:
1531 va_end(orgap);
1532 if (convbuf != NULL)
1533 free(convbuf);
1534 if (__sferror(fp))
1535 ret = END_OF_FILE;
1536 if ((argtable != NULL) && (argtable != statargtable))
1537 free (argtable);
1538 return (ret);
1539 /* NOTREACHED */
1540 oomem:
1541 errno = ENOMEM;
1542 ret = END_OF_FILE;
1543 goto error;
1547 * Find all arguments when a positional parameter is encountered. Returns a
1548 * table, indexed by argument number, of pointers to each arguments. The
1549 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1550 * It will be replaces with a malloc-ed one if it overflows.
1552 static int
1553 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
1555 CHAR_T *fmt; /* format string */
1556 int ch; /* character from fmt */
1557 int n, n2; /* handy integer (short term usage) */
1558 CHAR_T *cp; /* handy char pointer (short term usage) */
1559 int flags; /* flags as above */
1560 enum typeid *typetable; /* table of types */
1561 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1562 int tablesize; /* current size of type table */
1563 int tablemax; /* largest used index in table */
1564 int nextarg; /* 1-based argument index */
1567 * Add an argument type to the table, expanding if necessary.
1569 #define ADDTYPE(type) \
1570 do { \
1571 if (nextarg >= tablesize) \
1572 if (__grow_type_table(nextarg, &typetable, \
1573 &tablesize) == -1) \
1574 return -1; \
1575 if (nextarg > tablemax) \
1576 tablemax = nextarg; \
1577 typetable[nextarg++] = type; \
1578 } while (/*CONSTCOND*/0)
1580 #define ADDSARG() \
1581 do { \
1582 if (flags & INTMAXT) \
1583 ADDTYPE(T_INTMAXT); \
1584 else if (flags & SIZET) \
1585 ADDTYPE(T_SSIZET); \
1586 else if (flags & PTRDIFFT) \
1587 ADDTYPE(T_PTRDIFFT); \
1588 else if (flags & LLONGINT) \
1589 ADDTYPE(T_LLONG); \
1590 else if (flags & LONGINT) \
1591 ADDTYPE(T_LONG); \
1592 else \
1593 ADDTYPE(T_INT); \
1594 } while (/*CONSTCOND*/0)
1596 #define ADDUARG() \
1597 do { \
1598 if (flags & INTMAXT) \
1599 ADDTYPE(T_UINTMAXT); \
1600 else if (flags & SIZET) \
1601 ADDTYPE(T_SIZET); \
1602 else if (flags & PTRDIFFT) \
1603 ADDTYPE(T_PTRDIFFT); \
1604 else if (flags & LLONGINT) \
1605 ADDTYPE(T_U_LLONG); \
1606 else if (flags & LONGINT) \
1607 ADDTYPE(T_U_LONG); \
1608 else \
1609 ADDTYPE(T_U_INT); \
1610 } while (/*CONSTCOND*/0)
1612 * Add * arguments to the type array.
1614 #define ADDASTER() \
1615 n2 = 0; \
1616 cp = fmt; \
1617 while (is_digit(*cp)) { \
1618 n2 = 10 * n2 + to_digit(*cp); \
1619 cp++; \
1621 if (*cp == '$') { \
1622 int hold = nextarg; \
1623 nextarg = n2; \
1624 ADDTYPE(T_INT); \
1625 nextarg = hold; \
1626 fmt = ++cp; \
1627 } else { \
1628 ADDTYPE(T_INT); \
1630 fmt = (CHAR_T *)__UNCONST(fmt0);
1631 typetable = stattypetable;
1632 tablesize = STATIC_ARG_TBL_SIZE;
1633 tablemax = 0;
1634 nextarg = 1;
1635 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1636 typetable[n] = T_UNUSED;
1639 * Scan the format for conversions (`%' character).
1641 for (;;) {
1642 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1643 /* void */;
1644 if (ch == '\0')
1645 goto done;
1646 fmt++; /* skip over '%' */
1648 flags = 0;
1650 rflag: ch = *fmt++;
1651 reswitch: switch (ch) {
1652 case ' ':
1653 case '#':
1654 goto rflag;
1655 case '*':
1656 ADDASTER ();
1657 goto rflag;
1658 case '-':
1659 case '+':
1660 case '\'':
1661 goto rflag;
1662 case '.':
1663 if ((ch = *fmt++) == '*') {
1664 ADDASTER ();
1665 goto rflag;
1667 while (is_digit(ch)) {
1668 ch = *fmt++;
1670 goto reswitch;
1671 case '0':
1672 goto rflag;
1673 case '1': case '2': case '3': case '4':
1674 case '5': case '6': case '7': case '8': case '9':
1675 n = 0;
1676 do {
1677 n = 10 * n + to_digit(ch);
1678 ch = *fmt++;
1679 } while (is_digit(ch));
1680 if (ch == '$') {
1681 nextarg = n;
1682 goto rflag;
1684 goto reswitch;
1685 #ifndef NO_FLOATING_POINT
1686 case 'L':
1687 flags |= LONGDBL;
1688 goto rflag;
1689 #endif
1690 case 'h':
1691 if (flags & SHORTINT) {
1692 flags &= ~SHORTINT;
1693 flags |= CHARINT;
1694 } else
1695 flags |= SHORTINT;
1696 goto rflag;
1697 case 'j':
1698 flags |= INTMAXT;
1699 goto rflag;
1700 case 'l':
1701 if (flags & LONGINT) {
1702 flags &= ~LONGINT;
1703 flags |= LLONGINT;
1704 } else
1705 flags |= LONGINT;
1706 goto rflag;
1707 case 'q':
1708 flags |= LLONGINT; /* not necessarily */
1709 goto rflag;
1710 case 't':
1711 flags |= PTRDIFFT;
1712 goto rflag;
1713 case 'z':
1714 flags |= SIZET;
1715 goto rflag;
1716 case 'C':
1717 flags |= LONGINT;
1718 /*FALLTHROUGH*/
1719 case 'c':
1720 if (flags & LONGINT)
1721 ADDTYPE(T_WINT);
1722 else
1723 ADDTYPE(T_INT);
1724 break;
1725 case 'D':
1726 flags |= LONGINT;
1727 /*FALLTHROUGH*/
1728 case 'd':
1729 case 'i':
1730 ADDSARG();
1731 break;
1732 #ifndef NO_FLOATING_POINT
1733 case 'a':
1734 case 'A':
1735 case 'e':
1736 case 'E':
1737 case 'f':
1738 case 'g':
1739 case 'G':
1740 if (flags & LONGDBL)
1741 ADDTYPE(T_LONG_DOUBLE);
1742 else
1743 ADDTYPE(T_DOUBLE);
1744 break;
1745 #endif /* !NO_FLOATING_POINT */
1746 case 'n':
1747 if (flags & INTMAXT)
1748 ADDTYPE(TP_INTMAXT);
1749 else if (flags & PTRDIFFT)
1750 ADDTYPE(TP_PTRDIFFT);
1751 else if (flags & SIZET)
1752 ADDTYPE(TP_SIZET);
1753 else if (flags & LLONGINT)
1754 ADDTYPE(TP_LLONG);
1755 else if (flags & LONGINT)
1756 ADDTYPE(TP_LONG);
1757 else if (flags & SHORTINT)
1758 ADDTYPE(TP_SHORT);
1759 else if (flags & CHARINT)
1760 ADDTYPE(TP_SCHAR);
1761 else
1762 ADDTYPE(TP_INT);
1763 continue; /* no output */
1764 case 'O':
1765 flags |= LONGINT;
1766 /*FALLTHROUGH*/
1767 case 'o':
1768 ADDUARG();
1769 break;
1770 case 'p':
1771 ADDTYPE(TP_VOID);
1772 break;
1773 case 'S':
1774 flags |= LONGINT;
1775 /*FALLTHROUGH*/
1776 case 's':
1777 if (flags & LONGINT)
1778 ADDTYPE(TP_WCHAR);
1779 else
1780 ADDTYPE(TP_CHAR);
1781 break;
1782 case 'U':
1783 flags |= LONGINT;
1784 /*FALLTHROUGH*/
1785 case 'u':
1786 case 'X':
1787 case 'x':
1788 ADDUARG();
1789 break;
1790 default: /* "%?" prints ?, unless ? is NUL */
1791 if (ch == '\0')
1792 goto done;
1793 break;
1796 done:
1798 * Build the argument table.
1800 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1801 *argtable = (union arg *)
1802 malloc (sizeof (union arg) * (tablemax + 1));
1803 if (*argtable == NULL)
1804 return -1;
1807 (*argtable) [0].intarg = 0;
1808 for (n = 1; n <= tablemax; n++) {
1809 switch (typetable [n]) {
1810 case T_UNUSED: /* whoops! */
1811 (*argtable) [n].intarg = va_arg (ap, int);
1812 break;
1813 case TP_SCHAR:
1814 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1815 break;
1816 case TP_SHORT:
1817 (*argtable) [n].pshortarg = va_arg (ap, short *);
1818 break;
1819 case T_INT:
1820 (*argtable) [n].intarg = va_arg (ap, int);
1821 break;
1822 case T_U_INT:
1823 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1824 break;
1825 case TP_INT:
1826 (*argtable) [n].pintarg = va_arg (ap, int *);
1827 break;
1828 case T_LONG:
1829 (*argtable) [n].longarg = va_arg (ap, long);
1830 break;
1831 case T_U_LONG:
1832 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1833 break;
1834 case TP_LONG:
1835 (*argtable) [n].plongarg = va_arg (ap, long *);
1836 break;
1837 case T_LLONG:
1838 (*argtable) [n].longlongarg = va_arg (ap, long long);
1839 break;
1840 case T_U_LLONG:
1841 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1842 break;
1843 case TP_LLONG:
1844 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1845 break;
1846 case T_PTRDIFFT:
1847 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1848 break;
1849 case TP_PTRDIFFT:
1850 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1851 break;
1852 case T_SSIZET:
1853 (*argtable) [n].ssizearg = va_arg (ap, ssize_t);
1854 break;
1855 case T_SIZET:
1856 (*argtable) [n].sizearg = va_arg (ap, size_t);
1857 break;
1858 case TP_SIZET:
1859 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1860 break;
1861 case T_INTMAXT:
1862 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1863 break;
1864 case T_UINTMAXT:
1865 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1866 break;
1867 case TP_INTMAXT:
1868 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1869 break;
1870 case T_DOUBLE:
1871 #ifndef NO_FLOATING_POINT
1872 (*argtable) [n].doublearg = va_arg (ap, double);
1873 #endif
1874 break;
1875 case T_LONG_DOUBLE:
1876 #ifndef NO_FLOATING_POINT
1877 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1878 #endif
1879 break;
1880 case TP_CHAR:
1881 (*argtable) [n].pchararg = va_arg (ap, char *);
1882 break;
1883 case TP_VOID:
1884 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1885 break;
1886 case T_WINT:
1887 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1888 break;
1889 case TP_WCHAR:
1890 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1891 break;
1895 if ((typetable != NULL) && (typetable != stattypetable))
1896 free (typetable);
1897 return 0;
1901 * Increase the size of the type table.
1903 static int
1904 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1906 enum typeid *const oldtable = *typetable;
1907 const int oldsize = *tablesize;
1908 enum typeid *newtable;
1909 int n, newsize = oldsize * 2;
1911 if (newsize < nextarg + 1)
1912 newsize = nextarg + 1;
1913 if (oldsize == STATIC_ARG_TBL_SIZE) {
1914 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1915 return -1;
1916 memcpy(newtable, oldtable, oldsize * sizeof(enum typeid));
1917 } else {
1918 newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1919 if (newtable == NULL) {
1920 free(oldtable);
1921 return -1;
1924 for (n = oldsize; n < newsize; n++)
1925 newtable[n] = T_UNUSED;
1927 *typetable = newtable;
1928 *tablesize = newsize;
1929 return 0;
1933 #ifndef NO_FLOATING_POINT
1934 #ifndef WIDE_DOUBLE
1935 static char *
1936 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1937 int *length)
1939 int mode, dsgn;
1940 char *digits, *bp, *rve;
1942 _DIAGASSERT(decpt != NULL);
1943 _DIAGASSERT(length != NULL);
1944 _DIAGASSERT(sign != NULL);
1946 if (ch == 'f') {
1947 mode = 3; /* ndigits after the decimal point */
1948 } else {
1949 /* To obtain ndigits after the decimal point for the 'e'
1950 * and 'E' formats, round to ndigits + 1 significant
1951 * figures.
1953 if (ch == 'e' || ch == 'E') {
1954 ndigits++;
1956 mode = 2; /* ndigits significant digits */
1959 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1960 if (digits == NULL)
1961 return NULL;
1962 if (dsgn) {
1963 value = -value;
1964 *sign = '-';
1965 } else
1966 *sign = '\000';
1967 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
1968 bp = digits + ndigits;
1969 if (ch == 'f') {
1970 if (*digits == '0' && value)
1971 *decpt = -ndigits + 1;
1972 bp += *decpt;
1974 if (value == 0) /* kludge for __dtoa irregularity */
1975 rve = bp;
1976 while (rve < bp)
1977 *rve++ = '0';
1979 *length = rve - digits;
1980 return digits;
1982 #endif
1984 static int
1985 exponent(CHAR_T *p0, int expo, int fmtch)
1987 CHAR_T *p, *t;
1988 CHAR_T expbuf[MAXEXPDIG];
1990 p = p0;
1991 *p++ = fmtch;
1992 if (expo < 0) {
1993 expo = -expo;
1994 *p++ = '-';
1996 else
1997 *p++ = '+';
1998 t = expbuf + MAXEXPDIG;
1999 if (expo > 9) {
2000 do {
2001 *--t = to_char(expo % 10);
2002 } while ((expo /= 10) > 9);
2003 *--t = to_char(expo);
2004 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
2006 else {
2008 * Exponents for decimal floating point conversions
2009 * (%[eEgG]) must be at least two characters long,
2010 * whereas exponents for hexadecimal conversions can
2011 * be only one character long.
2013 if (fmtch == 'e' || fmtch == 'E')
2014 *p++ = '0';
2015 *p++ = to_char(expo);
2017 return (p - p0);
2019 #endif /* !NO_FLOATING_POINT */