Sync usage with man page.
[netbsd-mini2440.git] / lib / libc / stdio / vfwprintf.c
blob2abb8fa72786407959d1bbaf0bac2f76ef36024e
1 /* $NetBSD: vfwprintf.c,v 1.16 2009/08/05 20:46:01 dsl 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.16 2009/08/05 20:46:01 dsl 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);
167 /* copy the important variables */
168 fake._flags = fp->_flags & ~__SNBF;
169 fake._file = fp->_file;
170 fake._cookie = fp->_cookie;
171 fake._write = fp->_write;
173 /* set up the buffer */
174 fake._bf._base = fake._p = buf;
175 fake._bf._size = fake._w = sizeof(buf);
176 fake._lbfsize = 0; /* not actually used, but Just In Case */
178 /* do the work, then copy any error status */
179 ret = WDECL(__vf,printf_unlocked)(&fake, fmt, ap);
180 if (ret >= 0 && fflush(&fake))
181 ret = END_OF_FILE;
182 if (fake._flags & __SERR)
183 fp->_flags |= __SERR;
184 return (ret);
187 #ifndef NARROW
189 * Like __fputwc, but handles fake string (__SSTR) files properly.
190 * File must already be locked.
192 static wint_t
193 __xfputwc(wchar_t wc, FILE *fp)
195 static const mbstate_t initial;
196 mbstate_t mbs;
197 char buf[MB_LEN_MAX];
198 struct __suio uio;
199 struct __siov iov;
200 size_t len;
202 if ((fp->_flags & __SSTR) == 0)
203 return (__fputwc_unlock(wc, fp));
205 mbs = initial;
206 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
207 fp->_flags |= __SERR;
208 return (END_OF_FILE);
210 uio.uio_iov = &iov;
211 uio.uio_resid = len;
212 uio.uio_iovcnt = 1;
213 iov.iov_base = buf;
214 iov.iov_len = len;
215 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE);
217 #else
219 * Flush out all the vectors defined by the given uio,
220 * then reset it so that it can be reused.
222 static int
223 __sprint(FILE *fp, struct __suio *uio)
225 int err;
227 _DIAGASSERT(fp != NULL);
228 _DIAGASSERT(uio != NULL);
230 if (uio->uio_resid == 0) {
231 uio->uio_iovcnt = 0;
232 return (0);
234 err = __sfvwrite(fp, uio);
235 uio->uio_resid = 0;
236 uio->uio_iovcnt = 0;
237 return (err);
239 #endif
242 * Macros for converting digits to letters and vice versa
244 #define to_digit(c) ((c) - '0')
245 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
246 #define to_char(n) (CHAR_T)((n) + '0')
249 * Convert an unsigned long to ASCII for printf purposes, returning
250 * a pointer to the first character of the string representation.
251 * Octal numbers can be forced to have a leading zero; hex numbers
252 * use the given digits.
254 static CHAR_T *
255 __ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs,
256 int needgrp, char thousep, const char *grp)
258 CHAR_T *cp = endp;
259 long sval;
260 int ndig;
263 * Handle the three cases separately, in the hope of getting
264 * better/faster code.
266 switch (base) {
267 case 10:
268 if (val < 10) { /* many numbers are 1 digit */
269 *--cp = to_char(val);
270 return (cp);
272 ndig = 0;
274 * On many machines, unsigned arithmetic is harder than
275 * signed arithmetic, so we do at most one unsigned mod and
276 * divide; this is sufficient to reduce the range of
277 * the incoming value to where signed arithmetic works.
279 if (val > LONG_MAX) {
280 *--cp = to_char(val % 10);
281 ndig++;
282 sval = val / 10;
283 } else
284 sval = val;
285 do {
286 *--cp = to_char(sval % 10);
287 ndig++;
289 * If (*grp == CHAR_MAX) then no more grouping
290 * should be performed.
292 if (needgrp && ndig == *grp && *grp != CHAR_MAX
293 && sval > 9) {
294 *--cp = thousep;
295 ndig = 0;
297 * If (*(grp+1) == '\0') then we have to
298 * use *grp character (last grouping rule)
299 * for all next cases
301 if (*(grp+1) != '\0')
302 grp++;
304 sval /= 10;
305 } while (sval != 0);
306 break;
308 case 8:
309 do {
310 *--cp = to_char(val & 7);
311 val >>= 3;
312 } while (val);
313 if (octzero && *cp != '0')
314 *--cp = '0';
315 break;
317 case 16:
318 do {
319 *--cp = xdigs[(size_t)val & 15];
320 val >>= 4;
321 } while (val);
322 break;
324 default: /* oops */
325 abort();
327 return (cp);
330 /* Identical to __ultoa, but for intmax_t. */
331 static CHAR_T *
332 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero,
333 const char *xdigs, int needgrp, char thousep, const char *grp)
335 CHAR_T *cp = endp;
336 intmax_t sval;
337 int ndig;
339 /* quick test for small values; __ultoa is typically much faster */
340 /* (perhaps instead we should run until small, then call __ultoa?) */
341 if (val <= ULONG_MAX)
342 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
343 needgrp, thousep, grp));
344 switch (base) {
345 case 10:
346 if (val < 10) {
347 *--cp = to_char(val % 10);
348 return (cp);
350 ndig = 0;
351 if (val > INTMAX_MAX) {
352 *--cp = to_char(val % 10);
353 ndig++;
354 sval = val / 10;
355 } else
356 sval = val;
357 do {
358 *--cp = to_char(sval % 10);
359 ndig++;
361 * If (*grp == CHAR_MAX) then no more grouping
362 * should be performed.
364 if (needgrp && *grp != CHAR_MAX && ndig == *grp
365 && sval > 9) {
366 *--cp = thousep;
367 ndig = 0;
369 * If (*(grp+1) == '\0') then we have to
370 * use *grp character (last grouping rule)
371 * for all next cases
373 if (*(grp+1) != '\0')
374 grp++;
376 sval /= 10;
377 } while (sval != 0);
378 break;
380 case 8:
381 do {
382 *--cp = to_char(val & 7);
383 val >>= 3;
384 } while (val);
385 if (octzero && *cp != '0')
386 *--cp = '0';
387 break;
389 case 16:
390 do {
391 *--cp = xdigs[(size_t)val & 15];
392 val >>= 4;
393 } while (val);
394 break;
396 default:
397 abort();
399 return (cp);
402 #ifndef NARROW
404 * Convert a multibyte character string argument for the %s format to a wide
405 * string representation. ``prec'' specifies the maximum number of bytes
406 * to output. If ``prec'' is greater than or equal to zero, we can't assume
407 * that the multibyte char. string ends in a null character.
409 static wchar_t *
410 __mbsconv(char *mbsarg, int prec)
412 static const mbstate_t initial;
413 mbstate_t mbs;
414 wchar_t *convbuf, *wcp;
415 const char *p;
416 size_t insize, nchars, nconv;
418 if (mbsarg == NULL)
419 return (NULL);
422 * Supplied argument is a multibyte string; convert it to wide
423 * characters first.
425 if (prec >= 0) {
427 * String is not guaranteed to be NUL-terminated. Find the
428 * number of characters to print.
430 p = mbsarg;
431 insize = nchars = nconv = 0;
432 mbs = initial;
433 while (nchars != (size_t)prec) {
434 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
435 if (nconv == 0 || nconv == (size_t)-1 ||
436 nconv == (size_t)-2)
437 break;
438 p += nconv;
439 nchars++;
440 insize += nconv;
442 if (nconv == (size_t)-1 || nconv == (size_t)-2)
443 return (NULL);
444 } else
445 insize = strlen(mbsarg);
448 * Allocate buffer for the result and perform the conversion,
449 * converting at most `size' bytes of the input multibyte string to
450 * wide characters for printing.
452 convbuf = malloc((insize + 1) * sizeof(*convbuf));
453 if (convbuf == NULL)
454 return (NULL);
455 wcp = convbuf;
456 p = mbsarg;
457 mbs = initial;
458 nconv = 0;
459 while (insize != 0) {
460 nconv = mbrtowc(wcp, p, insize, &mbs);
461 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
462 break;
463 wcp++;
464 p += nconv;
465 insize -= nconv;
467 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
468 free(convbuf);
469 return (NULL);
471 *wcp = L'\0';
473 return (convbuf);
475 #else
477 * Convert a wide character string argument for the %ls format to a multibyte
478 * string representation. If not -1, prec specifies the maximum number of
479 * bytes to output, and also means that we can't assume that the wide char.
480 * string ends is null-terminated.
482 static char *
483 __wcsconv(wchar_t *wcsarg, int prec)
485 static const mbstate_t initial;
486 mbstate_t mbs;
487 char buf[MB_LEN_MAX];
488 wchar_t *p;
489 char *convbuf;
490 size_t clen, nbytes;
492 /* Allocate space for the maximum number of bytes we could output. */
493 if (prec < 0) {
494 p = wcsarg;
495 mbs = initial;
496 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
497 if (nbytes == (size_t)-1)
498 return (NULL);
499 } else {
501 * Optimisation: if the output precision is small enough,
502 * just allocate enough memory for the maximum instead of
503 * scanning the string.
505 if (prec < 128)
506 nbytes = prec;
507 else {
508 nbytes = 0;
509 p = wcsarg;
510 mbs = initial;
511 for (;;) {
512 clen = wcrtomb(buf, *p++, &mbs);
513 if (clen == 0 || clen == (size_t)-1 ||
514 nbytes + clen > (size_t)prec)
515 break;
516 nbytes += clen;
520 if ((convbuf = malloc(nbytes + 1)) == NULL)
521 return (NULL);
523 /* Fill the output buffer. */
524 p = wcsarg;
525 mbs = initial;
526 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
527 nbytes, &mbs)) == (size_t)-1) {
528 free(convbuf);
529 return (NULL);
531 convbuf[nbytes] = '\0';
532 return (convbuf);
534 #endif
537 * MT-safe version
540 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap)
542 int ret;
544 FLOCKFILE(fp);
545 ret = WDECL(__vf,printf_unlocked)(fp, fmt0, ap);
546 FUNLOCKFILE(fp);
547 return (ret);
550 #ifndef NO_FLOATING_POINT
552 #include <float.h>
553 #include <math.h>
554 #include "floatio.h"
556 #define DEFPREC 6
558 static int exponent(CHAR_T *, int, int);
559 #ifndef WIDE_DOUBLE
560 static char *cvt(double, int, int, char *, int *, int, int *);
561 #endif
563 #endif /* !NO_FLOATING_POINT */
566 * The size of the buffer we use as scratch space for integer
567 * conversions, among other things. Technically, we would need the
568 * most space for base 10 conversions with thousands' grouping
569 * characters between each pair of digits. 100 bytes is a
570 * conservative overestimate even for a 128-bit uintmax_t.
572 #define BUF 100
574 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
577 * Flags used during conversion.
579 #define ALT 0x001 /* alternate form */
580 #define LADJUST 0x004 /* left adjustment */
581 #define LONGDBL 0x008 /* long double */
582 #define LONGINT 0x010 /* long integer */
583 #define LLONGINT 0x020 /* long long integer */
584 #define SHORTINT 0x040 /* short integer */
585 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
586 #define FPT 0x100 /* Floating point number */
587 #define GROUPING 0x200 /* use grouping ("'" flag) */
588 /* C99 additional size modifiers: */
589 #define SIZET 0x400 /* size_t */
590 #define PTRDIFFT 0x800 /* ptrdiff_t */
591 #define INTMAXT 0x1000 /* intmax_t */
592 #define CHARINT 0x2000 /* print char using int format */
595 * Non-MT-safe version
598 WDECL(__vf,printf_unlocked)(FILE *fp, const CHAR_T *fmt0, va_list ap)
600 CHAR_T *fmt; /* format string */
601 int ch; /* character from fmt */
602 int n, n2; /* handy integer (short term usage) */
603 CHAR_T *cp; /* handy char pointer (short term usage) */
604 int flags; /* flags as above */
605 int ret; /* return value accumulator */
606 int width; /* width from format (%8d), or 0 */
607 int prec; /* precision from format; <0 for N/A */
608 CHAR_T sign; /* sign prefix (' ', '+', '-', or \0) */
609 char thousands_sep; /* locale specific thousands separator */
610 const char *grouping; /* locale specific numeric grouping rules */
611 #ifndef NO_FLOATING_POINT
613 * We can decompose the printed representation of floating
614 * point numbers into several parts, some of which may be empty:
616 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
617 * A B ---C--- D E F
619 * A: 'sign' holds this value if present; '\0' otherwise
620 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
621 * C: cp points to the string MMMNNN. Leading and trailing
622 * zeros are not in the string and must be added.
623 * D: expchar holds this character; '\0' if no exponent, e.g. %f
624 * F: at least two digits for decimal, at least one digit for hex
626 char *decimal_point; /* locale specific decimal point */
627 #ifdef WIDE_DOUBLE
628 int signflag; /* true if float is negative */
629 union { /* floating point arguments %[aAeEfFgG] */
630 double dbl;
631 long double ldbl;
632 } fparg;
633 char *dtoaend; /* pointer to end of converted digits */
634 #else
635 double _double; /* double precision arguments %[eEfgG] */
636 char softsign; /* temporary negative sign for floats */
637 #endif
638 char *dtoaresult; /* buffer allocated by dtoa */
639 int expt; /* integer value of exponent */
640 char expchar; /* exponent character: [eEpP\0] */
641 int expsize; /* character count for expstr */
642 int lead; /* sig figs before decimal or group sep */
643 int ndig; /* actual number of digits returned by dtoa */
644 CHAR_T expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
645 int nseps; /* number of group separators with ' */
646 int nrepeats; /* number of repeats of the last group */
647 #endif
648 u_long ulval; /* integer arguments %[diouxX] */
649 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
650 int base; /* base for [diouxX] conversion */
651 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
652 int realsz; /* field size expanded by dprec, sign, etc */
653 int size; /* size of converted field or string */
654 int prsize; /* max size of printed field */
655 const char *xdigs; /* digits for %[xX] conversion */
656 #ifdef NARROW
657 #define NIOV 8
658 struct __siov *iovp; /* for PRINT macro */
659 struct __suio uio; /* output information: summary */
660 struct __siov iov[NIOV];/* ... and individual io vectors */
661 #else
662 int n3;
663 #endif
664 CHAR_T buf[BUF]; /* buffer with space for digits of uintmax_t */
665 CHAR_T ox[2]; /* space for 0x hex-prefix */
666 union arg *argtable; /* args, built due to positional arg */
667 union arg statargtable [STATIC_ARG_TBL_SIZE];
668 int nextarg; /* 1-based argument index */
669 va_list orgap; /* original argument pointer */
670 CHAR_T *convbuf; /* multibyte to wide conversion result */
673 * Choose PADSIZE to trade efficiency vs. size. If larger printf
674 * fields occur frequently, increase PADSIZE and make the initialisers
675 * below longer.
677 #define PADSIZE 16 /* pad chunk size */
678 static CHAR_T blanks[PADSIZE] =
679 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
680 static CHAR_T zeroes[PADSIZE] =
681 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
683 static const char xdigs_lower[16] = "0123456789abcdef";
684 static const char xdigs_upper[16] = "0123456789ABCDEF";
687 * BEWARE, these `goto error' on error, PRINT uses `n2' and
688 * PAD uses `n'.
690 #ifndef NARROW
691 #define PRINT(ptr, len) do { \
692 for (n3 = 0; n3 < (len); n3++) \
693 __xfputwc((ptr)[n3], fp); \
694 } while (/*CONSTCOND*/0)
695 #define FLUSH()
696 #else
697 #define PRINT(ptr, len) do { \
698 iovp->iov_base = __UNCONST(ptr); \
699 iovp->iov_len = (len); \
700 uio.uio_resid += (len); \
701 iovp++; \
702 if (++uio.uio_iovcnt >= NIOV) { \
703 if (__sprint(fp, &uio)) \
704 goto error; \
705 iovp = iov; \
707 } while (/*CONSTCOND*/0)
708 #define FLUSH() do { \
709 if (uio.uio_resid && __sprint(fp, &uio)) \
710 goto error; \
711 uio.uio_iovcnt = 0; \
712 iovp = iov; \
713 } while (/*CONSTCOND*/0)
714 #endif /* NARROW */
716 #define PAD(howmany, with) do { \
717 if ((n = (howmany)) > 0) { \
718 while (n > PADSIZE) { \
719 PRINT(with, PADSIZE); \
720 n -= PADSIZE; \
722 PRINT(with, n); \
724 } while (/*CONSTCOND*/0)
725 #define PRINTANDPAD(p, ep, len, with) do { \
726 n2 = (ep) - (p); \
727 if (n2 > (len)) \
728 n2 = (len); \
729 if (n2 > 0) \
730 PRINT((p), n2); \
731 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
732 } while(/*CONSTCOND*/0)
735 * Get the argument indexed by nextarg. If the argument table is
736 * built, use it to get the argument. If its not, get the next
737 * argument (and arguments must be gotten sequentially).
739 #define GETARG(type) \
740 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
741 (nextarg++, va_arg(ap, type)))
744 * To extend shorts properly, we need both signed and unsigned
745 * argument extraction methods.
747 #define SARG() \
748 (flags&LONGINT ? GETARG(long) : \
749 flags&SHORTINT ? (long)(short)GETARG(int) : \
750 flags&CHARINT ? (long)(signed char)GETARG(int) : \
751 (long)GETARG(int))
752 #define UARG() \
753 (flags&LONGINT ? GETARG(u_long) : \
754 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
755 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
756 (u_long)GETARG(u_int))
757 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
758 #define SJARG() \
759 (flags&INTMAXT ? GETARG(intmax_t) : \
760 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
761 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
762 (intmax_t)GETARG(long long))
763 #define UJARG() \
764 (flags&INTMAXT ? GETARG(uintmax_t) : \
765 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
766 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
767 (uintmax_t)GETARG(unsigned long long))
770 * Get * arguments, including the form *nn$. Preserve the nextarg
771 * that the argument can be gotten once the type is determined.
773 #define GETASTER(val) \
774 n2 = 0; \
775 cp = fmt; \
776 while (is_digit(*cp)) { \
777 n2 = 10 * n2 + to_digit(*cp); \
778 cp++; \
780 if (*cp == '$') { \
781 int hold = nextarg; \
782 if (argtable == NULL) { \
783 argtable = statargtable; \
784 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
785 goto oomem; \
787 nextarg = n2; \
788 val = GETARG (int); \
789 nextarg = hold; \
790 fmt = ++cp; \
791 } else { \
792 val = GETARG (int); \
795 _DIAGASSERT(fp != NULL);
796 _DIAGASSERT(fmt0 != NULL);
798 _SET_ORIENTATION(fp, -1);
800 ndig = -1; /* XXX gcc */
802 thousands_sep = '\0';
803 grouping = NULL;
804 #ifndef NO_FLOATING_POINT
805 decimal_point = localeconv()->decimal_point;
806 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
807 #endif
808 convbuf = NULL;
809 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
810 if (cantwrite(fp)) {
811 errno = EBADF;
812 return (END_OF_FILE);
815 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
816 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
817 __sfileno(fp) != -1)
818 return (__sbprintf(fp, fmt0, ap));
820 fmt = (CHAR_T *)__UNCONST(fmt0);
821 argtable = NULL;
822 nextarg = 1;
823 va_copy(orgap, ap);
824 #ifdef NARROW
825 uio.uio_iov = iovp = iov;
826 uio.uio_resid = 0;
827 uio.uio_iovcnt = 0;
828 #endif
829 ret = 0;
832 * Scan the format for conversions (`%' character).
834 for (;;) {
835 const CHAR_T *result;
837 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
838 continue;
839 if ((n = fmt - cp) != 0) {
840 if ((unsigned)ret + n > INT_MAX) {
841 ret = END_OF_FILE;
842 goto error;
844 PRINT(cp, n);
845 ret += n;
847 if (ch == '\0')
848 goto done;
849 fmt++; /* skip over '%' */
851 flags = 0;
852 dprec = 0;
853 width = 0;
854 prec = -1;
855 sign = '\0';
856 ox[1] = '\0';
857 expchar = '\0';
858 lead = 0;
859 nseps = nrepeats = 0;
860 ulval = 0;
861 ujval = 0;
862 xdigs = NULL;
864 rflag: ch = *fmt++;
865 reswitch: switch (ch) {
866 case ' ':
868 * ``If the space and + flags both appear, the space
869 * flag will be ignored.''
870 * -- ANSI X3J11
872 if (!sign)
873 sign = ' ';
874 goto rflag;
875 case '#':
876 flags |= ALT;
877 goto rflag;
878 case '*':
880 * ``A negative field width argument is taken as a
881 * - flag followed by a positive field width.''
882 * -- ANSI X3J11
883 * They don't exclude field widths read from args.
885 GETASTER (width);
886 if (width >= 0)
887 goto rflag;
888 width = -width;
889 /* FALLTHROUGH */
890 case '-':
891 flags |= LADJUST;
892 goto rflag;
893 case '+':
894 sign = '+';
895 goto rflag;
896 case '\'':
897 flags |= GROUPING;
898 thousands_sep = *(localeconv()->thousands_sep);
899 grouping = localeconv()->grouping;
900 /* If the locale doesn't define the above, use sane
901 * defaults - otherwise silly things happen! */
902 if (thousands_sep == 0)
903 thousands_sep = ',';
904 if (!grouping || !*grouping)
905 grouping = "\3";
906 goto rflag;
907 case '.':
908 if ((ch = *fmt++) == '*') {
909 GETASTER (prec);
910 goto rflag;
912 prec = 0;
913 while (is_digit(ch)) {
914 prec = 10 * prec + to_digit(ch);
915 ch = *fmt++;
917 goto reswitch;
918 case '0':
920 * ``Note that 0 is taken as a flag, not as the
921 * beginning of a field width.''
922 * -- ANSI X3J11
924 flags |= ZEROPAD;
925 goto rflag;
926 case '1': case '2': case '3': case '4':
927 case '5': case '6': case '7': case '8': case '9':
928 n = 0;
929 do {
930 n = 10 * n + to_digit(ch);
931 ch = *fmt++;
932 } while (is_digit(ch));
933 if (ch == '$') {
934 nextarg = n;
935 if (argtable == NULL) {
936 argtable = statargtable;
937 if (__find_arguments(fmt0, orgap,
938 &argtable) == -1)
939 goto oomem;
941 goto rflag;
943 width = n;
944 goto reswitch;
945 #ifndef NO_FLOATING_POINT
946 case 'L':
947 flags |= LONGDBL;
948 goto rflag;
949 #endif
950 case 'h':
951 if (flags & SHORTINT) {
952 flags &= ~SHORTINT;
953 flags |= CHARINT;
954 } else
955 flags |= SHORTINT;
956 goto rflag;
957 case 'j':
958 flags |= INTMAXT;
959 goto rflag;
960 case 'l':
961 if (flags & LONGINT) {
962 flags &= ~LONGINT;
963 flags |= LLONGINT;
964 } else
965 flags |= LONGINT;
966 goto rflag;
967 case 'q':
968 flags |= LLONGINT; /* not necessarily */
969 goto rflag;
970 case 't':
971 flags |= PTRDIFFT;
972 goto rflag;
973 case 'z':
974 flags |= SIZET;
975 goto rflag;
976 case 'C':
977 flags |= LONGINT;
978 /*FALLTHROUGH*/
979 case 'c':
980 #ifdef NARROW
981 if (flags & LONGINT) {
982 static const mbstate_t initial;
983 mbstate_t mbs;
984 size_t mbseqlen;
986 mbs = initial;
987 mbseqlen = wcrtomb(buf,
988 (wchar_t)GETARG(wint_t), &mbs);
989 if (mbseqlen == (size_t)-1) {
990 fp->_flags |= __SERR;
991 goto error;
993 size = (int)mbseqlen;
994 } else {
995 *buf = GETARG(int);
996 size = 1;
998 #else
999 if (flags & LONGINT)
1000 *buf = (wchar_t)GETARG(wint_t);
1001 else
1002 *buf = (wchar_t)btowc(GETARG(int));
1003 size = 1;
1004 #endif
1005 result = buf;
1006 sign = '\0';
1007 break;
1008 case 'D':
1009 flags |= LONGINT;
1010 /*FALLTHROUGH*/
1011 case 'd':
1012 case 'i':
1013 if (flags & INTMAX_SIZE) {
1014 ujval = SJARG();
1015 if ((intmax_t)ujval < 0) {
1016 ujval = -ujval;
1017 sign = '-';
1019 } else {
1020 ulval = SARG();
1021 if ((long)ulval < 0) {
1022 ulval = -ulval;
1023 sign = '-';
1026 base = 10;
1027 goto number;
1028 #ifndef NO_FLOATING_POINT
1029 #ifdef WIDE_DOUBLE
1030 case 'a':
1031 case 'A':
1032 if (ch == 'a') {
1033 ox[1] = 'x';
1034 xdigs = xdigs_lower;
1035 expchar = 'p';
1036 } else {
1037 ox[1] = 'X';
1038 xdigs = xdigs_upper;
1039 expchar = 'P';
1041 if (prec >= 0)
1042 prec++;
1043 if (flags & LONGDBL) {
1044 fparg.ldbl = GETARG(long double);
1045 dtoaresult =
1046 __hldtoa(fparg.ldbl, xdigs, prec,
1047 &expt, &signflag, &dtoaend);
1048 } else {
1049 fparg.dbl = GETARG(double);
1050 dtoaresult =
1051 __hdtoa(fparg.dbl, xdigs, prec,
1052 &expt, &signflag, &dtoaend);
1054 if (dtoaresult == NULL)
1055 goto oomem;
1057 if (prec < 0)
1058 prec = dtoaend - dtoaresult;
1059 if (expt == INT_MAX)
1060 ox[1] = '\0';
1061 ndig = dtoaend - dtoaresult;
1062 if (convbuf != NULL)
1063 free(convbuf);
1064 #ifndef NARROW
1065 result = convbuf = __mbsconv(dtoaresult, -1);
1066 #else
1067 /*XXX inefficient*/
1068 result = convbuf = strdup(dtoaresult);
1069 #endif
1070 if (result == NULL)
1071 goto oomem;
1072 __freedtoa(dtoaresult);
1073 goto fp_common;
1074 case 'e':
1075 case 'E':
1076 expchar = ch;
1077 if (prec < 0) /* account for digit before decpt */
1078 prec = DEFPREC + 1;
1079 else
1080 prec++;
1081 goto fp_begin;
1082 case 'f':
1083 case 'F':
1084 expchar = '\0';
1085 goto fp_begin;
1086 case 'g':
1087 case 'G':
1088 expchar = ch - ('g' - 'e');
1089 if (prec == 0)
1090 prec = 1;
1091 fp_begin:
1092 if (prec < 0)
1093 prec = DEFPREC;
1094 if (flags & LONGDBL) {
1095 fparg.ldbl = GETARG(long double);
1096 dtoaresult =
1097 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
1098 &expt, &signflag, &dtoaend);
1099 } else {
1100 fparg.dbl = GETARG(double);
1101 dtoaresult =
1102 __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
1103 &expt, &signflag, &dtoaend);
1104 if (expt == 9999)
1105 expt = INT_MAX;
1107 if (dtoaresult == NULL)
1108 goto oomem;
1109 ndig = dtoaend - dtoaresult;
1110 if (convbuf != NULL)
1111 free(convbuf);
1112 #ifndef NARROW
1113 result = convbuf = __mbsconv(dtoaresult, -1);
1114 #else
1115 /*XXX inefficient*/
1116 result = convbuf = strdup(dtoaresult);
1117 #endif
1118 if (result == NULL)
1119 goto oomem;
1120 __freedtoa(dtoaresult);
1121 fp_common:
1122 if (signflag)
1123 sign = '-';
1124 if (expt == INT_MAX) { /* inf or nan */
1125 if (*result == 'N') {
1126 result = (ch >= 'a') ? STRCONST("nan") :
1127 STRCONST("NAN");
1128 sign = '\0';
1129 } else
1130 result = (ch >= 'a') ? STRCONST("inf") :
1131 STRCONST("INF");
1132 size = 3;
1133 break;
1135 #else
1136 case 'e':
1137 case 'E':
1138 case 'f':
1139 case 'F':
1140 case 'g':
1141 case 'G':
1142 if (prec == -1) {
1143 prec = DEFPREC;
1144 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
1145 prec = 1;
1148 if (flags & LONGDBL) {
1149 _double = (double) GETARG(long double);
1150 } else {
1151 _double = GETARG(double);
1154 /* do this before tricky precision changes */
1155 if (isinf(_double)) {
1156 if (_double < 0)
1157 sign = '-';
1158 if (ch == 'E' || ch == 'F' || ch == 'G')
1159 result = STRCONST("INF");
1160 else
1161 result = STRCONST("inf");
1162 size = 3;
1163 break;
1165 if (isnan(_double)) {
1166 if (ch == 'E' || ch == 'F' || ch == 'G')
1167 result = STRCONST("NAN");
1168 else
1169 result = STRCONST("nan");
1170 size = 3;
1171 break;
1174 flags |= FPT;
1175 dtoaresult = cvt(_double, prec, flags, &softsign,
1176 &expt, ch, &ndig);
1177 if (dtoaresult == NULL)
1178 goto oomem;
1179 if (convbuf != NULL)
1180 free(convbuf);
1181 #ifndef NARROW
1182 result = convbuf = __mbsconv(dtoaresult, -1);
1183 #else
1184 /*XXX inefficient*/
1185 result = convbuf = strdup(dtoaresult);
1186 #endif
1187 if (result == NULL)
1188 goto oomem;
1189 __freedtoa(dtoaresult);
1190 if (softsign)
1191 sign = '-';
1192 #endif
1193 flags |= FPT;
1194 if (ch == 'g' || ch == 'G') {
1195 if (expt > -4 && expt <= prec) {
1196 /* Make %[gG] smell like %[fF] */
1197 expchar = '\0';
1198 if (flags & ALT)
1199 prec -= expt;
1200 else
1201 prec = ndig - expt;
1202 if (prec < 0)
1203 prec = 0;
1204 } else {
1206 * Make %[gG] smell like %[eE], but
1207 * trim trailing zeroes if no # flag.
1209 if (!(flags & ALT))
1210 prec = ndig;
1213 if (expchar) {
1214 expsize = exponent(expstr, expt - 1, expchar);
1215 size = expsize + prec;
1216 if (prec > 1 || flags & ALT)
1217 ++size;
1218 } else {
1219 /* space for digits before decimal point */
1220 if (expt > 0)
1221 size = expt;
1222 else /* "0" */
1223 size = 1;
1224 /* space for decimal pt and following digits */
1225 if (prec || flags & ALT)
1226 size += prec + 1;
1227 if (grouping && expt > 0) {
1228 /* space for thousands' grouping */
1229 nseps = nrepeats = 0;
1230 lead = expt;
1231 while (*grouping != CHAR_MAX) {
1232 if (lead <= *grouping)
1233 break;
1234 lead -= *grouping;
1235 if (*(grouping+1)) {
1236 nseps++;
1237 grouping++;
1238 } else
1239 nrepeats++;
1241 size += nseps + nrepeats;
1242 } else
1243 lead = expt;
1245 break;
1246 #endif /* !NO_FLOATING_POINT */
1247 case 'n':
1249 * Assignment-like behavior is specified if the
1250 * value overflows or is otherwise unrepresentable.
1251 * C99 says to use `signed char' for %hhn conversions.
1253 if (flags & LLONGINT)
1254 *GETARG(long long *) = ret;
1255 else if (flags & SIZET)
1256 *GETARG(ssize_t *) = (ssize_t)ret;
1257 else if (flags & PTRDIFFT)
1258 *GETARG(ptrdiff_t *) = ret;
1259 else if (flags & INTMAXT)
1260 *GETARG(intmax_t *) = ret;
1261 else if (flags & LONGINT)
1262 *GETARG(long *) = ret;
1263 else if (flags & SHORTINT)
1264 *GETARG(short *) = ret;
1265 else if (flags & CHARINT)
1266 *GETARG(signed char *) = ret;
1267 else
1268 *GETARG(int *) = ret;
1269 continue; /* no output */
1270 case 'O':
1271 flags |= LONGINT;
1272 /*FALLTHROUGH*/
1273 case 'o':
1274 if (flags & INTMAX_SIZE)
1275 ujval = UJARG();
1276 else
1277 ulval = UARG();
1278 base = 8;
1279 goto nosign;
1280 case 'p':
1282 * ``The argument shall be a pointer to void. The
1283 * value of the pointer is converted to a sequence
1284 * of printable characters, in an implementation-
1285 * defined manner.''
1286 * -- ANSI X3J11
1288 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1289 base = 16;
1290 xdigs = xdigs_lower;
1291 flags = flags | INTMAXT;
1292 ox[1] = 'x';
1293 goto nosign;
1294 case 'S':
1295 flags |= LONGINT;
1296 /*FALLTHROUGH*/
1297 case 's':
1298 if ((flags & LONGINT) != MULTI) {
1299 if ((result = GETARG(CHAR_T *)) == NULL)
1300 result = STRCONST("(null)");
1301 } else {
1302 MCHAR_T *mc;
1304 if (convbuf != NULL)
1305 free(convbuf);
1306 if ((mc = GETARG(MCHAR_T *)) == NULL)
1307 result = STRCONST("(null)");
1308 else {
1309 convbuf = SCONV(mc, prec);
1310 if (convbuf == NULL) {
1311 fp->_flags |= __SERR;
1312 goto error;
1314 result = convbuf;
1318 if (prec >= 0) {
1320 * can't use STRLEN; can only look for the
1321 * NUL in the first `prec' characters, and
1322 * STRLEN() will go further.
1324 CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
1326 if (p != NULL) {
1327 size = p - result;
1328 if (size > prec)
1329 size = prec;
1330 } else
1331 size = prec;
1332 } else
1333 size = STRLEN(result);
1334 sign = '\0';
1335 break;
1336 case 'U':
1337 flags |= LONGINT;
1338 /*FALLTHROUGH*/
1339 case 'u':
1340 if (flags & INTMAX_SIZE)
1341 ujval = UJARG();
1342 else
1343 ulval = UARG();
1344 base = 10;
1345 goto nosign;
1346 case 'X':
1347 xdigs = xdigs_upper;
1348 goto hex;
1349 case 'x':
1350 xdigs = xdigs_lower;
1351 hex:
1352 if (flags & INTMAX_SIZE)
1353 ujval = UJARG();
1354 else
1355 ulval = UARG();
1356 base = 16;
1357 /* leading 0x/X only if non-zero */
1358 if (flags & ALT &&
1359 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1360 ox[1] = ch;
1362 flags &= ~GROUPING;
1363 /* unsigned conversions */
1364 nosign: sign = '\0';
1366 * ``... diouXx conversions ... if a precision is
1367 * specified, the 0 flag will be ignored.''
1368 * -- ANSI X3J11
1370 number: if ((dprec = prec) >= 0)
1371 flags &= ~ZEROPAD;
1374 * ``The result of converting a zero value with an
1375 * explicit precision of zero is no characters.''
1376 * -- ANSI X3J11
1378 * ``The C Standard is clear enough as is. The call
1379 * printf("%#.0o", 0) should print 0.''
1380 * -- Defect Report #151
1382 result = cp = buf + BUF;
1383 if (flags & INTMAX_SIZE) {
1384 if (ujval != 0 || prec != 0 ||
1385 (flags & ALT && base == 8))
1386 result = __ujtoa(ujval, cp, base,
1387 flags & ALT, xdigs,
1388 flags & GROUPING, thousands_sep,
1389 grouping);
1390 } else {
1391 if (ulval != 0 || prec != 0 ||
1392 (flags & ALT && base == 8))
1393 result = __ultoa(ulval, cp, base,
1394 flags & ALT, xdigs,
1395 flags & GROUPING, thousands_sep,
1396 grouping);
1398 size = buf + BUF - result;
1399 if (size > BUF) /* should never happen */
1400 abort();
1401 break;
1402 default: /* "%?" prints ?, unless ? is NUL */
1403 if (ch == '\0')
1404 goto done;
1405 /* pretend it was %c with argument ch */
1406 *buf = ch;
1407 result = buf;
1408 size = 1;
1409 sign = '\0';
1410 break;
1414 * All reasonable formats wind up here. At this point, `result'
1415 * points to a string which (if not flags&LADJUST) should be
1416 * padded out to `width' places. If flags&ZEROPAD, it should
1417 * first be prefixed by any sign or other prefix; otherwise,
1418 * it should be blank padded before the prefix is emitted.
1419 * After any left-hand padding and prefixing, emit zeroes
1420 * required by a decimal [diouxX] precision, then print the
1421 * string proper, then emit zeroes required by any leftover
1422 * floating precision; finally, if LADJUST, pad with blanks.
1424 * Compute actual size, so we know how much to pad.
1425 * size excludes decimal prec; realsz includes it.
1427 realsz = dprec > size ? dprec : size;
1428 if (sign)
1429 realsz++;
1430 if (ox[1])
1431 realsz += 2;
1433 prsize = width > realsz ? width : realsz;
1434 if ((unsigned)ret + prsize > INT_MAX) {
1435 ret = END_OF_FILE;
1436 goto error;
1439 /* right-adjusting blank padding */
1440 if ((flags & (LADJUST|ZEROPAD)) == 0)
1441 PAD(width - realsz, blanks);
1443 /* prefix */
1444 if (sign)
1445 PRINT(&sign, 1);
1447 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1448 ox[0] = '0';
1449 PRINT(ox, 2);
1452 /* right-adjusting zero padding */
1453 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1454 PAD(width - realsz, zeroes);
1456 /* leading zeroes from decimal precision */
1457 PAD(dprec - size, zeroes);
1459 /* the string or number proper */
1460 #ifndef NO_FLOATING_POINT
1461 if ((flags & FPT) == 0) {
1462 PRINT(result, size);
1463 } else { /* glue together f_p fragments */
1464 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1465 if (expt <= 0) {
1466 PRINT(zeroes, 1);
1467 if (prec || flags & ALT)
1468 PRINT(decimal_point, 1);
1469 PAD(-expt, zeroes);
1470 /* already handled initial 0's */
1471 prec += expt;
1472 } else {
1473 PRINTANDPAD(result, convbuf + ndig,
1474 lead, zeroes);
1475 result += lead;
1476 if (grouping) {
1477 while (nseps>0 || nrepeats>0) {
1478 if (nrepeats > 0)
1479 nrepeats--;
1480 else {
1481 grouping--;
1482 nseps--;
1484 PRINT(&thousands_sep,
1486 PRINTANDPAD(result,
1487 convbuf + ndig,
1488 *grouping, zeroes);
1489 result += *grouping;
1491 if (result > convbuf + ndig)
1492 result = convbuf + ndig;
1494 if (prec || flags & ALT) {
1495 buf[0] = *decimal_point;
1496 PRINT(buf, 1);
1499 PRINTANDPAD(result, convbuf + ndig, prec,
1500 zeroes);
1501 } else { /* %[eE] or sufficiently long %[gG] */
1502 if (prec > 1 || flags & ALT) {
1503 buf[0] = *result++;
1504 buf[1] = *decimal_point;
1505 PRINT(buf, 2);
1506 PRINT(result, ndig-1);
1507 PAD(prec - ndig, zeroes);
1508 } else /* XeYYY */
1509 PRINT(result, 1);
1510 PRINT(expstr, expsize);
1513 #else
1514 PRINT(result, size);
1515 #endif
1516 /* left-adjusting padding (always blank) */
1517 if (flags & LADJUST)
1518 PAD(width - realsz, blanks);
1520 /* finally, adjust ret */
1521 ret += prsize;
1522 FLUSH();
1524 done:
1525 FLUSH();
1526 error:
1527 va_end(orgap);
1528 if (convbuf != NULL)
1529 free(convbuf);
1530 if (__sferror(fp))
1531 ret = END_OF_FILE;
1532 if ((argtable != NULL) && (argtable != statargtable))
1533 free (argtable);
1534 return (ret);
1535 /* NOTREACHED */
1536 oomem:
1537 errno = ENOMEM;
1538 ret = END_OF_FILE;
1539 goto error;
1543 * Find all arguments when a positional parameter is encountered. Returns a
1544 * table, indexed by argument number, of pointers to each arguments. The
1545 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1546 * It will be replaces with a malloc-ed one if it overflows.
1548 static int
1549 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
1551 CHAR_T *fmt; /* format string */
1552 int ch; /* character from fmt */
1553 int n, n2; /* handy integer (short term usage) */
1554 CHAR_T *cp; /* handy char pointer (short term usage) */
1555 int flags; /* flags as above */
1556 enum typeid *typetable; /* table of types */
1557 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1558 int tablesize; /* current size of type table */
1559 int tablemax; /* largest used index in table */
1560 int nextarg; /* 1-based argument index */
1563 * Add an argument type to the table, expanding if necessary.
1565 #define ADDTYPE(type) \
1566 do { \
1567 if (nextarg >= tablesize) \
1568 if (__grow_type_table(nextarg, &typetable, \
1569 &tablesize) == -1) \
1570 return -1; \
1571 if (nextarg > tablemax) \
1572 tablemax = nextarg; \
1573 typetable[nextarg++] = type; \
1574 } while (/*CONSTCOND*/0)
1576 #define ADDSARG() \
1577 do { \
1578 if (flags & INTMAXT) \
1579 ADDTYPE(T_INTMAXT); \
1580 else if (flags & SIZET) \
1581 ADDTYPE(T_SSIZET); \
1582 else if (flags & PTRDIFFT) \
1583 ADDTYPE(T_PTRDIFFT); \
1584 else if (flags & LLONGINT) \
1585 ADDTYPE(T_LLONG); \
1586 else if (flags & LONGINT) \
1587 ADDTYPE(T_LONG); \
1588 else \
1589 ADDTYPE(T_INT); \
1590 } while (/*CONSTCOND*/0)
1592 #define ADDUARG() \
1593 do { \
1594 if (flags & INTMAXT) \
1595 ADDTYPE(T_UINTMAXT); \
1596 else if (flags & SIZET) \
1597 ADDTYPE(T_SIZET); \
1598 else if (flags & PTRDIFFT) \
1599 ADDTYPE(T_PTRDIFFT); \
1600 else if (flags & LLONGINT) \
1601 ADDTYPE(T_U_LLONG); \
1602 else if (flags & LONGINT) \
1603 ADDTYPE(T_U_LONG); \
1604 else \
1605 ADDTYPE(T_U_INT); \
1606 } while (/*CONSTCOND*/0)
1608 * Add * arguments to the type array.
1610 #define ADDASTER() \
1611 n2 = 0; \
1612 cp = fmt; \
1613 while (is_digit(*cp)) { \
1614 n2 = 10 * n2 + to_digit(*cp); \
1615 cp++; \
1617 if (*cp == '$') { \
1618 int hold = nextarg; \
1619 nextarg = n2; \
1620 ADDTYPE(T_INT); \
1621 nextarg = hold; \
1622 fmt = ++cp; \
1623 } else { \
1624 ADDTYPE(T_INT); \
1626 fmt = (CHAR_T *)__UNCONST(fmt0);
1627 typetable = stattypetable;
1628 tablesize = STATIC_ARG_TBL_SIZE;
1629 tablemax = 0;
1630 nextarg = 1;
1631 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1632 typetable[n] = T_UNUSED;
1635 * Scan the format for conversions (`%' character).
1637 for (;;) {
1638 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1639 /* void */;
1640 if (ch == '\0')
1641 goto done;
1642 fmt++; /* skip over '%' */
1644 flags = 0;
1646 rflag: ch = *fmt++;
1647 reswitch: switch (ch) {
1648 case ' ':
1649 case '#':
1650 goto rflag;
1651 case '*':
1652 ADDASTER ();
1653 goto rflag;
1654 case '-':
1655 case '+':
1656 case '\'':
1657 goto rflag;
1658 case '.':
1659 if ((ch = *fmt++) == '*') {
1660 ADDASTER ();
1661 goto rflag;
1663 while (is_digit(ch)) {
1664 ch = *fmt++;
1666 goto reswitch;
1667 case '0':
1668 goto rflag;
1669 case '1': case '2': case '3': case '4':
1670 case '5': case '6': case '7': case '8': case '9':
1671 n = 0;
1672 do {
1673 n = 10 * n + to_digit(ch);
1674 ch = *fmt++;
1675 } while (is_digit(ch));
1676 if (ch == '$') {
1677 nextarg = n;
1678 goto rflag;
1680 goto reswitch;
1681 #ifndef NO_FLOATING_POINT
1682 case 'L':
1683 flags |= LONGDBL;
1684 goto rflag;
1685 #endif
1686 case 'h':
1687 if (flags & SHORTINT) {
1688 flags &= ~SHORTINT;
1689 flags |= CHARINT;
1690 } else
1691 flags |= SHORTINT;
1692 goto rflag;
1693 case 'j':
1694 flags |= INTMAXT;
1695 goto rflag;
1696 case 'l':
1697 if (flags & LONGINT) {
1698 flags &= ~LONGINT;
1699 flags |= LLONGINT;
1700 } else
1701 flags |= LONGINT;
1702 goto rflag;
1703 case 'q':
1704 flags |= LLONGINT; /* not necessarily */
1705 goto rflag;
1706 case 't':
1707 flags |= PTRDIFFT;
1708 goto rflag;
1709 case 'z':
1710 flags |= SIZET;
1711 goto rflag;
1712 case 'C':
1713 flags |= LONGINT;
1714 /*FALLTHROUGH*/
1715 case 'c':
1716 if (flags & LONGINT)
1717 ADDTYPE(T_WINT);
1718 else
1719 ADDTYPE(T_INT);
1720 break;
1721 case 'D':
1722 flags |= LONGINT;
1723 /*FALLTHROUGH*/
1724 case 'd':
1725 case 'i':
1726 ADDSARG();
1727 break;
1728 #ifndef NO_FLOATING_POINT
1729 case 'a':
1730 case 'A':
1731 case 'e':
1732 case 'E':
1733 case 'f':
1734 case 'g':
1735 case 'G':
1736 if (flags & LONGDBL)
1737 ADDTYPE(T_LONG_DOUBLE);
1738 else
1739 ADDTYPE(T_DOUBLE);
1740 break;
1741 #endif /* !NO_FLOATING_POINT */
1742 case 'n':
1743 if (flags & INTMAXT)
1744 ADDTYPE(TP_INTMAXT);
1745 else if (flags & PTRDIFFT)
1746 ADDTYPE(TP_PTRDIFFT);
1747 else if (flags & SIZET)
1748 ADDTYPE(TP_SIZET);
1749 else if (flags & LLONGINT)
1750 ADDTYPE(TP_LLONG);
1751 else if (flags & LONGINT)
1752 ADDTYPE(TP_LONG);
1753 else if (flags & SHORTINT)
1754 ADDTYPE(TP_SHORT);
1755 else if (flags & CHARINT)
1756 ADDTYPE(TP_SCHAR);
1757 else
1758 ADDTYPE(TP_INT);
1759 continue; /* no output */
1760 case 'O':
1761 flags |= LONGINT;
1762 /*FALLTHROUGH*/
1763 case 'o':
1764 ADDUARG();
1765 break;
1766 case 'p':
1767 ADDTYPE(TP_VOID);
1768 break;
1769 case 'S':
1770 flags |= LONGINT;
1771 /*FALLTHROUGH*/
1772 case 's':
1773 if (flags & LONGINT)
1774 ADDTYPE(TP_WCHAR);
1775 else
1776 ADDTYPE(TP_CHAR);
1777 break;
1778 case 'U':
1779 flags |= LONGINT;
1780 /*FALLTHROUGH*/
1781 case 'u':
1782 case 'X':
1783 case 'x':
1784 ADDUARG();
1785 break;
1786 default: /* "%?" prints ?, unless ? is NUL */
1787 if (ch == '\0')
1788 goto done;
1789 break;
1792 done:
1794 * Build the argument table.
1796 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1797 *argtable = (union arg *)
1798 malloc (sizeof (union arg) * (tablemax + 1));
1799 if (*argtable == NULL)
1800 return -1;
1803 (*argtable) [0].intarg = 0;
1804 for (n = 1; n <= tablemax; n++) {
1805 switch (typetable [n]) {
1806 case T_UNUSED: /* whoops! */
1807 (*argtable) [n].intarg = va_arg (ap, int);
1808 break;
1809 case TP_SCHAR:
1810 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1811 break;
1812 case TP_SHORT:
1813 (*argtable) [n].pshortarg = va_arg (ap, short *);
1814 break;
1815 case T_INT:
1816 (*argtable) [n].intarg = va_arg (ap, int);
1817 break;
1818 case T_U_INT:
1819 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1820 break;
1821 case TP_INT:
1822 (*argtable) [n].pintarg = va_arg (ap, int *);
1823 break;
1824 case T_LONG:
1825 (*argtable) [n].longarg = va_arg (ap, long);
1826 break;
1827 case T_U_LONG:
1828 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1829 break;
1830 case TP_LONG:
1831 (*argtable) [n].plongarg = va_arg (ap, long *);
1832 break;
1833 case T_LLONG:
1834 (*argtable) [n].longlongarg = va_arg (ap, long long);
1835 break;
1836 case T_U_LLONG:
1837 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1838 break;
1839 case TP_LLONG:
1840 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1841 break;
1842 case T_PTRDIFFT:
1843 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1844 break;
1845 case TP_PTRDIFFT:
1846 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1847 break;
1848 case T_SSIZET:
1849 (*argtable) [n].ssizearg = va_arg (ap, ssize_t);
1850 break;
1851 case T_SIZET:
1852 (*argtable) [n].sizearg = va_arg (ap, size_t);
1853 break;
1854 case TP_SIZET:
1855 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1856 break;
1857 case T_INTMAXT:
1858 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1859 break;
1860 case T_UINTMAXT:
1861 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1862 break;
1863 case TP_INTMAXT:
1864 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1865 break;
1866 case T_DOUBLE:
1867 #ifndef NO_FLOATING_POINT
1868 (*argtable) [n].doublearg = va_arg (ap, double);
1869 #endif
1870 break;
1871 case T_LONG_DOUBLE:
1872 #ifndef NO_FLOATING_POINT
1873 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1874 #endif
1875 break;
1876 case TP_CHAR:
1877 (*argtable) [n].pchararg = va_arg (ap, char *);
1878 break;
1879 case TP_VOID:
1880 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1881 break;
1882 case T_WINT:
1883 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1884 break;
1885 case TP_WCHAR:
1886 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1887 break;
1891 if ((typetable != NULL) && (typetable != stattypetable))
1892 free (typetable);
1893 return 0;
1897 * Increase the size of the type table.
1899 static int
1900 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1902 enum typeid *const oldtable = *typetable;
1903 const int oldsize = *tablesize;
1904 enum typeid *newtable;
1905 int n, newsize = oldsize * 2;
1907 if (newsize < nextarg + 1)
1908 newsize = nextarg + 1;
1909 if (oldsize == STATIC_ARG_TBL_SIZE) {
1910 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1911 return -1;
1912 memcpy(newtable, oldtable, oldsize * sizeof(enum typeid));
1913 } else {
1914 newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1915 if (newtable == NULL) {
1916 free(oldtable);
1917 return -1;
1920 for (n = oldsize; n < newsize; n++)
1921 newtable[n] = T_UNUSED;
1923 *typetable = newtable;
1924 *tablesize = newsize;
1925 return 0;
1929 #ifndef NO_FLOATING_POINT
1930 #ifndef WIDE_DOUBLE
1931 static char *
1932 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1933 int *length)
1935 int mode, dsgn;
1936 char *digits, *bp, *rve;
1938 _DIAGASSERT(decpt != NULL);
1939 _DIAGASSERT(length != NULL);
1940 _DIAGASSERT(sign != NULL);
1942 if (ch == 'f') {
1943 mode = 3; /* ndigits after the decimal point */
1944 } else {
1945 /* To obtain ndigits after the decimal point for the 'e'
1946 * and 'E' formats, round to ndigits + 1 significant
1947 * figures.
1949 if (ch == 'e' || ch == 'E') {
1950 ndigits++;
1952 mode = 2; /* ndigits significant digits */
1955 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1956 if (digits == NULL)
1957 return NULL;
1958 if (dsgn) {
1959 value = -value;
1960 *sign = '-';
1961 } else
1962 *sign = '\000';
1963 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
1964 bp = digits + ndigits;
1965 if (ch == 'f') {
1966 if (*digits == '0' && value)
1967 *decpt = -ndigits + 1;
1968 bp += *decpt;
1970 if (value == 0) /* kludge for __dtoa irregularity */
1971 rve = bp;
1972 while (rve < bp)
1973 *rve++ = '0';
1975 *length = rve - digits;
1976 return digits;
1978 #endif
1980 static int
1981 exponent(CHAR_T *p0, int expo, int fmtch)
1983 CHAR_T *p, *t;
1984 CHAR_T expbuf[MAXEXPDIG];
1986 p = p0;
1987 *p++ = fmtch;
1988 if (expo < 0) {
1989 expo = -expo;
1990 *p++ = '-';
1992 else
1993 *p++ = '+';
1994 t = expbuf + MAXEXPDIG;
1995 if (expo > 9) {
1996 do {
1997 *--t = to_char(expo % 10);
1998 } while ((expo /= 10) > 9);
1999 *--t = to_char(expo);
2000 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
2002 else {
2004 * Exponents for decimal floating point conversions
2005 * (%[eEgG]) must be at least two characters long,
2006 * whereas exponents for hexadecimal conversions can
2007 * be only one character long.
2009 if (fmtch == 'e' || fmtch == 'E')
2010 *p++ = '0';
2011 *p++ = to_char(expo);
2013 return (p - p0);
2015 #endif /* !NO_FLOATING_POINT */