Remove building with NOCRYPTO option
[minix.git] / lib / libc / stdio / vfwprintf.c
blob46132e32208a10ae477bd8ef63949b31c7fa7621
1 /* $NetBSD: vfwprintf.c,v 1.34 2014/01/20 14:11:03 yamt 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.34 2014/01/20 14:11:03 yamt 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 "setlocale_local.h"
68 #include "local.h"
69 #include "extern.h"
70 #include "fvwrite.h"
72 #ifndef NARROW
73 #define MCHAR_T char
74 #define CHAR_T wchar_t
75 #define STRLEN(a) wcslen(a)
76 #define MEMCHR(a, b, c) wmemchr(a, b, c)
77 #define SCONV(a, b, loc) __mbsconv(a, b, loc)
78 #define STRCONST(a) L ## a
79 #define WDECL(a, b) a ## w ## b
80 #define END_OF_FILE WEOF
81 #define MULTI 0
82 #else
83 #define MCHAR_T wchar_t
84 #define CHAR_T char
85 #define STRLEN(a) strlen(a)
86 #define MEMCHR(a, b, c) memchr(a, b, c)
87 #define SCONV(a, b, loc) __wcsconv(a, b, loc)
88 #define STRCONST(a) a
89 #define WDECL(a, b) a ## b
90 #define END_OF_FILE EOF
91 #define MULTI LONGINT
92 #endif
94 union arg {
95 int intarg;
96 u_int uintarg;
97 long longarg;
98 u_long ulongarg;
99 long long longlongarg;
100 unsigned long long ulonglongarg;
101 ptrdiff_t ptrdiffarg;
102 ssize_t ssizearg;
103 size_t sizearg;
104 intmax_t intmaxarg;
105 uintmax_t uintmaxarg;
106 void *pvoidarg;
107 char *pchararg;
108 signed char *pschararg;
109 short *pshortarg;
110 int *pintarg;
111 long *plongarg;
112 long long *plonglongarg;
113 ptrdiff_t *pptrdiffarg;
114 size_t *psizearg;
115 intmax_t *pintmaxarg;
116 #ifndef NO_FLOATING_POINT
117 double doublearg;
118 long double longdoublearg;
119 #endif
120 wint_t wintarg;
121 wchar_t *pwchararg;
125 * Type ids for argument type table.
127 enum typeid {
128 T_UNUSED = 0, TP_SHORT, T_INT, T_U_INT, TP_INT,
129 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
130 T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SIZET,
131 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
132 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
135 #ifdef NARROW
136 __printflike(3, 0)
137 #endif
138 static int __sbprintf(FILE *, locale_t, const CHAR_T *, va_list);
140 static CHAR_T *__ujtoa(uintmax_t, CHAR_T *, int, int, const char *, int,
141 char, const char *);
142 static CHAR_T *__ultoa(u_long, CHAR_T *, int, int, const char *, int,
143 char, const char *);
144 #ifndef NARROW
145 static CHAR_T *__mbsconv(char *, int, locale_t);
146 static wint_t __xfputwc(CHAR_T, FILE *, locale_t);
147 #else
148 static char *__wcsconv(wchar_t *, int, locale_t);
149 static int __sprint(FILE *, struct __suio *);
150 #endif
151 static int __find_arguments(const CHAR_T *, va_list, union arg **);
152 static int __grow_type_table(size_t, enum typeid **, size_t *);
155 * Helper function for `fprintf to unbuffered unix file': creates a
156 * temporary buffer. We only work on write-only files; this avoids
157 * worries about ungetc buffers and so forth.
159 static int
160 __sbprintf(FILE *fp, locale_t loc, const CHAR_T *fmt, va_list ap)
162 int ret;
163 FILE fake;
164 struct __sfileext fakeext;
165 unsigned char buf[BUFSIZ];
167 _DIAGASSERT(fp != NULL);
168 _DIAGASSERT(fmt != NULL);
170 _FILEEXT_SETUP(&fake, &fakeext);
171 memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
173 /* copy the important variables */
174 fake._flags = fp->_flags & ~__SNBF;
175 fake._file = fp->_file;
176 fake._cookie = fp->_cookie;
177 fake._write = fp->_write;
178 fake._flush = fp->_flush;
180 /* set up the buffer */
181 fake._bf._base = fake._p = buf;
182 fake._bf._size = fake._w = sizeof(buf);
183 fake._lbfsize = 0; /* not actually used, but Just In Case */
185 /* do the work, then copy any error status */
186 ret = WDECL(__vf,printf_unlocked_l)(&fake, loc, fmt, ap);
187 if (ret >= 0 && fflush(&fake))
188 ret = END_OF_FILE;
189 if (fake._flags & __SERR)
190 fp->_flags |= __SERR;
191 return ret;
194 #ifndef NARROW
196 * Like __fputwc, but handles fake string (__SSTR) files properly.
197 * File must already be locked.
199 static wint_t
200 __xfputwc(wchar_t wc, FILE *fp, locale_t loc)
202 static const mbstate_t initial;
203 mbstate_t mbs;
204 char buf[MB_LEN_MAX];
205 struct __suio uio;
206 struct __siov iov;
207 size_t len;
209 if ((fp->_flags & __SSTR) == 0)
210 return __fputwc_unlock(wc, fp);
212 mbs = initial;
213 if ((len = wcrtomb_l(buf, wc, &mbs, loc)) == (size_t)-1) {
214 fp->_flags |= __SERR;
215 return END_OF_FILE;
217 uio.uio_iov = &iov;
218 uio.uio_resid = len;
219 uio.uio_iovcnt = 1;
220 iov.iov_base = buf;
221 iov.iov_len = len;
222 return __sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE;
224 #else
226 * Flush out all the vectors defined by the given uio,
227 * then reset it so that it can be reused.
229 static int
230 __sprint(FILE *fp, struct __suio *uio)
232 int err;
234 _DIAGASSERT(fp != NULL);
235 _DIAGASSERT(uio != NULL);
237 if (uio->uio_resid == 0) {
238 uio->uio_iovcnt = 0;
239 return 0;
241 err = __sfvwrite(fp, uio);
242 uio->uio_resid = 0;
243 uio->uio_iovcnt = 0;
244 return err;
246 #endif
249 * Macros for converting digits to letters and vice versa
251 #define to_digit(c) ((c) - '0')
252 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
253 #define to_char(n) (CHAR_T)((n) + '0')
256 * Convert an unsigned long to ASCII for printf purposes, returning
257 * a pointer to the first character of the string representation.
258 * Octal numbers can be forced to have a leading zero; hex numbers
259 * use the given digits.
261 static CHAR_T *
262 __ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs,
263 int needgrp, char thousep, const char *grp)
265 CHAR_T *cp = endp;
266 long sval;
267 int ndig;
270 * Handle the three cases separately, in the hope of getting
271 * better/faster code.
273 switch (base) {
274 case 10:
275 if (val < 10) { /* many numbers are 1 digit */
276 *--cp = to_char(val);
277 return cp;
279 ndig = 0;
281 * On many machines, unsigned arithmetic is harder than
282 * signed arithmetic, so we do at most one unsigned mod and
283 * divide; this is sufficient to reduce the range of
284 * the incoming value to where signed arithmetic works.
286 if (val > LONG_MAX) {
287 *--cp = to_char(val % 10);
288 ndig++;
289 sval = val / 10;
290 } else
291 sval = val;
292 do {
293 *--cp = to_char(sval % 10);
294 ndig++;
296 * If (*grp == CHAR_MAX) then no more grouping
297 * should be performed.
299 if (needgrp && ndig == *grp
300 && (unsigned char)*grp != (unsigned char)CHAR_MAX
301 && sval > 9) {
302 *--cp = thousep;
303 ndig = 0;
305 * If (*(grp+1) == '\0') then we have to
306 * use *grp character (last grouping rule)
307 * for all next cases
309 if (*(grp+1) != '\0')
310 grp++;
312 sval /= 10;
313 } while (sval != 0);
314 break;
316 case 8:
317 do {
318 *--cp = to_char(val & 7);
319 val >>= 3;
320 } while (val);
321 if (octzero && *cp != '0')
322 *--cp = '0';
323 break;
325 case 16:
326 do {
327 *--cp = xdigs[(size_t)val & 15];
328 val >>= 4;
329 } while (val);
330 break;
332 default: /* oops */
333 abort();
335 return cp;
338 /* Identical to __ultoa, but for intmax_t. */
339 static CHAR_T *
340 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero,
341 const char *xdigs, int needgrp, char thousep, const char *grp)
343 CHAR_T *cp = endp;
344 intmax_t sval;
345 int ndig;
347 /* quick test for small values; __ultoa is typically much faster */
348 /* (perhaps instead we should run until small, then call __ultoa?) */
349 if (val <= ULONG_MAX)
350 return __ultoa((u_long)val, endp, base, octzero, xdigs,
351 needgrp, thousep, grp);
352 switch (base) {
353 case 10:
354 if (val < 10) {
355 *--cp = to_char(val % 10);
356 return cp;
358 ndig = 0;
359 if (val > INTMAX_MAX) {
360 *--cp = to_char(val % 10);
361 ndig++;
362 sval = val / 10;
363 } else
364 sval = val;
365 do {
366 *--cp = to_char(sval % 10);
367 ndig++;
369 * If (*grp == CHAR_MAX) then no more grouping
370 * should be performed.
372 if (needgrp
373 && (unsigned char)*grp != (unsigned char)CHAR_MAX
374 && ndig == *grp
375 && sval > 9) {
376 *--cp = thousep;
377 ndig = 0;
379 * If (*(grp+1) == '\0') then we have to
380 * use *grp character (last grouping rule)
381 * for all next cases
383 if (*(grp+1) != '\0')
384 grp++;
386 sval /= 10;
387 } while (sval != 0);
388 break;
390 case 8:
391 do {
392 *--cp = to_char(val & 7);
393 val >>= 3;
394 } while (val);
395 if (octzero && *cp != '0')
396 *--cp = '0';
397 break;
399 case 16:
400 do {
401 *--cp = xdigs[(size_t)val & 15];
402 val >>= 4;
403 } while (val);
404 break;
406 default:
407 abort();
409 return cp;
412 #ifndef NARROW
414 * Convert a multibyte character string argument for the %s format to a wide
415 * string representation. ``prec'' specifies the maximum number of bytes
416 * to output. If ``prec'' is greater than or equal to zero, we can't assume
417 * that the multibyte char. string ends in a null character.
419 static wchar_t *
420 __mbsconv(char *mbsarg, int prec, locale_t loc)
422 static const mbstate_t initial;
423 mbstate_t mbs;
424 wchar_t *convbuf, *wcp;
425 const char *p;
426 size_t insize, nchars, nconv;
428 if (mbsarg == NULL)
429 return NULL;
432 * Supplied argument is a multibyte string; convert it to wide
433 * characters first.
435 if (prec >= 0) {
437 * String is not guaranteed to be NUL-terminated. Find the
438 * number of characters to print.
440 p = mbsarg;
441 insize = nchars = nconv = 0;
442 mbs = initial;
443 while (nchars != (size_t)prec) {
444 nconv = mbrlen_l(p, MB_CUR_MAX_L(loc), &mbs, loc);
445 if (nconv == 0 || nconv == (size_t)-1 ||
446 nconv == (size_t)-2)
447 break;
448 p += nconv;
449 nchars++;
450 insize += nconv;
452 if (nconv == (size_t)-1 || nconv == (size_t)-2)
453 return NULL;
454 } else
455 insize = strlen(mbsarg);
458 * Allocate buffer for the result and perform the conversion,
459 * converting at most `size' bytes of the input multibyte string to
460 * wide characters for printing.
462 convbuf = malloc((insize + 1) * sizeof(*convbuf));
463 if (convbuf == NULL)
464 return NULL;
465 wcp = convbuf;
466 p = mbsarg;
467 mbs = initial;
468 nconv = 0;
469 while (insize != 0) {
470 nconv = mbrtowc_l(wcp, p, insize, &mbs, loc);
471 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
472 break;
473 wcp++;
474 p += nconv;
475 insize -= nconv;
477 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
478 free(convbuf);
479 return NULL;
481 *wcp = L'\0';
483 return convbuf;
485 #else
487 * Convert a wide-character string argument for the %ls format to a multibyte
488 * string representation. If not -1, prec specifies the maximum number of
489 * bytes to output, and also means that we can't assume that the wide-char.
490 * string ends is null-terminated.
492 static char *
493 __wcsconv(wchar_t *wcsarg, int prec, locale_t loc)
495 static const mbstate_t initial;
496 mbstate_t mbs;
497 char buf[MB_LEN_MAX];
498 wchar_t *p;
499 char *convbuf;
500 size_t clen, nbytes;
502 /* Allocate space for the maximum number of bytes we could output. */
503 if (prec < 0) {
504 p = wcsarg;
505 mbs = initial;
506 nbytes = wcsrtombs_l(NULL, (void *)&p, 0, &mbs, loc);
507 if (nbytes == (size_t)-1)
508 return NULL;
509 } else {
511 * Optimisation: if the output precision is small enough,
512 * just allocate enough memory for the maximum instead of
513 * scanning the string.
515 if (prec < 128)
516 nbytes = prec;
517 else {
518 nbytes = 0;
519 p = wcsarg;
520 mbs = initial;
521 for (;;) {
522 clen = wcrtomb_l(buf, *p++, &mbs, loc);
523 if (clen == 0 || clen == (size_t)-1 ||
524 nbytes + clen > (size_t)prec)
525 break;
526 nbytes += clen;
530 if ((convbuf = malloc(nbytes + 1)) == NULL)
531 return NULL;
533 /* Fill the output buffer. */
534 p = wcsarg;
535 mbs = initial;
536 if ((nbytes = wcsrtombs_l(convbuf, (void *)&p,
537 nbytes, &mbs, loc)) == (size_t)-1) {
538 free(convbuf);
539 return NULL;
541 convbuf[nbytes] = '\0';
542 return convbuf;
544 #endif
547 * MT-safe version
550 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap)
552 int ret;
554 FLOCKFILE(fp);
555 ret = WDECL(__vf,printf_unlocked_l)(fp, _current_locale(), fmt0, ap);
556 FUNLOCKFILE(fp);
557 return ret;
561 WDECL(vf,printf_l)(FILE * __restrict fp, locale_t loc, const CHAR_T * __restrict fmt0,
562 va_list ap)
564 int ret;
566 FLOCKFILE(fp);
567 ret = WDECL(__vf,printf_unlocked_l)(fp, loc, fmt0, ap);
568 FUNLOCKFILE(fp);
569 return ret;
572 #ifndef NO_FLOATING_POINT
574 #include <float.h>
575 #include <math.h>
576 #include "floatio.h"
578 #define DEFPREC 6
580 static int exponent(CHAR_T *, int, int);
581 #ifndef WIDE_DOUBLE
582 static char *cvt(double, int, int, char *, int *, int, int *);
583 #endif
585 #endif /* !NO_FLOATING_POINT */
588 * The size of the buffer we use as scratch space for integer
589 * conversions, among other things. Technically, we would need the
590 * most space for base 10 conversions with thousands' grouping
591 * characters between each pair of digits. 100 bytes is a
592 * conservative overestimate even for a 128-bit uintmax_t.
594 #define BUF 100
596 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
599 * Flags used during conversion.
601 #define ALT 0x001 /* alternate form */
602 #define LADJUST 0x004 /* left adjustment */
603 #define LONGDBL 0x008 /* long double */
604 #define LONGINT 0x010 /* long integer */
605 #define LLONGINT 0x020 /* long long integer */
606 #define SHORTINT 0x040 /* short integer */
607 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
608 #define FPT 0x100 /* Floating point number */
609 #define GROUPING 0x200 /* use grouping ("'" flag) */
610 /* C99 additional size modifiers: */
611 #define SIZET 0x400 /* size_t */
612 #define PTRDIFFT 0x800 /* ptrdiff_t */
613 #define INTMAXT 0x1000 /* intmax_t */
614 #define CHARINT 0x2000 /* print char using int format */
617 * Non-MT-safe version
620 WDECL(__vf,printf_unlocked_l)(FILE *fp, locale_t loc, const CHAR_T *fmt0, va_list ap)
622 CHAR_T *fmt; /* format string */
623 int ch; /* character from fmt */
624 int n, n2; /* handy integer (short term usage) */
625 CHAR_T *cp; /* handy char pointer (short term usage) */
626 int flags; /* flags as above */
627 int ret; /* return value accumulator */
628 int width; /* width from format (%8d), or 0 */
629 int prec; /* precision from format; <0 for N/A */
630 CHAR_T sign; /* sign prefix (' ', '+', '-', or \0) */
631 char thousands_sep; /* locale specific thousands separator */
632 const char *grouping; /* locale specific numeric grouping rules */
633 #ifndef NO_FLOATING_POINT
635 * We can decompose the printed representation of floating
636 * point numbers into several parts, some of which may be empty:
638 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
639 * A B ---C--- D E F
641 * A: 'sign' holds this value if present; '\0' otherwise
642 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
643 * C: cp points to the string MMMNNN. Leading and trailing
644 * zeros are not in the string and must be added.
645 * D: expchar holds this character; '\0' if no exponent, e.g. %f
646 * F: at least two digits for decimal, at least one digit for hex
648 char *decimal_point; /* locale specific decimal point */
649 #ifdef WIDE_DOUBLE
650 int signflag; /* true if float is negative */
651 union { /* floating point arguments %[aAeEfFgG] */
652 double dbl;
653 long double ldbl;
654 } fparg;
655 char *dtoaend; /* pointer to end of converted digits */
656 #else
657 double _double; /* double precision arguments %[eEfgG] */
658 char softsign; /* temporary negative sign for floats */
659 #endif
660 char *dtoaresult; /* buffer allocated by dtoa */
661 int expt; /* integer value of exponent */
662 char expchar; /* exponent character: [eEpP\0] */
663 int expsize; /* character count for expstr */
664 int lead; /* sig figs before decimal or group sep */
665 int ndig; /* actual number of digits returned by dtoa */
666 CHAR_T expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
667 int nseps; /* number of group separators with ' */
668 int nrepeats; /* number of repeats of the last group */
669 #endif
670 u_long ulval; /* integer arguments %[diouxX] */
671 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
672 int base; /* base for [diouxX] conversion */
673 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
674 int realsz; /* field size expanded by dprec, sign, etc */
675 int size; /* size of converted field or string */
676 int prsize; /* max size of printed field */
677 const char *xdigs; /* digits for %[xX] conversion */
678 #ifdef NARROW
679 #define NIOV 8
680 struct __siov *iovp; /* for PRINT macro */
681 struct __suio uio; /* output information: summary */
682 struct __siov iov[NIOV];/* ... and individual io vectors */
683 #else
684 int n3;
685 #endif
686 CHAR_T buf[BUF]; /* buffer with space for digits of uintmax_t */
687 CHAR_T ox[2]; /* space for 0x hex-prefix */
688 union arg *argtable; /* args, built due to positional arg */
689 union arg statargtable [STATIC_ARG_TBL_SIZE];
690 int nextarg; /* 1-based argument index */
691 va_list orgap; /* original argument pointer */
692 CHAR_T *convbuf; /* multibyte to wide conversion result */
695 * Choose PADSIZE to trade efficiency vs. size. If larger printf
696 * fields occur frequently, increase PADSIZE and make the initialisers
697 * below longer.
699 #define PADSIZE 16 /* pad chunk size */
700 static CHAR_T blanks[PADSIZE] =
701 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
702 static CHAR_T zeroes[PADSIZE] =
703 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
705 static const char xdigs_lower[16] = "0123456789abcdef";
706 static const char xdigs_upper[16] = "0123456789ABCDEF";
709 * BEWARE, these `goto error' on error, PRINT uses `n2' and
710 * PAD uses `n'.
712 #ifndef NARROW
713 #define PRINT(ptr, len) do { \
714 for (n3 = 0; n3 < (len); n3++) \
715 if (__xfputwc((ptr)[n3], fp, loc) == END_OF_FILE) { \
716 fp->_flags |= __SERR; \
717 goto error; \
719 } while (/*CONSTCOND*/0)
720 #define FLUSH()
721 #else
722 #define PRINT(ptr, len) do { \
723 iovp->iov_base = __UNCONST(ptr); \
724 iovp->iov_len = (len); \
725 uio.uio_resid += (len); \
726 iovp++; \
727 if (++uio.uio_iovcnt >= NIOV) { \
728 if (__sprint(fp, &uio)) \
729 goto error; \
730 iovp = iov; \
732 } while (/*CONSTCOND*/0)
733 #define FLUSH() do { \
734 if (uio.uio_resid && __sprint(fp, &uio)) \
735 goto error; \
736 uio.uio_iovcnt = 0; \
737 iovp = iov; \
738 } while (/*CONSTCOND*/0)
739 #endif /* NARROW */
741 #define PAD(howmany, with) do { \
742 if ((n = (howmany)) > 0) { \
743 while (n > PADSIZE) { \
744 PRINT(with, PADSIZE); \
745 n -= PADSIZE; \
747 PRINT(with, n); \
749 } while (/*CONSTCOND*/0)
750 #define PRINTANDPAD(p, ep, len, with) do { \
751 ptrdiff_t td = (ep) - (p); \
752 _DIAGASSERT(__type_fit(int, td)); \
753 n2 = (int)td; \
754 if (n2 > (len)) \
755 n2 = (len); \
756 if (n2 > 0) \
757 PRINT((p), n2); \
758 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
759 } while(/*CONSTCOND*/0)
762 * Get the argument indexed by nextarg. If the argument table is
763 * built, use it to get the argument. If its not, get the next
764 * argument (and arguments must be gotten sequentially).
766 #define GETARG(type) \
767 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
768 (nextarg++, va_arg(ap, type)))
771 * To extend shorts properly, we need both signed and unsigned
772 * argument extraction methods.
774 #define SARG() \
775 (flags&LONGINT ? GETARG(long) : \
776 flags&SHORTINT ? (long)(short)GETARG(int) : \
777 flags&CHARINT ? (long)(signed char)GETARG(int) : \
778 (long)GETARG(int))
779 #define UARG() \
780 (flags&LONGINT ? GETARG(u_long) : \
781 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
782 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
783 (u_long)GETARG(u_int))
784 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
785 #define SJARG() \
786 (flags&INTMAXT ? GETARG(intmax_t) : \
787 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
788 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
789 (intmax_t)GETARG(long long))
790 #define UJARG() \
791 (flags&INTMAXT ? GETARG(uintmax_t) : \
792 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
793 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
794 (uintmax_t)GETARG(unsigned long long))
797 * Get * arguments, including the form *nn$. Preserve the nextarg
798 * that the argument can be gotten once the type is determined.
800 #define GETASTER(val) \
801 n2 = 0; \
802 cp = fmt; \
803 while (is_digit(*cp)) { \
804 n2 = 10 * n2 + to_digit(*cp); \
805 cp++; \
807 if (*cp == '$') { \
808 int hold = nextarg; \
809 if (argtable == NULL) { \
810 argtable = statargtable; \
811 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
812 goto oomem; \
814 nextarg = n2; \
815 val = GETARG (int); \
816 nextarg = hold; \
817 fmt = ++cp; \
818 } else { \
819 val = GETARG (int); \
822 _DIAGASSERT(fp != NULL);
823 _DIAGASSERT(fmt0 != NULL);
825 _SET_ORIENTATION(fp, -1);
827 thousands_sep = '\0';
828 grouping = NULL;
829 #ifndef NO_FLOATING_POINT
830 decimal_point = localeconv_l(loc)->decimal_point;
831 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
832 ndig = -1; /* XXX gcc */
833 #endif
834 convbuf = NULL;
835 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
836 if (cantwrite(fp)) {
837 errno = EBADF;
838 return END_OF_FILE;
841 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
842 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
843 __sfileno(fp) != -1)
844 return __sbprintf(fp, loc, fmt0, ap);
846 fmt = (CHAR_T *)__UNCONST(fmt0);
847 argtable = NULL;
848 nextarg = 1;
849 va_copy(orgap, ap);
850 #ifdef NARROW
851 uio.uio_iov = iovp = iov;
852 uio.uio_resid = 0;
853 uio.uio_iovcnt = 0;
854 #endif
855 ret = 0;
858 * Scan the format for conversions (`%' character).
860 for (;;) {
861 const CHAR_T *result;
863 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
864 continue;
865 _DIAGASSERT(__type_fit(int, fmt - cp));
866 if ((n = (int)(fmt - cp)) != 0) {
867 if ((unsigned)ret + n > INT_MAX) {
868 ret = END_OF_FILE;
869 goto error;
871 PRINT(cp, n);
872 ret += n;
874 if (ch == '\0')
875 goto done;
876 fmt++; /* skip over '%' */
878 flags = 0;
879 dprec = 0;
880 width = 0;
881 prec = -1;
882 sign = '\0';
883 ox[1] = '\0';
884 #ifndef NO_FLOATING_POINT
885 expchar = '\0';
886 lead = 0;
887 nseps = nrepeats = 0;
888 #endif
889 ulval = 0;
890 ujval = 0;
891 xdigs = NULL;
893 rflag: ch = *fmt++;
894 reswitch: switch (ch) {
895 case ' ':
897 * ``If the space and + flags both appear, the space
898 * flag will be ignored.''
899 * -- ANSI X3J11
901 if (!sign)
902 sign = ' ';
903 goto rflag;
904 case '#':
905 flags |= ALT;
906 goto rflag;
907 case '*':
909 * ``A negative field width argument is taken as a
910 * - flag followed by a positive field width.''
911 * -- ANSI X3J11
912 * They don't exclude field widths read from args.
914 GETASTER (width);
915 if (width >= 0)
916 goto rflag;
917 width = -width;
918 /* FALLTHROUGH */
919 case '-':
920 flags |= LADJUST;
921 goto rflag;
922 case '+':
923 sign = '+';
924 goto rflag;
925 case '\'':
926 flags |= GROUPING;
927 thousands_sep = *(localeconv_l(loc)->thousands_sep);
928 grouping = localeconv_l(loc)->grouping;
929 /* If the locale doesn't define the above, use sane
930 * defaults - otherwise silly things happen! */
931 if (thousands_sep == 0)
932 thousands_sep = ',';
933 if (!grouping || !*grouping)
934 grouping = "\3";
935 goto rflag;
936 case '.':
937 if ((ch = *fmt++) == '*') {
938 GETASTER (prec);
939 goto rflag;
941 prec = 0;
942 while (is_digit(ch)) {
943 prec = 10 * prec + to_digit(ch);
944 ch = *fmt++;
946 goto reswitch;
947 case '0':
949 * ``Note that 0 is taken as a flag, not as the
950 * beginning of a field width.''
951 * -- ANSI X3J11
953 flags |= ZEROPAD;
954 goto rflag;
955 case '1': case '2': case '3': case '4':
956 case '5': case '6': case '7': case '8': case '9':
957 n = 0;
958 do {
959 n = 10 * n + to_digit(ch);
960 ch = *fmt++;
961 } while (is_digit(ch));
962 if (ch == '$') {
963 nextarg = n;
964 if (argtable == NULL) {
965 argtable = statargtable;
966 if (__find_arguments(fmt0, orgap,
967 &argtable) == -1)
968 goto oomem;
970 goto rflag;
972 width = n;
973 goto reswitch;
974 #ifndef NO_FLOATING_POINT
975 case 'L':
976 flags |= LONGDBL;
977 goto rflag;
978 #endif
979 case 'h':
980 if (flags & SHORTINT) {
981 flags &= ~SHORTINT;
982 flags |= CHARINT;
983 } else
984 flags |= SHORTINT;
985 goto rflag;
986 case 'j':
987 flags |= INTMAXT;
988 goto rflag;
989 case 'l':
990 if (flags & LONGINT) {
991 flags &= ~LONGINT;
992 flags |= LLONGINT;
993 } else
994 flags |= LONGINT;
995 goto rflag;
996 case 'q':
997 flags |= LLONGINT; /* not necessarily */
998 goto rflag;
999 case 't':
1000 flags |= PTRDIFFT;
1001 goto rflag;
1002 case 'z':
1003 flags |= SIZET;
1004 goto rflag;
1005 case 'C':
1006 flags |= LONGINT;
1007 /*FALLTHROUGH*/
1008 case 'c':
1009 #ifdef NARROW
1010 if (flags & LONGINT) {
1011 static const mbstate_t initial;
1012 mbstate_t mbs;
1013 size_t mbseqlen;
1015 mbs = initial;
1016 mbseqlen = wcrtomb_l(buf,
1017 (wchar_t)GETARG(wint_t), &mbs, loc);
1018 if (mbseqlen == (size_t)-1) {
1019 fp->_flags |= __SERR;
1020 goto error;
1022 size = (int)mbseqlen;
1023 } else {
1024 *buf = GETARG(int);
1025 size = 1;
1027 #else
1028 if (flags & LONGINT)
1029 *buf = (wchar_t)GETARG(wint_t);
1030 else
1031 *buf = (wchar_t)btowc_l(GETARG(int), loc);
1032 size = 1;
1033 #endif
1034 result = buf;
1035 sign = '\0';
1036 break;
1037 case 'D':
1038 flags |= LONGINT;
1039 /*FALLTHROUGH*/
1040 case 'd':
1041 case 'i':
1042 if (flags & INTMAX_SIZE) {
1043 ujval = SJARG();
1044 if ((intmax_t)ujval < 0) {
1045 ujval = -ujval;
1046 sign = '-';
1048 } else {
1049 ulval = SARG();
1050 if ((long)ulval < 0) {
1051 ulval = -ulval;
1052 sign = '-';
1055 base = 10;
1056 goto number;
1057 #ifndef NO_FLOATING_POINT
1058 #ifdef WIDE_DOUBLE
1059 case 'a':
1060 case 'A':
1061 if (ch == 'a') {
1062 ox[1] = 'x';
1063 xdigs = xdigs_lower;
1064 expchar = 'p';
1065 } else {
1066 ox[1] = 'X';
1067 xdigs = xdigs_upper;
1068 expchar = 'P';
1070 if (prec >= 0)
1071 prec++;
1072 if (flags & LONGDBL) {
1073 fparg.ldbl = GETARG(long double);
1074 dtoaresult =
1075 __hldtoa(fparg.ldbl, xdigs, prec,
1076 &expt, &signflag, &dtoaend);
1077 } else {
1078 fparg.dbl = GETARG(double);
1079 dtoaresult =
1080 __hdtoa(fparg.dbl, xdigs, prec,
1081 &expt, &signflag, &dtoaend);
1083 if (dtoaresult == NULL)
1084 goto oomem;
1086 if (prec < 0) {
1087 _DIAGASSERT(__type_fit(int,
1088 dtoaend - dtoaresult));
1089 prec = (int)(dtoaend - dtoaresult);
1091 if (expt == INT_MAX)
1092 ox[1] = '\0';
1093 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult));
1094 ndig = (int)(dtoaend - dtoaresult);
1095 if (convbuf != NULL)
1096 free(convbuf);
1097 #ifndef NARROW
1098 result = convbuf = __mbsconv(dtoaresult, -1, loc);
1099 #else
1100 /*XXX inefficient*/
1101 result = convbuf = strdup(dtoaresult);
1102 #endif
1103 if (result == NULL)
1104 goto oomem;
1105 __freedtoa(dtoaresult);
1106 goto fp_common;
1107 case 'e':
1108 case 'E':
1109 expchar = ch;
1110 if (prec < 0) /* account for digit before decpt */
1111 prec = DEFPREC + 1;
1112 else
1113 prec++;
1114 goto fp_begin;
1115 case 'f':
1116 case 'F':
1117 expchar = '\0';
1118 goto fp_begin;
1119 case 'g':
1120 case 'G':
1121 expchar = ch - ('g' - 'e');
1122 if (prec == 0)
1123 prec = 1;
1124 fp_begin:
1125 if (prec < 0)
1126 prec = DEFPREC;
1127 if (flags & LONGDBL) {
1128 fparg.ldbl = GETARG(long double);
1129 dtoaresult =
1130 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
1131 &expt, &signflag, &dtoaend);
1132 } else {
1133 fparg.dbl = GETARG(double);
1134 dtoaresult =
1135 __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
1136 &expt, &signflag, &dtoaend);
1137 if (expt == 9999)
1138 expt = INT_MAX;
1140 if (dtoaresult == NULL)
1141 goto oomem;
1142 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult));
1143 ndig = (int)(dtoaend - dtoaresult);
1144 if (convbuf != NULL)
1145 free(convbuf);
1146 #ifndef NARROW
1147 result = convbuf = __mbsconv(dtoaresult, -1, loc);
1148 #else
1149 /*XXX inefficient*/
1150 result = convbuf = strdup(dtoaresult);
1151 #endif
1152 if (result == NULL)
1153 goto oomem;
1154 __freedtoa(dtoaresult);
1155 fp_common:
1156 if (signflag)
1157 sign = '-';
1158 if (expt == INT_MAX) { /* inf or nan */
1159 if (*result == 'N') {
1160 result = (ch >= 'a') ? STRCONST("nan") :
1161 STRCONST("NAN");
1162 sign = '\0';
1163 } else
1164 result = (ch >= 'a') ? STRCONST("inf") :
1165 STRCONST("INF");
1166 size = 3;
1167 flags &= ~ZEROPAD;
1168 break;
1170 #else
1171 case 'e':
1172 case 'E':
1173 case 'f':
1174 case 'F':
1175 case 'g':
1176 case 'G':
1177 if (prec == -1) {
1178 prec = DEFPREC;
1179 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
1180 prec = 1;
1183 if (flags & LONGDBL) {
1184 _double = (double) GETARG(long double);
1185 } else {
1186 _double = GETARG(double);
1189 /* do this before tricky precision changes */
1190 if (isinf(_double)) {
1191 if (_double < 0)
1192 sign = '-';
1193 if (ch == 'E' || ch == 'F' || ch == 'G')
1194 result = STRCONST("INF");
1195 else
1196 result = STRCONST("inf");
1197 size = 3;
1198 flags &= ~ZEROPAD;
1199 break;
1201 if (isnan(_double)) {
1202 if (ch == 'E' || ch == 'F' || ch == 'G')
1203 result = STRCONST("NAN");
1204 else
1205 result = STRCONST("nan");
1206 size = 3;
1207 flags &= ~ZEROPAD;
1208 break;
1211 flags |= FPT;
1212 dtoaresult = cvt(_double, prec, flags, &softsign,
1213 &expt, ch, &ndig);
1214 if (dtoaresult == NULL)
1215 goto oomem;
1216 if (convbuf != NULL)
1217 free(convbuf);
1218 #ifndef NARROW
1219 result = convbuf = __mbsconv(dtoaresult, -1, loc);
1220 #else
1221 /*XXX inefficient*/
1222 result = convbuf = strdup(dtoaresult);
1223 #endif
1224 if (result == NULL)
1225 goto oomem;
1226 __freedtoa(dtoaresult);
1227 if (softsign)
1228 sign = '-';
1229 #endif
1230 flags |= FPT;
1231 if (ch == 'g' || ch == 'G') {
1232 if (expt > -4 && expt <= prec) {
1233 /* Make %[gG] smell like %[fF] */
1234 expchar = '\0';
1235 if (flags & ALT)
1236 prec -= expt;
1237 else
1238 prec = ndig - expt;
1239 if (prec < 0)
1240 prec = 0;
1241 } else {
1243 * Make %[gG] smell like %[eE], but
1244 * trim trailing zeroes if no # flag.
1246 if (!(flags & ALT))
1247 prec = ndig;
1250 if (expchar) {
1251 expsize = exponent(expstr, expt - 1, expchar);
1252 size = expsize + prec;
1253 if (prec > 1 || flags & ALT)
1254 ++size;
1255 } else {
1256 /* space for digits before decimal point */
1257 if (expt > 0)
1258 size = expt;
1259 else /* "0" */
1260 size = 1;
1261 /* space for decimal pt and following digits */
1262 if (prec || flags & ALT)
1263 size += prec + 1;
1264 if (grouping && expt > 0) {
1265 /* space for thousands' grouping */
1266 nseps = nrepeats = 0;
1267 lead = expt;
1268 while ((unsigned char)*grouping
1269 != (unsigned char)CHAR_MAX) {
1270 if (lead <= *grouping)
1271 break;
1272 lead -= *grouping;
1273 if (*(grouping+1)) {
1274 nseps++;
1275 grouping++;
1276 } else
1277 nrepeats++;
1279 size += nseps + nrepeats;
1280 } else
1281 lead = expt;
1283 break;
1284 #endif /* !NO_FLOATING_POINT */
1285 case 'n':
1287 * Assignment-like behavior is specified if the
1288 * value overflows or is otherwise unrepresentable.
1289 * C99 says to use `signed char' for %hhn conversions.
1291 if (flags & LLONGINT)
1292 *GETARG(long long *) = ret;
1293 else if (flags & SIZET)
1294 *GETARG(ssize_t *) = (ssize_t)ret;
1295 else if (flags & PTRDIFFT)
1296 *GETARG(ptrdiff_t *) = ret;
1297 else if (flags & INTMAXT)
1298 *GETARG(intmax_t *) = ret;
1299 else if (flags & LONGINT)
1300 *GETARG(long *) = ret;
1301 else if (flags & SHORTINT)
1302 *GETARG(short *) = ret;
1303 else if (flags & CHARINT)
1304 *GETARG(signed char *) = ret;
1305 else
1306 *GETARG(int *) = ret;
1307 continue; /* no output */
1308 case 'O':
1309 flags |= LONGINT;
1310 /*FALLTHROUGH*/
1311 case 'o':
1312 if (flags & INTMAX_SIZE)
1313 ujval = UJARG();
1314 else
1315 ulval = UARG();
1316 base = 8;
1317 goto nosign;
1318 case 'p':
1320 * ``The argument shall be a pointer to void. The
1321 * value of the pointer is converted to a sequence
1322 * of printable characters, in an implementation-
1323 * defined manner.''
1324 * -- ANSI X3J11
1326 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1327 base = 16;
1328 xdigs = xdigs_lower;
1329 flags = flags | INTMAXT;
1330 ox[1] = 'x';
1331 goto nosign;
1332 case 'S':
1333 flags |= LONGINT;
1334 /*FALLTHROUGH*/
1335 case 's':
1336 if ((flags & LONGINT) != MULTI) {
1337 if ((result = GETARG(CHAR_T *)) == NULL)
1338 result = STRCONST("(null)");
1339 } else {
1340 MCHAR_T *mc;
1342 if (convbuf != NULL)
1343 free(convbuf);
1344 if ((mc = GETARG(MCHAR_T *)) == NULL)
1345 result = STRCONST("(null)");
1346 else {
1347 convbuf = SCONV(mc, prec, loc);
1348 if (convbuf == NULL) {
1349 fp->_flags |= __SERR;
1350 goto error;
1352 result = convbuf;
1356 if (prec >= 0) {
1358 * can't use STRLEN; can only look for the
1359 * NUL in the first `prec' characters, and
1360 * STRLEN() will go further.
1362 CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
1364 if (p != NULL) {
1365 _DIAGASSERT(__type_fit(int,
1366 p - result));
1367 size = (int)(p - result);
1368 if (size > prec)
1369 size = prec;
1370 } else
1371 size = prec;
1372 } else {
1373 size_t rlen = STRLEN(result);
1374 _DIAGASSERT(__type_fit(int, rlen));
1375 size = (int)rlen;
1377 sign = '\0';
1378 break;
1379 case 'U':
1380 flags |= LONGINT;
1381 /*FALLTHROUGH*/
1382 case 'u':
1383 if (flags & INTMAX_SIZE)
1384 ujval = UJARG();
1385 else
1386 ulval = UARG();
1387 base = 10;
1388 goto nosign;
1389 case 'X':
1390 xdigs = xdigs_upper;
1391 goto hex;
1392 case 'x':
1393 xdigs = xdigs_lower;
1394 hex:
1395 if (flags & INTMAX_SIZE)
1396 ujval = UJARG();
1397 else
1398 ulval = UARG();
1399 base = 16;
1400 /* leading 0x/X only if non-zero */
1401 if (flags & ALT &&
1402 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1403 ox[1] = ch;
1405 flags &= ~GROUPING;
1406 /* unsigned conversions */
1407 nosign: sign = '\0';
1409 * ``... diouXx conversions ... if a precision is
1410 * specified, the 0 flag will be ignored.''
1411 * -- ANSI X3J11
1413 number: if ((dprec = prec) >= 0)
1414 flags &= ~ZEROPAD;
1417 * ``The result of converting a zero value with an
1418 * explicit precision of zero is no characters.''
1419 * -- ANSI X3J11
1421 * ``The C Standard is clear enough as is. The call
1422 * printf("%#.0o", 0) should print 0.''
1423 * -- Defect Report #151
1425 result = cp = buf + BUF;
1426 if (flags & INTMAX_SIZE) {
1427 if (ujval != 0 || prec != 0 ||
1428 (flags & ALT && base == 8))
1429 result = __ujtoa(ujval, cp, base,
1430 flags & ALT, xdigs,
1431 flags & GROUPING, thousands_sep,
1432 grouping);
1433 } else {
1434 if (ulval != 0 || prec != 0 ||
1435 (flags & ALT && base == 8))
1436 result = __ultoa(ulval, cp, base,
1437 flags & ALT, xdigs,
1438 flags & GROUPING, thousands_sep,
1439 grouping);
1441 _DIAGASSERT(__type_fit(int, buf + BUF - result));
1442 size = (int)(buf + BUF - result);
1443 if (size > BUF) /* should never happen */
1444 abort();
1445 break;
1446 default: /* "%?" prints ?, unless ? is NUL */
1447 if (ch == '\0')
1448 goto done;
1449 /* pretend it was %c with argument ch */
1450 *buf = ch;
1451 result = buf;
1452 size = 1;
1453 sign = '\0';
1454 break;
1458 * All reasonable formats wind up here. At this point, `result'
1459 * points to a string which (if not flags&LADJUST) should be
1460 * padded out to `width' places. If flags&ZEROPAD, it should
1461 * first be prefixed by any sign or other prefix; otherwise,
1462 * it should be blank padded before the prefix is emitted.
1463 * After any left-hand padding and prefixing, emit zeroes
1464 * required by a decimal [diouxX] precision, then print the
1465 * string proper, then emit zeroes required by any leftover
1466 * floating precision; finally, if LADJUST, pad with blanks.
1468 * Compute actual size, so we know how much to pad.
1469 * size excludes decimal prec; realsz includes it.
1471 realsz = dprec > size ? dprec : size;
1472 if (sign)
1473 realsz++;
1474 if (ox[1])
1475 realsz += 2;
1477 prsize = width > realsz ? width : realsz;
1478 if ((unsigned)ret + prsize > INT_MAX) {
1479 ret = END_OF_FILE;
1480 goto error;
1483 /* right-adjusting blank padding */
1484 if ((flags & (LADJUST|ZEROPAD)) == 0)
1485 PAD(width - realsz, blanks);
1487 /* prefix */
1488 if (sign)
1489 PRINT(&sign, 1);
1491 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1492 ox[0] = '0';
1493 PRINT(ox, 2);
1496 /* right-adjusting zero padding */
1497 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1498 PAD(width - realsz, zeroes);
1500 /* leading zeroes from decimal precision */
1501 PAD(dprec - size, zeroes);
1503 /* the string or number proper */
1504 #ifndef NO_FLOATING_POINT
1505 if ((flags & FPT) == 0) {
1506 PRINT(result, size);
1507 } else { /* glue together f_p fragments */
1508 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1509 if (expt <= 0) {
1510 PRINT(zeroes, 1);
1511 if (prec || flags & ALT)
1512 PRINT(decimal_point, 1);
1513 PAD(-expt, zeroes);
1514 /* already handled initial 0's */
1515 prec += expt;
1516 } else {
1517 PRINTANDPAD(result, convbuf + ndig,
1518 lead, zeroes);
1519 result += lead;
1520 if (grouping) {
1521 while (nseps>0 || nrepeats>0) {
1522 if (nrepeats > 0)
1523 nrepeats--;
1524 else {
1525 grouping--;
1526 nseps--;
1528 PRINT(&thousands_sep,
1530 PRINTANDPAD(result,
1531 convbuf + ndig,
1532 *grouping, zeroes);
1533 result += *grouping;
1535 if (result > convbuf + ndig)
1536 result = convbuf + ndig;
1538 if (prec || flags & ALT) {
1539 buf[0] = *decimal_point;
1540 PRINT(buf, 1);
1543 PRINTANDPAD(result, convbuf + ndig, prec,
1544 zeroes);
1545 } else { /* %[eE] or sufficiently long %[gG] */
1546 if (prec > 1 || flags & ALT) {
1547 buf[0] = *result++;
1548 buf[1] = *decimal_point;
1549 PRINT(buf, 2);
1550 PRINT(result, ndig-1);
1551 PAD(prec - ndig, zeroes);
1552 } else /* XeYYY */
1553 PRINT(result, 1);
1554 PRINT(expstr, expsize);
1557 #else
1558 PRINT(result, size);
1559 #endif
1560 /* left-adjusting padding (always blank) */
1561 if (flags & LADJUST)
1562 PAD(width - realsz, blanks);
1564 /* finally, adjust ret */
1565 ret += prsize;
1566 FLUSH();
1568 done:
1569 FLUSH();
1570 error:
1571 va_end(orgap);
1572 if (convbuf != NULL)
1573 free(convbuf);
1574 if (__sferror(fp))
1575 ret = END_OF_FILE;
1576 if ((argtable != NULL) && (argtable != statargtable))
1577 free (argtable);
1578 return ret;
1579 /* NOTREACHED */
1580 oomem:
1581 errno = ENOMEM;
1582 ret = END_OF_FILE;
1583 goto error;
1587 * Find all arguments when a positional parameter is encountered. Returns a
1588 * table, indexed by argument number, of pointers to each arguments. The
1589 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1590 * It will be replaces with a malloc-ed one if it overflows.
1592 static int
1593 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
1595 CHAR_T *fmt; /* format string */
1596 int ch; /* character from fmt */
1597 size_t n, n2; /* handy index (short term usage) */
1598 CHAR_T *cp; /* handy char pointer (short term usage) */
1599 int flags; /* flags as above */
1600 enum typeid *typetable; /* table of types */
1601 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1602 size_t tablesize; /* current size of type table */
1603 size_t tablemax; /* largest used index in table */
1604 size_t nextarg; /* 1-based argument index */
1605 size_t nitems; /* number of items we picked from the stack */
1608 * Add an argument type to the table, expanding if necessary.
1609 * Check for overflow.
1611 #define ADDTYPE(type) \
1612 do { \
1613 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \
1614 if (typetable != stattypetable) \
1615 free(typetable); \
1616 return -1; \
1618 if (nextarg >= tablesize) \
1619 if (__grow_type_table(nextarg, &typetable, \
1620 &tablesize) == -1) \
1621 return -1; \
1622 if (nextarg > tablemax) \
1623 tablemax = nextarg; \
1624 typetable[nextarg++] = type; \
1625 nitems++; \
1626 } while (/*CONSTCOND*/0)
1628 #define ADDSARG() \
1629 do { \
1630 if (flags & INTMAXT) \
1631 ADDTYPE(T_INTMAXT); \
1632 else if (flags & SIZET) \
1633 ADDTYPE(T_SSIZET); \
1634 else if (flags & PTRDIFFT) \
1635 ADDTYPE(T_PTRDIFFT); \
1636 else if (flags & LLONGINT) \
1637 ADDTYPE(T_LLONG); \
1638 else if (flags & LONGINT) \
1639 ADDTYPE(T_LONG); \
1640 else \
1641 ADDTYPE(T_INT); \
1642 } while (/*CONSTCOND*/0)
1644 #define ADDUARG() \
1645 do { \
1646 if (flags & INTMAXT) \
1647 ADDTYPE(T_UINTMAXT); \
1648 else if (flags & SIZET) \
1649 ADDTYPE(T_SIZET); \
1650 else if (flags & PTRDIFFT) \
1651 ADDTYPE(T_PTRDIFFT); \
1652 else if (flags & LLONGINT) \
1653 ADDTYPE(T_U_LLONG); \
1654 else if (flags & LONGINT) \
1655 ADDTYPE(T_U_LONG); \
1656 else \
1657 ADDTYPE(T_U_INT); \
1658 } while (/*CONSTCOND*/0)
1660 * Add * arguments to the type array.
1662 #define ADDASTER() \
1663 n2 = 0; \
1664 cp = fmt; \
1665 while (is_digit(*cp)) { \
1666 n2 = 10 * n2 + to_digit(*cp); \
1667 cp++; \
1669 if (*cp == '$') { \
1670 size_t hold = nextarg; \
1671 nextarg = n2; \
1672 ADDTYPE(T_INT); \
1673 nextarg = hold; \
1674 fmt = ++cp; \
1675 } else { \
1676 ADDTYPE(T_INT); \
1678 fmt = (CHAR_T *)__UNCONST(fmt0);
1679 memset(stattypetable, 0, sizeof(stattypetable));
1680 typetable = stattypetable;
1681 tablesize = STATIC_ARG_TBL_SIZE;
1682 tablemax = 0;
1683 nextarg = 1;
1684 nitems = 1;
1687 * Scan the format for conversions (`%' character).
1689 for (;;) {
1690 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1691 /* void */;
1692 if (ch == '\0')
1693 goto done;
1694 fmt++; /* skip over '%' */
1696 flags = 0;
1698 rflag: ch = *fmt++;
1699 reswitch: switch (ch) {
1700 case ' ':
1701 case '#':
1702 goto rflag;
1703 case '*':
1704 ADDASTER ();
1705 goto rflag;
1706 case '-':
1707 case '+':
1708 case '\'':
1709 goto rflag;
1710 case '.':
1711 if ((ch = *fmt++) == '*') {
1712 ADDASTER ();
1713 goto rflag;
1715 while (is_digit(ch)) {
1716 ch = *fmt++;
1718 goto reswitch;
1719 case '0':
1720 goto rflag;
1721 case '1': case '2': case '3': case '4':
1722 case '5': case '6': case '7': case '8': case '9':
1723 n = 0;
1724 do {
1725 n = 10 * n + to_digit(ch);
1726 ch = *fmt++;
1727 } while (is_digit(ch));
1728 if (ch == '$') {
1729 nextarg = n;
1730 goto rflag;
1732 goto reswitch;
1733 #ifndef NO_FLOATING_POINT
1734 case 'L':
1735 flags |= LONGDBL;
1736 goto rflag;
1737 #endif
1738 case 'h':
1739 if (flags & SHORTINT) {
1740 flags &= ~SHORTINT;
1741 flags |= CHARINT;
1742 } else
1743 flags |= SHORTINT;
1744 goto rflag;
1745 case 'j':
1746 flags |= INTMAXT;
1747 goto rflag;
1748 case 'l':
1749 if (flags & LONGINT) {
1750 flags &= ~LONGINT;
1751 flags |= LLONGINT;
1752 } else
1753 flags |= LONGINT;
1754 goto rflag;
1755 case 'q':
1756 flags |= LLONGINT; /* not necessarily */
1757 goto rflag;
1758 case 't':
1759 flags |= PTRDIFFT;
1760 goto rflag;
1761 case 'z':
1762 flags |= SIZET;
1763 goto rflag;
1764 case 'C':
1765 flags |= LONGINT;
1766 /*FALLTHROUGH*/
1767 case 'c':
1768 if (flags & LONGINT)
1769 ADDTYPE(T_WINT);
1770 else
1771 ADDTYPE(T_INT);
1772 break;
1773 case 'D':
1774 flags |= LONGINT;
1775 /*FALLTHROUGH*/
1776 case 'd':
1777 case 'i':
1778 ADDSARG();
1779 break;
1780 #ifndef NO_FLOATING_POINT
1781 case 'a':
1782 case 'A':
1783 case 'e':
1784 case 'E':
1785 case 'f':
1786 case 'g':
1787 case 'G':
1788 if (flags & LONGDBL)
1789 ADDTYPE(T_LONG_DOUBLE);
1790 else
1791 ADDTYPE(T_DOUBLE);
1792 break;
1793 #endif /* !NO_FLOATING_POINT */
1794 case 'n':
1795 if (flags & INTMAXT)
1796 ADDTYPE(TP_INTMAXT);
1797 else if (flags & PTRDIFFT)
1798 ADDTYPE(TP_PTRDIFFT);
1799 else if (flags & SIZET)
1800 ADDTYPE(TP_SIZET);
1801 else if (flags & LLONGINT)
1802 ADDTYPE(TP_LLONG);
1803 else if (flags & LONGINT)
1804 ADDTYPE(TP_LONG);
1805 else if (flags & SHORTINT)
1806 ADDTYPE(TP_SHORT);
1807 else if (flags & CHARINT)
1808 ADDTYPE(TP_SCHAR);
1809 else
1810 ADDTYPE(TP_INT);
1811 continue; /* no output */
1812 case 'O':
1813 flags |= LONGINT;
1814 /*FALLTHROUGH*/
1815 case 'o':
1816 ADDUARG();
1817 break;
1818 case 'p':
1819 ADDTYPE(TP_VOID);
1820 break;
1821 case 'S':
1822 flags |= LONGINT;
1823 /*FALLTHROUGH*/
1824 case 's':
1825 if (flags & LONGINT)
1826 ADDTYPE(TP_WCHAR);
1827 else
1828 ADDTYPE(TP_CHAR);
1829 break;
1830 case 'U':
1831 flags |= LONGINT;
1832 /*FALLTHROUGH*/
1833 case 'u':
1834 case 'X':
1835 case 'x':
1836 ADDUARG();
1837 break;
1838 default: /* "%?" prints ?, unless ? is NUL */
1839 if (ch == '\0')
1840 goto done;
1841 break;
1844 done:
1846 * nitems contains the number of arguments we picked from the stack.
1847 * If tablemax is larger, this means that some positional argument,
1848 * tried to pick an argument the number of arguments possibly supplied.
1849 * Since positional arguments are typically used to swap the order of
1850 * the printf arguments and not to pick random arguments from strange
1851 * positions in the stack, we assume that if the positional argument
1852 * is trying to pick beyond the end of arguments, then this is wrong.
1853 * Alternatively we could find a way to figure out when va_arg() runs
1854 * out, but how to do that?
1856 if (nitems < tablemax) {
1857 if (typetable != stattypetable)
1858 free(typetable);
1859 return -1;
1862 * Build the argument table.
1864 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1865 *argtable = malloc(sizeof(**argtable) * (tablemax + 1));
1866 if (*argtable == NULL) {
1867 free(typetable);
1868 return -1;
1872 (*argtable) [0].intarg = 0;
1873 for (n = 1; n <= tablemax; n++) {
1874 switch (typetable [n]) {
1875 case T_UNUSED: /* whoops! */
1876 (*argtable) [n].intarg = va_arg (ap, int);
1877 break;
1878 case TP_SCHAR:
1879 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1880 break;
1881 case TP_SHORT:
1882 (*argtable) [n].pshortarg = va_arg (ap, short *);
1883 break;
1884 case T_INT:
1885 (*argtable) [n].intarg = va_arg (ap, int);
1886 break;
1887 case T_U_INT:
1888 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1889 break;
1890 case TP_INT:
1891 (*argtable) [n].pintarg = va_arg (ap, int *);
1892 break;
1893 case T_LONG:
1894 (*argtable) [n].longarg = va_arg (ap, long);
1895 break;
1896 case T_U_LONG:
1897 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1898 break;
1899 case TP_LONG:
1900 (*argtable) [n].plongarg = va_arg (ap, long *);
1901 break;
1902 case T_LLONG:
1903 (*argtable) [n].longlongarg = va_arg (ap, long long);
1904 break;
1905 case T_U_LLONG:
1906 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1907 break;
1908 case TP_LLONG:
1909 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1910 break;
1911 case T_PTRDIFFT:
1912 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1913 break;
1914 case TP_PTRDIFFT:
1915 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1916 break;
1917 case T_SSIZET:
1918 (*argtable) [n].ssizearg = va_arg (ap, ssize_t);
1919 break;
1920 case T_SIZET:
1921 (*argtable) [n].sizearg = va_arg (ap, size_t);
1922 break;
1923 case TP_SIZET:
1924 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1925 break;
1926 case T_INTMAXT:
1927 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1928 break;
1929 case T_UINTMAXT:
1930 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1931 break;
1932 case TP_INTMAXT:
1933 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1934 break;
1935 case T_DOUBLE:
1936 #ifndef NO_FLOATING_POINT
1937 (*argtable) [n].doublearg = va_arg (ap, double);
1938 #endif
1939 break;
1940 case T_LONG_DOUBLE:
1941 #ifndef NO_FLOATING_POINT
1942 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1943 #endif
1944 break;
1945 case TP_CHAR:
1946 (*argtable) [n].pchararg = va_arg (ap, char *);
1947 break;
1948 case TP_VOID:
1949 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1950 break;
1951 case T_WINT:
1952 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1953 break;
1954 case TP_WCHAR:
1955 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1956 break;
1960 if (typetable != stattypetable)
1961 free (typetable);
1962 return 0;
1966 * Increase the size of the type table.
1968 static int
1969 __grow_type_table (size_t nextarg, enum typeid **typetable, size_t *tablesize)
1971 enum typeid *const oldtable = *typetable;
1972 const size_t oldsize = *tablesize;
1973 enum typeid *newtable;
1974 size_t newsize = oldsize * 2;
1976 if (newsize < nextarg + 1)
1977 newsize = nextarg + 1;
1978 if (oldsize == STATIC_ARG_TBL_SIZE) {
1979 if ((newtable = malloc(newsize * sizeof(*newtable))) == NULL)
1980 return -1;
1981 memcpy(newtable, oldtable, oldsize * sizeof(*newtable));
1982 } else {
1983 newtable = realloc(oldtable, newsize * sizeof(*newtable));
1984 if (newtable == NULL) {
1985 free(oldtable);
1986 return -1;
1989 memset(&newtable[oldsize], 0, (newsize - oldsize) * sizeof(*newtable));
1991 *typetable = newtable;
1992 *tablesize = newsize;
1993 return 0;
1997 #ifndef NO_FLOATING_POINT
1998 #ifndef WIDE_DOUBLE
1999 static char *
2000 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
2001 int *length)
2003 int mode, dsgn;
2004 char *digits, *bp, *rve;
2006 _DIAGASSERT(decpt != NULL);
2007 _DIAGASSERT(length != NULL);
2008 _DIAGASSERT(sign != NULL);
2010 if (ch == 'f') {
2011 mode = 3; /* ndigits after the decimal point */
2012 } else {
2013 /* To obtain ndigits after the decimal point for the 'e'
2014 * and 'E' formats, round to ndigits + 1 significant
2015 * figures.
2017 if (ch == 'e' || ch == 'E') {
2018 ndigits++;
2020 mode = 2; /* ndigits significant digits */
2023 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
2024 if (digits == NULL)
2025 return NULL;
2026 if (dsgn) {
2027 value = -value;
2028 *sign = '-';
2029 } else
2030 *sign = '\000';
2031 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
2032 bp = digits + ndigits;
2033 if (ch == 'f') {
2034 if (*digits == '0' && value)
2035 *decpt = -ndigits + 1;
2036 bp += *decpt;
2038 if (value == 0) /* kludge for __dtoa irregularity */
2039 rve = bp;
2040 while (rve < bp)
2041 *rve++ = '0';
2043 *length = rve - digits;
2044 return digits;
2046 #endif
2048 static int
2049 exponent(CHAR_T *p0, int expo, int fmtch)
2051 CHAR_T *p, *t;
2052 CHAR_T expbuf[MAXEXPDIG];
2054 p = p0;
2055 *p++ = fmtch;
2056 if (expo < 0) {
2057 expo = -expo;
2058 *p++ = '-';
2060 else
2061 *p++ = '+';
2062 t = expbuf + MAXEXPDIG;
2063 if (expo > 9) {
2064 do {
2065 *--t = to_char(expo % 10);
2066 } while ((expo /= 10) > 9);
2067 *--t = to_char(expo);
2068 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
2070 else {
2072 * Exponents for decimal floating point conversions
2073 * (%[eEgG]) must be at least two characters long,
2074 * whereas exponents for hexadecimal conversions can
2075 * be only one character long.
2077 if (fmtch == 'e' || fmtch == 'E')
2078 *p++ = '0';
2079 *p++ = to_char(expo);
2081 _DIAGASSERT(__type_fit(int, p - p0));
2082 return (int)(p - p0);
2084 #endif /* !NO_FLOATING_POINT */