Replace our strtod with the gdtoa package.
[dragonfly.git] / lib / libc / stdio / vfwprintf.c
1 /*-
2  * Copyright (c) 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.24 2005/04/16 22:36:51 das Exp $
37  * $NetBSD: vfwprintf.c,v 1.3 2005/06/15 09:31:27 he Exp $
38  * $DragonFly: src/lib/libc/stdio/vfwprintf.c,v 1.3 2006/03/02 18:05:30 joerg Exp $
39  */
40
41 /*
42  * Actual wprintf innards.
43  *
44  * Avoid making gratuitous changes to this source file; it should be kept
45  * as close as possible to vfprintf.c for ease of maintenance.
46  */
47
48 #include "namespace.h"
49 #include <sys/types.h>
50
51 #include <assert.h>
52 #include <ctype.h>
53 #include <errno.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 <wchar.h>
63 #include <wctype.h>
64
65 #include "un-namespace.h"
66
67 #include "libc_private.h"
68 #include "local.h"
69 #include "priv_stdio.h"
70
71
72 union arg {
73         int                      intarg;
74         unsigned int             uintarg;
75         long                     longarg;
76         unsigned long            ulongarg;
77         long long                longlongarg;
78         unsigned long long       ulonglongarg;
79         ptrdiff_t                ptrdiffarg;
80         size_t                   sizearg;
81         intmax_t                 intmaxarg;
82         uintmax_t                uintmaxarg;
83         void                    *pvoidarg;
84         char                    *pchararg;
85         signed char             *pschararg;
86         short                   *pshortarg;
87         int                     *pintarg;
88         long                    *plongarg;
89         quad_t                  *plonglongarg;
90         ptrdiff_t               *pptrdiffarg;
91         size_t                  *psizearg;
92         intmax_t                *pintmaxarg;
93 #ifndef NO_FLOATING_POINT
94         double                   doublearg;
95         long double              longdoublearg;
96 #endif
97         wint_t                   wintarg;
98         wchar_t                 *pwchararg;
99 };
100
101 /*
102  * Type ids for argument type table.
103  */
104 enum typeid {
105         T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
106         T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
107         T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
108         T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
109         T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
110 };
111
112 static int      __sbprintf(FILE *, const wchar_t *, va_list);
113 static wint_t   __xfputwc(wchar_t, FILE *);
114 static wchar_t  *__ujtoa(uintmax_t, wchar_t *, int, int, const char *, int,
115                     char, const char *);
116 static wchar_t  *__ultoa(u_long, wchar_t *, int, int, const char *, int,
117                     char, const char *);
118 static wchar_t  *__mbsconv(char *, int);
119 static void     __find_arguments(const wchar_t *, va_list, union arg **);
120 static void     __grow_type_table(int, enum typeid **, int *);
121
122 /*
123  * Helper function for `fprintf to unbuffered unix file': creates a
124  * temporary buffer.  We only work on write-only files; this avoids
125  * worries about ungetc buffers and so forth.
126  */
127 static int
128 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
129 {
130         int ret;
131         FILE fake;
132         unsigned char buf[BUFSIZ];
133
134         /* copy the important variables */
135         fake.pub._flags = fp->pub._flags & ~__SNBF;
136         fake.pub._fileno = fp->pub._fileno;
137         fake._cookie = fp->_cookie;
138         fake._write = fp->_write;
139
140         fake._up = fp->_up;
141         fake.fl_mutex = fp->fl_mutex;
142         fake.fl_owner = fp->fl_owner;
143         fake.fl_count = fp->fl_count;
144         memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
145
146         /* set up the buffer */
147         fake._bf._base = fake.pub._p = buf;
148         fake._bf._size = fake.pub._w = sizeof(buf);
149         fake.pub._lbfsize = 0;  /* not actually used, but Just In Case */
150
151         /* do the work, then copy any error status */
152         ret = __vfwprintf_unlocked(&fake, fmt, ap);
153         if (ret >= 0 && __fflush(&fake))
154                 ret = WEOF;
155         if (fake.pub._flags & __SERR)
156                 fp->pub._flags |= __SERR;
157         return (ret);
158 }
159
160 /*
161  * Like __fputwc, but handles fake string (__SSTR) files properly.
162  * File must already be locked.
163  */
164 static wint_t
165 __xfputwc(wchar_t wc, FILE *fp)
166 {
167         static const mbstate_t initial;
168         mbstate_t mbs;
169         char buf[MB_LEN_MAX];
170         struct __suio uio;
171         struct __siov iov;
172         size_t len;
173
174         if ((fp->pub._flags & __SSTR) == 0)
175                 return (__fputwc_unlock(wc, fp));
176
177         mbs = initial;
178         if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
179                 fp->pub._flags |= __SERR;
180                 return (WEOF);
181         }
182         uio.uio_iov = &iov;
183         uio.uio_resid = len;
184         uio.uio_iovcnt = 1;
185         iov.iov_base = buf;
186         iov.iov_len = len;
187         return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
188 }
189
190 /*
191  * Macros for converting digits to letters and vice versa
192  */
193 #define to_digit(c)     ((c) - '0')
194 #define is_digit(c)     ((unsigned)to_digit(c) <= 9)
195 #define to_char(n)      (wchar_t)((n) + '0')
196
197 /*
198  * Convert an unsigned long to ASCII for printf purposes, returning
199  * a pointer to the first character of the string representation.
200  * Octal numbers can be forced to have a leading zero; hex numbers
201  * use the given digits.
202  */
203 static wchar_t *
204 __ultoa(u_long val, wchar_t *endp, int base, int octzero, const char *xdigs,
205         int needgrp, char thousep, const char *grp)
206 {
207         wchar_t *cp = endp;
208         long sval;
209         int ndig;
210
211         /*
212          * Handle the three cases separately, in the hope of getting
213          * better/faster code.
214          */
215         switch (base) {
216         case 10:
217                 if (val < 10) { /* many numbers are 1 digit */
218                         *--cp = to_char(val);
219                         return (cp);
220                 }
221                 ndig = 0;
222                 /*
223                  * On many machines, unsigned arithmetic is harder than
224                  * signed arithmetic, so we do at most one unsigned mod and
225                  * divide; this is sufficient to reduce the range of
226                  * the incoming value to where signed arithmetic works.
227                  */
228                 if (val > LONG_MAX) {
229                         *--cp = to_char(val % 10);
230                         ndig++;
231                         sval = val / 10;
232                 } else
233                         sval = val;
234                 do {
235                         *--cp = to_char(sval % 10);
236                         ndig++;
237                         /*
238                          * If (*grp == CHAR_MAX) then no more grouping
239                          * should be performed.
240                          */
241                         if (needgrp && ndig == *grp && *grp != CHAR_MAX &&
242                             sval > 9) {
243                                 *--cp = thousep;
244                                 ndig = 0;
245                                 /*
246                                  * If (*(grp+1) == '\0') then we have to
247                                  * use *grp character (last grouping rule)
248                                  * for all next cases
249                                  */
250                                 if (*(grp+1) != '\0')
251                                         grp++;
252                         }
253                         sval /= 10;
254                 } while (sval != 0);
255                 break;
256
257         case 8:
258                 do {
259                         *--cp = to_char(val & 7);
260                         val >>= 3;
261                 } while (val);
262                 if (octzero && *cp != '0')
263                         *--cp = '0';
264                 break;
265
266         case 16:
267                 do {
268                         *--cp = xdigs[(size_t)val & 15];
269                         val >>= 4;
270                 } while (val);
271                 break;
272
273         default:                        /* oops */
274                 abort();
275         }
276         return (cp);
277 }
278
279 /* Identical to __ultoa, but for intmax_t. */
280 static wchar_t *
281 __ujtoa(uintmax_t val, wchar_t *endp, int base, int octzero,
282         const char *xdigs, int needgrp, char thousep, const char *grp)
283 {
284         wchar_t *cp = endp;
285         intmax_t sval;
286         int ndig;
287
288         /* quick test for small values; __ultoa is typically much faster */
289         /* (perhaps instead we should run until small, then call __ultoa?) */
290         if (val <= ULONG_MAX)
291                 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
292                     needgrp, thousep, grp));
293         switch (base) {
294         case 10:
295                 if (val < 10) {
296                         *--cp = to_char(val % 10);
297                         return (cp);
298                 }
299                 ndig = 0;
300                 if (val > INTMAX_MAX) {
301                         *--cp = to_char(val % 10);
302                         ndig++;
303                         sval = val / 10;
304                 } else
305                         sval = val;
306                 do {
307                         *--cp = to_char(sval % 10);
308                         ndig++;
309                         /*
310                          * If (*grp == CHAR_MAX) then no more grouping
311                          * should be performed.
312                          */
313                         if (needgrp && *grp != CHAR_MAX && ndig == *grp &&
314                             sval > 9) {
315                                 *--cp = thousep;
316                                 ndig = 0;
317                                 /*
318                                  * If (*(grp+1) == '\0') then we have to
319                                  * use *grp character (last grouping rule)
320                                  * for all next cases
321                                  */
322                                 if (*(grp+1) != '\0')
323                                         grp++;
324                         }
325                         sval /= 10;
326                 } while (sval != 0);
327                 break;
328
329         case 8:
330                 do {
331                         *--cp = to_char(val & 7);
332                         val >>= 3;
333                 } while (val);
334                 if (octzero && *cp != '0')
335                         *--cp = '0';
336                 break;
337
338         case 16:
339                 do {
340                         *--cp = xdigs[(size_t)val & 15];
341                         val >>= 4;
342                 } while (val);
343                 break;
344
345         default:
346                 abort();
347         }
348         return (cp);
349 }
350
351 /*
352  * Convert a multibyte character string argument for the %s format to a wide
353  * string representation. ``prec'' specifies the maximum number of bytes
354  * to output. If ``prec'' is greater than or equal to zero, we can't assume
355  * that the multibyte char. string ends in a null character.
356  */
357 static wchar_t *
358 __mbsconv(char *mbsarg, int prec)
359 {
360         static const mbstate_t initial;
361         mbstate_t mbs;
362         wchar_t *convbuf, *wcp;
363         const char *p;
364         size_t insize, nchars, nconv;
365
366         if (mbsarg == NULL)
367                 return (NULL);
368
369         /*
370          * Supplied argument is a multibyte string; convert it to wide
371          * characters first.
372          */
373         if (prec >= 0) {
374                 /*
375                  * String is not guaranteed to be NUL-terminated. Find the
376                  * number of characters to print.
377                  */
378                 p = mbsarg;
379                 insize = nchars = nconv = 0;
380                 mbs = initial;
381                 while (nchars != (size_t)prec) {
382                         nconv = mbrlen(p, MB_CUR_MAX, &mbs);
383                         if (nconv == 0 || nconv == (size_t)-1 ||
384                             nconv == (size_t)-2)
385                                 break;
386                         p += nconv;
387                         nchars++;
388                         insize += nconv;
389                 }
390                 if (nconv == (size_t)-1 || nconv == (size_t)-2)
391                         return (NULL);
392         } else
393                 insize = strlen(mbsarg);
394
395         /*
396          * Allocate buffer for the result and perform the conversion,
397          * converting at most `size' bytes of the input multibyte string to
398          * wide characters for printing.
399          */
400         convbuf = malloc((insize + 1) * sizeof(*convbuf));
401         if (convbuf == NULL)
402                 return (NULL);
403         wcp = convbuf;
404         p = mbsarg;
405         mbs = initial;
406         nconv = 0;
407         while (insize != 0) {
408                 nconv = mbrtowc(wcp, p, insize, &mbs);
409                 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
410                         break;
411                 wcp++;
412                 p += nconv;
413                 insize -= nconv;
414         }
415         if (nconv == (size_t)-1 || nconv == (size_t)-2) {
416                 free(convbuf);
417                 return (NULL);
418         }
419         *wcp = L'\0';
420
421         return (convbuf);
422 }
423
424 /*
425  * MT-safe version
426  */
427 int
428 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
429 {
430         int ret;
431
432         FLOCKFILE(fp);
433         ret = __vfwprintf_unlocked(fp, fmt0, ap);
434         FUNLOCKFILE(fp);
435         return (ret);
436 }
437
438 #ifndef NO_FLOATING_POINT
439
440 #define dtoa            __dtoa
441 #define freedtoa        __freedtoa
442
443 #include <float.h>
444 #include <math.h>
445 #include "floatio.h"
446
447 #define DEFPREC         6
448
449 static int exponent(wchar_t *, int, wchar_t);
450 static wchar_t *cvt(double, int, int, char *, int *, int, int *, char **);
451
452 #endif /* !NO_FLOATING_POINT */
453
454 /*
455  * The size of the buffer we use as scratch space for integer
456  * conversions, among other things.  Technically, we would need the
457  * most space for base 10 conversions with thousands' grouping
458  * characters between each pair of digits.  100 bytes is a
459  * conservative overestimate even for a 128-bit uintmax_t.
460  */
461 #define BUF     100
462
463 #define STATIC_ARG_TBL_SIZE 8           /* Size of static argument table. */
464
465 /*
466  * Flags used during conversion.
467  */
468 #define ALT             0x001           /* alternate form */
469 #define LADJUST         0x004           /* left adjustment */
470 #define LONGDBL         0x008           /* long double */
471 #define LONGINT         0x010           /* long integer */
472 #define LLONGINT        0x020           /* quad_t integer */
473 #define SHORTINT        0x040           /* short integer */
474 #define ZEROPAD         0x080           /* zero (as opposed to blank) pad */
475 #define FPT             0x100           /* Floating point number */
476 #define GROUPING        0x200           /* use grouping ("'" flag) */
477                                         /* C99 additional size modifiers: */
478 #define SIZET           0x400           /* size_t */
479 #define PTRDIFFT        0x800           /* ptrdiff_t */
480 #define INTMAXT         0x1000          /* intmax_t */
481 #define CHARINT         0x2000          /* print char using int format */
482
483 /*
484  * Non-MT-safe version
485  */
486 int
487 __vfwprintf_unlocked(FILE *fp, const wchar_t *fmt0, va_list ap)
488 {
489         wchar_t *fmt;           /* format string */
490         wchar_t ch;             /* character from fmt */
491         int n, n2, n3;          /* handy integer (short term usage) */
492         wchar_t *cp;            /* handy char pointer (short term usage) */
493         int flags;              /* flags as above */
494         int ret;                /* return value accumulator */
495         int width;              /* width from format (%8d), or 0 */
496         int prec;               /* precision from format; <0 for N/A */
497         wchar_t sign;           /* sign prefix (' ', '+', '-', or \0) */
498         char thousands_sep;     /* locale specific thousands separator */
499         const char *grouping;   /* locale specific numeric grouping rules */
500 #ifndef NO_FLOATING_POINT
501         /*
502          * We can decompose the printed representation of floating
503          * point numbers into several parts, some of which may be empty:
504          *
505          * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
506          *    A       B     ---C---      D       E   F
507          *
508          * A:   'sign' holds this value if present; '\0' otherwise
509          * B:   ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
510          * C:   cp points to the string MMMNNN.  Leading and trailing
511          *      zeros are not in the string and must be added.
512          * D:   expchar holds this character; '\0' if no exponent, e.g. %f
513          * F:   at least two digits for decimal, at least one digit for hex
514          */
515         const char *decimal_point;      /* locale specific decimal point */
516 #ifdef notyet
517         int signflag;           /* true if float is negative */
518         union {                 /* floating point arguments %[aAeEfFgG] */
519                 double dbl;
520                 long double ldbl;
521         } fparg;
522         char *dtoaend;          /* pointer to end of converted digits */
523 #else
524         double _double;         /* double precision arguments %[eEfgG] */
525         char softsign;          /* temporary negative sign for floats */
526 #endif
527         int expt;               /* integer value of exponent */
528         char expchar;           /* exponent character: [eEpP\0] */
529         int expsize;            /* character count for expstr */
530         char *dtoaresult;       /* buffer allocated by dtoa */
531         int lead;               /* sig figs before decimal or group sep */
532         int ndig;               /* actual number of digits returned by dtoa */
533         wchar_t expstr[MAXEXPDIG+2];    /* buffer for exponent string: e+ZZZ */
534         int nseps;              /* number of group separators with ' */
535         int nrepeats;           /* number of repeats of the last group */
536 #endif
537         u_long  ulval;          /* integer arguments %[diouxX] */
538         uintmax_t ujval;        /* %j, %ll, %q, %t, %z integers */
539         int base;               /* base for [diouxX] conversion */
540         int dprec;              /* a copy of prec if [diouxX], 0 otherwise */
541         int realsz;             /* field size expanded by dprec, sign, etc */
542         int size;               /* size of converted field or string */
543         int prsize;             /* max size of printed field */
544         const char *xdigs;      /* digits for [xX] conversion */
545         wchar_t buf[BUF];       /* buffer with space for digits of uintmax_t */
546         wchar_t ox[2];          /* space for 0x hex-prefix */
547         union arg *argtable;    /* args, built due to positional arg */
548         union arg statargtable [STATIC_ARG_TBL_SIZE];
549         int nextarg;            /* 1-based argument index */
550         va_list orgap;          /* original argument pointer */
551         wchar_t *convbuf;       /* multibyte to wide conversion result */
552
553         /*
554          * Choose PADSIZE to trade efficiency vs. size.  If larger printf
555          * fields occur frequently, increase PADSIZE and make the initialisers
556          * below longer.
557          */
558 #define PADSIZE 16              /* pad chunk size */
559         static wchar_t blanks[PADSIZE] =
560          {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
561         static wchar_t zeroes[PADSIZE] =
562          {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
563
564         static const char xdigs_lower[16] = "0123456789abcdef";
565         static const char xdigs_upper[16] = "0123456789ABCDEF";
566
567         /*
568          * BEWARE, these `goto error' on error, PRINT uses `n2' and
569          * PAD uses `n'.
570          */
571 #define PRINT(ptr, len) do {                    \
572         for (n3 = 0; n3 < (len); n3++)          \
573                 __xfputwc((ptr)[n3], fp);       \
574 } while (/*CONSTCOND*/0)
575 #define PAD(howmany, with)      do {            \
576         if ((n = (howmany)) > 0) {              \
577                 while (n > PADSIZE) {           \
578                         PRINT(with, PADSIZE);   \
579                         n -= PADSIZE;           \
580                 }                               \
581                 PRINT(with, n);                 \
582         }                                       \
583 } while (/*CONSTCOND*/0)
584 #define PRINTANDPAD(p, ep, len, with) do {      \
585         n2 = (ep) - (p);                        \
586         if (n2 > (len))                         \
587                 n2 = (len);                     \
588         if (n2 > 0)                             \
589                 PRINT((p), n2);                 \
590         PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
591 } while(/*CONSTCOND*/0)
592
593         /*
594          * Get the argument indexed by nextarg.   If the argument table is
595          * built, use it to get the argument.  If its not, get the next
596          * argument (and arguments must be gotten sequentially).
597          */
598 #define GETARG(type) \
599         ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
600             (nextarg++, va_arg(ap, type)))
601
602         /*
603          * To extend shorts properly, we need both signed and unsigned
604          * argument extraction methods.
605          */
606 #define SARG() \
607         (flags&LONGINT ? GETARG(long) : \
608             flags&SHORTINT ? (long)(short)GETARG(int) : \
609             flags&CHARINT ? (long)(signed char)GETARG(int) : \
610             (long)GETARG(int))
611 #define UARG() \
612         (flags&LONGINT ? GETARG(u_long) : \
613             flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
614             flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
615             (u_long)GETARG(u_int))
616 #define INTMAX_SIZE     (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
617 #define SJARG() \
618         (flags&INTMAXT ? GETARG(intmax_t) : \
619             flags&SIZET ? (intmax_t)GETARG(size_t) : \
620             flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
621             (intmax_t)GETARG(quad_t))
622 #define UJARG() \
623         (flags&INTMAXT ? GETARG(uintmax_t) : \
624             flags&SIZET ? (uintmax_t)GETARG(size_t) : \
625             flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
626             (uintmax_t)GETARG(u_quad_t))
627
628         /*
629          * Get * arguments, including the form *nn$.  Preserve the nextarg
630          * that the argument can be gotten once the type is determined.
631          */
632 #define GETASTER(val) \
633         n2 = 0; \
634         cp = fmt; \
635         while (is_digit(*cp)) { \
636                 n2 = 10 * n2 + to_digit(*cp); \
637                 cp++; \
638         } \
639         if (*cp == '$') { \
640                 int hold = nextarg; \
641                 if (argtable == NULL) { \
642                         argtable = statargtable; \
643                         __find_arguments (fmt0, orgap, &argtable); \
644                 } \
645                 nextarg = n2; \
646                 val = GETARG (int); \
647                 nextarg = hold; \
648                 fmt = ++cp; \
649         } else { \
650                 val = GETARG (int); \
651         }
652
653
654         thousands_sep = '\0';
655         grouping = NULL;
656 #ifndef NO_FLOATING_POINT
657         dtoaresult = NULL;
658         decimal_point = localeconv()->decimal_point;
659         expsize = 0;            /* XXXGCC -Wuninitialized [sh3,m68000] */
660 #endif
661         convbuf = NULL;
662         /* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
663         if (cantwrite(fp)) {
664                 errno = EBADF;
665                 return (WEOF);
666         }
667
668         /* optimise fprintf(stderr) (and other unbuffered Unix files) */
669         if ((fp->pub._flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
670             fp->pub._fileno >= 0)
671                 return (__sbprintf(fp, fmt0, ap));
672
673         fmt = __DECONST(wchar_t *, fmt0);
674         argtable = NULL;
675         nextarg = 1;
676         va_copy(orgap, ap);
677         ret = 0;
678
679         /*
680          * Scan the format for conversions (`%' character).
681          */
682         for (;;) {
683                 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
684                         /* void */;
685                 if ((n = fmt - cp) != 0) {
686                         if ((unsigned)ret + n > INT_MAX) {
687                                 ret = EOF;
688                                 goto error;
689                         }
690                         PRINT(cp, n);
691                         ret += n;
692                 }
693                 if (ch == '\0')
694                         goto done;
695                 fmt++;          /* skip over '%' */
696
697                 flags = 0;
698                 dprec = 0;
699                 width = 0;
700                 prec = -1;
701                 sign = '\0';
702                 ox[1] = '\0';
703                 expchar = '\0';
704                 lead = 0;
705                 nseps = nrepeats = 0;
706                 ulval = 0;
707                 ujval = 0;
708                 xdigs = NULL;
709
710 rflag:          ch = *fmt++;
711 reswitch:       switch (ch) {
712                 case ' ':
713                         /*
714                          * ``If the space and + flags both appear, the space
715                          * flag will be ignored.''
716                          *      -- ANSI X3J11
717                          */
718                         if (!sign)
719                                 sign = ' ';
720                         goto rflag;
721                 case '#':
722                         flags |= ALT;
723                         goto rflag;
724                 case '*':
725                         /*
726                          * ``A negative field width argument is taken as a
727                          * - flag followed by a positive field width.''
728                          *      -- ANSI X3J11
729                          * They don't exclude field widths read from args.
730                          */
731                         GETASTER (width);
732                         if (width >= 0)
733                                 goto rflag;
734                         width = -width;
735                         /* FALLTHROUGH */
736                 case '-':
737                         flags |= LADJUST;
738                         goto rflag;
739                 case '+':
740                         sign = '+';
741                         goto rflag;
742                 case '\'':
743                         flags |= GROUPING;
744                         thousands_sep = *(localeconv()->thousands_sep);
745                         grouping = localeconv()->grouping;
746                         goto rflag;
747                 case '.':
748                         if ((ch = *fmt++) == '*') {
749                                 GETASTER (prec);
750                                 goto rflag;
751                         }
752                         prec = 0;
753                         while (is_digit(ch)) {
754                                 prec = 10 * prec + to_digit(ch);
755                                 ch = *fmt++;
756                         }
757                         goto reswitch;
758                 case '0':
759                         /*
760                          * ``Note that 0 is taken as a flag, not as the
761                          * beginning of a field width.''
762                          *      -- ANSI X3J11
763                          */
764                         flags |= ZEROPAD;
765                         goto rflag;
766                 case '1': case '2': case '3': case '4':
767                 case '5': case '6': case '7': case '8': case '9':
768                         n = 0;
769                         do {
770                                 n = 10 * n + to_digit(ch);
771                                 ch = *fmt++;
772                         } while (is_digit(ch));
773                         if (ch == '$') {
774                                 nextarg = n;
775                                 if (argtable == NULL) {
776                                         argtable = statargtable;
777                                         __find_arguments (fmt0, orgap,
778                                             &argtable);
779                                 }
780                                 goto rflag;
781                         }
782                         width = n;
783                         goto reswitch;
784 #ifndef NO_FLOATING_POINT
785                 case 'L':
786                         flags |= LONGDBL;
787                         goto rflag;
788 #endif
789                 case 'h':
790                         if (flags & SHORTINT) {
791                                 flags &= ~SHORTINT;
792                                 flags |= CHARINT;
793                         } else
794                                 flags |= SHORTINT;
795                         goto rflag;
796                 case 'j':
797                         flags |= INTMAXT;
798                         goto rflag;
799                 case 'l':
800                         if (flags & LONGINT) {
801                                 flags &= ~LONGINT;
802                                 flags |= LLONGINT;
803                         } else
804                                 flags |= LONGINT;
805                         goto rflag;
806                 case 'q':
807                         flags |= LLONGINT;      /* not necessarily */
808                         goto rflag;
809                 case 't':
810                         flags |= PTRDIFFT;
811                         goto rflag;
812                 case 'z':
813                         flags |= SIZET;
814                         goto rflag;
815                 case 'C':
816                         flags |= LONGINT;
817                         /*FALLTHROUGH*/
818                 case 'c':
819                         if (flags & LONGINT)
820                                 *(cp = buf) = (wchar_t)GETARG(wint_t);
821                         else
822                                 *(cp = buf) = (wchar_t)btowc(GETARG(int));
823                         size = 1;
824                         sign = '\0';
825                         break;
826                 case 'D':
827                         flags |= LONGINT;
828                         /*FALLTHROUGH*/
829                 case 'd':
830                 case 'i':
831                         if (flags & INTMAX_SIZE) {
832                                 ujval = SJARG();
833                                 if ((intmax_t)ujval < 0) {
834                                         ujval = -ujval;
835                                         sign = '-';
836                                 }
837                         } else {
838                                 ulval = SARG();
839                                 if ((long)ulval < 0) {
840                                         ulval = -ulval;
841                                         sign = '-';
842                                 }
843                         }
844                         base = 10;
845                         goto number;
846 #ifndef NO_FLOATING_POINT
847 #ifdef notyet
848                 case 'a':
849                 case 'A':
850                         if (ch == 'a') {
851                                 ox[1] = 'x';
852                                 xdigs = xdigs_lower;
853                                 expchar = 'p';
854                         } else {
855                                 ox[1] = 'X';
856                                 xdigs = xdigs_upper;
857                                 expchar = 'P';
858                         }
859                         if (prec >= 0)
860                                 prec++;
861                         if (flags & LONGDBL) {
862                                 fparg.ldbl = GETARG(long double);
863                                 dtoaresult =
864                                     __hldtoa(fparg.ldbl, xdigs, prec,
865                                         &expt, &signflag, &dtoaend);
866                         } else {
867                                 fparg.dbl = GETARG(double);
868                                 dtoaresult =
869                                     __hdtoa(fparg.dbl, xdigs, prec,
870                                         &expt, &signflag, &dtoaend);
871                         }
872                         
873                         if (prec < 0)
874                                 prec = dtoaend - dtoaresult;
875                         if (expt == INT_MAX)
876                                 ox[1] = '\0';
877                         if (convbuf != NULL)
878                                 free(convbuf);
879                         ndig = dtoaend - dtoaresult;
880                         cp = convbuf = __mbsconv(dtoaresult, -1);
881                         freedtoa(dtoaresult);
882                         goto fp_common;
883                 case 'e':
884                 case 'E':
885                         expchar = ch;
886                         if (prec < 0)   /* account for digit before decpt */
887                                 prec = DEFPREC + 1;
888                         else
889                                 prec++;
890                         goto fp_begin;
891                 case 'f':
892                 case 'F':
893                         expchar = '\0';
894                         goto fp_begin;
895                 case 'g':
896                 case 'G':
897                         expchar = ch - ('g' - 'e');
898                         if (prec == 0)
899                                 prec = 1;
900 fp_begin:
901                         if (prec < 0)
902                                 prec = DEFPREC;
903                         if (convbuf != NULL)
904                                 free(convbuf);
905                         if (flags & LONGDBL) {
906                                 fparg.ldbl = GETARG(long double);
907                                 dtoaresult =
908                                     __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
909                                     &expt, &signflag, &dtoaend);
910                         } else {
911                                 fparg.dbl = GETARG(double);
912                                 dtoaresult =
913                                     dtoa(fparg.dbl, expchar ? 2 : 3, prec,
914                                     &expt, &signflag, &dtoaend);
915                                 if (expt == 9999)
916                                         expt = INT_MAX;
917                         }
918                         ndig = dtoaend - dtoaresult;
919                         cp = convbuf = __mbsconv(dtoaresult, -1);
920                         freedtoa(dtoaresult);
921 fp_common:
922                         if (signflag)
923                                 sign = '-';
924                         if (expt == INT_MAX) {  /* inf or nan */
925                                 if (*cp == 'N') {
926                                         cp = (ch >= 'a') ? L"nan" : L"NAN";
927                                         sign = '\0';
928                                 } else
929                                         cp = (ch >= 'a') ? L"inf" : L"INF";
930                                 size = 3;
931                                 break;
932                         }
933 #else
934                 case 'e':
935                 case 'E':
936                 case 'f':
937                 case 'F':
938                 case 'g':
939                 case 'G':
940                         if (prec == -1) {
941                                 prec = DEFPREC;
942                         } else if ((ch == 'g' || ch == 'G') && prec == 0) {
943                                 prec = 1;
944                         }
945
946                         if (flags & LONGDBL) {
947                                 _double = (double) GETARG(long double);
948                         } else {
949                                 _double = GETARG(double);
950                         }
951
952                         /* do this before tricky precision changes */
953                         if (isinf(_double)) {
954                                 if (_double < 0)
955                                         sign = '-';
956                                 if (ch == 'E' || ch == 'F' || ch == 'G')
957                                         cp = L"INF";
958                                 else
959                                         cp = L"inf";
960                                 size = 3;
961                                 break;
962                         }
963                         if (isnan(_double)) {
964                                 if (ch == 'E' || ch == 'F' || ch == 'G')
965                                         cp = L"NAN";
966                                 else
967                                         cp = L"nan";
968                                 size = 3;
969                                 break;
970                         }
971
972                         flags |= FPT;
973                         if (dtoaresult != NULL) {
974                                 free(dtoaresult);
975                                 dtoaresult = NULL;
976                         }
977                         cp = cvt(_double, prec, flags, &softsign,
978                                 &expt, ch, &ndig, &dtoaresult);
979                         if (softsign)
980                                 sign = '-';
981 #endif
982                         flags |= FPT;
983                         if (ch == 'g' || ch == 'G') {
984                                 if (expt > -4 && expt <= prec) {
985                                         /* Make %[gG] smell like %[fF] */
986                                         expchar = '\0';
987                                         if (flags & ALT)
988                                                 prec -= expt;
989                                         else
990                                                 prec = ndig - expt;
991                                         if (prec < 0)
992                                                 prec = 0;
993                                 } else {
994                                         /*
995                                          * Make %[gG] smell like %[eE], but
996                                          * trim trailing zeroes if no # flag.
997                                          */
998                                         if (!(flags & ALT))
999                                                 prec = ndig;
1000                                 }
1001                         }
1002                         if (expchar) {
1003                                 expsize = exponent(expstr, expt - 1, expchar);
1004                                 size = expsize + prec;
1005                                 if (prec > 1 || flags & ALT)
1006                                         ++size;
1007                         } else {
1008                                 /* space for digits before decimal point */
1009                                 if (expt > 0)
1010                                         size = expt;
1011                                 else    /* "0" */
1012                                         size = 1;
1013                                 /* space for decimal pt and following digits */
1014                                 if (prec || flags & ALT)
1015                                         size += prec + 1;
1016                                 if (grouping && expt > 0) {
1017                                         /* space for thousands' grouping */
1018                                         nseps = nrepeats = 0;
1019                                         lead = expt;
1020                                         while (*grouping != CHAR_MAX) {
1021                                                 if (lead <= *grouping)
1022                                                         break;
1023                                                 lead -= *grouping;
1024                                                 if (*(grouping+1)) {
1025                                                         nseps++;
1026                                                         grouping++;
1027                                                 } else
1028                                                         nrepeats++;
1029                                         }
1030                                         size += nseps + nrepeats;
1031                                 } else
1032                                         lead = expt;
1033                         }
1034                         break;
1035 #endif /* !NO_FLOATING_POINT */
1036                 case 'n':
1037                         /*
1038                          * Assignment-like behavior is specified if the
1039                          * value overflows or is otherwise unrepresentable.
1040                          * C99 says to use `signed char' for %hhn conversions.
1041                          */
1042                         if (flags & LLONGINT)
1043                                 *GETARG(quad_t *) = ret;
1044                         else if (flags & SIZET)
1045                                 *GETARG(ssize_t *) = (ssize_t)ret;
1046                         else if (flags & PTRDIFFT)
1047                                 *GETARG(ptrdiff_t *) = ret;
1048                         else if (flags & INTMAXT)
1049                                 *GETARG(intmax_t *) = ret;
1050                         else if (flags & LONGINT)
1051                                 *GETARG(long *) = ret;
1052                         else if (flags & SHORTINT)
1053                                 *GETARG(short *) = ret;
1054                         else if (flags & CHARINT)
1055                                 *GETARG(signed char *) = ret;
1056                         else
1057                                 *GETARG(int *) = ret;
1058                         continue;       /* no output */
1059                 case 'O':
1060                         flags |= LONGINT;
1061                         /*FALLTHROUGH*/
1062                 case 'o':
1063                         if (flags & INTMAX_SIZE)
1064                                 ujval = UJARG();
1065                         else
1066                                 ulval = UARG();
1067                         base = 8;
1068                         goto nosign;
1069                 case 'p':
1070                         /*
1071                          * ``The argument shall be a pointer to void.  The
1072                          * value of the pointer is converted to a sequence
1073                          * of printable characters, in an implementation-
1074                          * defined manner.''
1075                          *      -- ANSI X3J11
1076                          */
1077                         ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1078                         base = 16;
1079                         xdigs = xdigs_lower;
1080                         flags = flags | INTMAXT;
1081                         ox[1] = 'x';
1082                         goto nosign;
1083                 case 'S':
1084                         flags |= LONGINT;
1085                         /*FALLTHROUGH*/
1086                 case 's':
1087                         if (flags & LONGINT) {
1088                                 if ((cp = GETARG(wchar_t *)) == NULL)
1089                                         cp = L"(null)";
1090                         } else {
1091                                 char *mbp;
1092
1093                                 if (convbuf != NULL)
1094                                         free(convbuf);
1095                                 if ((mbp = GETARG(char *)) == NULL)
1096                                         cp = L"(null)";
1097                                 else {
1098                                         convbuf = __mbsconv(mbp, prec);
1099                                         if (convbuf == NULL) {
1100                                                 fp->pub._flags |= __SERR;
1101                                                 goto error;
1102                                         }
1103                                         cp = convbuf;
1104                                 }
1105                         }
1106
1107                         if (prec >= 0) {
1108                                 /*
1109                                  * can't use wcslen; can only look for the
1110                                  * NUL in the first `prec' characters, and
1111                                  * wcslen() will go further.
1112                                  */
1113                                 wchar_t *p = wmemchr(cp, 0, (size_t)prec);
1114
1115                                 if (p != NULL) {
1116                                         size = p - cp;
1117                                         if (size > prec)
1118                                                 size = prec;
1119                                 } else
1120                                         size = prec;
1121                         } else
1122                                 size = wcslen(cp);
1123                         sign = '\0';
1124                         break;
1125                 case 'U':
1126                         flags |= LONGINT;
1127                         /*FALLTHROUGH*/
1128                 case 'u':
1129                         if (flags & INTMAX_SIZE)
1130                                 ujval = UJARG();
1131                         else
1132                                 ulval = UARG();
1133                         base = 10;
1134                         goto nosign;
1135                 case 'X':
1136                         xdigs = xdigs_upper;
1137                         goto hex;
1138                 case 'x':
1139                         xdigs = xdigs_lower;
1140 hex:
1141                         if (flags & INTMAX_SIZE)
1142                                 ujval = UJARG();
1143                         else
1144                                 ulval = UARG();
1145                         base = 16;
1146                         /* leading 0x/X only if non-zero */
1147                         if (flags & ALT &&
1148                             (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1149                                 ox[1] = ch;
1150
1151                         flags &= ~GROUPING;
1152                         /* unsigned conversions */
1153 nosign:                 sign = '\0';
1154                         /*
1155                          * ``... diouXx conversions ... if a precision is
1156                          * specified, the 0 flag will be ignored.''
1157                          *      -- ANSI X3J11
1158                          */
1159 number:                 if ((dprec = prec) >= 0)
1160                                 flags &= ~ZEROPAD;
1161
1162                         /*
1163                          * ``The result of converting a zero value with an
1164                          * explicit precision of zero is no characters.''
1165                          *      -- ANSI X3J11
1166                          *
1167                          * ``The C Standard is clear enough as is.  The call
1168                          * printf("%#.0o", 0) should print 0.''
1169                          *      -- Defect Report #151
1170                          */
1171                         cp = buf + BUF;
1172                         if (flags & INTMAX_SIZE) {
1173                                 if (ujval != 0 || prec != 0 ||
1174                                     (flags & ALT && base == 8))
1175                                         cp = __ujtoa(ujval, cp, base,
1176                                             flags & ALT, xdigs,
1177                                             flags & GROUPING, thousands_sep,
1178                                             grouping);
1179                         } else {
1180                                 if (ulval != 0 || prec != 0 ||
1181                                     (flags & ALT && base == 8))
1182                                         cp = __ultoa(ulval, cp, base,
1183                                             flags & ALT, xdigs,
1184                                             flags & GROUPING, thousands_sep,
1185                                             grouping);
1186                         }
1187                         size = buf + BUF - cp;
1188                         if (size > BUF) /* should never happen */
1189                                 abort();
1190                         break;
1191                 default:        /* "%?" prints ?, unless ? is NUL */
1192                         if (ch == '\0')
1193                                 goto done;
1194                         /* pretend it was %c with argument ch */
1195                         cp = buf;
1196                         *cp = ch;
1197                         size = 1;
1198                         sign = '\0';
1199                         break;
1200                 }
1201
1202                 /*
1203                  * All reasonable formats wind up here.  At this point, `cp'
1204                  * points to a string which (if not flags&LADJUST) should be
1205                  * padded out to `width' places.  If flags&ZEROPAD, it should
1206                  * first be prefixed by any sign or other prefix; otherwise,
1207                  * it should be blank padded before the prefix is emitted.
1208                  * After any left-hand padding and prefixing, emit zeroes
1209                  * required by a decimal [diouxX] precision, then print the
1210                  * string proper, then emit zeroes required by any leftover
1211                  * floating precision; finally, if LADJUST, pad with blanks.
1212                  *
1213                  * Compute actual size, so we know how much to pad.
1214                  * size excludes decimal prec; realsz includes it.
1215                  */
1216                 realsz = dprec > size ? dprec : size;
1217                 if (sign)
1218                         realsz++;
1219                 if (ox[1])
1220                         realsz += 2;
1221
1222                 prsize = width > realsz ? width : realsz;
1223                 if ((unsigned)ret + prsize > INT_MAX) {
1224                         ret = EOF;
1225                         goto error;
1226                 }
1227
1228                 /* right-adjusting blank padding */
1229                 if ((flags & (LADJUST|ZEROPAD)) == 0)
1230                         PAD(width - realsz, blanks);
1231
1232                 /* prefix */
1233                 if (sign)
1234                         PRINT(&sign, 1);
1235
1236                 if (ox[1]) {    /* ox[1] is either x, X, or \0 */
1237                         ox[0] = '0';
1238                         PRINT(ox, 2);
1239                 }
1240
1241                 /* right-adjusting zero padding */
1242                 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1243                         PAD(width - realsz, zeroes);
1244
1245                 /* leading zeroes from decimal precision */
1246                 PAD(dprec - size, zeroes);
1247
1248                 /* the string or number proper */
1249 #ifndef NO_FLOATING_POINT
1250                 if ((flags & FPT) == 0) {
1251                         PRINT(cp, size);
1252                 } else {        /* glue together f_p fragments */
1253                         if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1254                                 if (expt <= 0) {
1255                                         PRINT(zeroes, 1);
1256                                         if (prec || flags & ALT)
1257                                                 PRINT(decimal_point, 1);
1258                                         PAD(-expt, zeroes);
1259                                         /* already handled initial 0's */
1260                                         prec += expt;
1261                                 } else {
1262                                         PRINTANDPAD(cp, convbuf + ndig, lead, zeroes);
1263                                         cp += lead;
1264                                         if (grouping) {
1265                                                 while (nseps>0 || nrepeats>0) {
1266                                                         if (nrepeats > 0)
1267                                                                 nrepeats--;
1268                                                         else {
1269                                                                 grouping--;
1270                                                                 nseps--;
1271                                                         }
1272                                                         PRINT(&thousands_sep,
1273                                                             1);
1274                                                         PRINTANDPAD(cp,
1275                                                             convbuf + ndig,
1276                                                             *grouping, zeroes);
1277                                                         cp += *grouping;
1278                                                 }
1279                                                 if (cp > convbuf + ndig)
1280                                                         cp = convbuf + ndig;
1281                                         }
1282                                         if (prec || flags & ALT) {
1283                                                 buf[0] = *decimal_point;
1284                                                 PRINT(buf, 1);
1285                                         }
1286                                 }
1287                                 PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1288                         } else {        /* %[eE] or sufficiently long %[gG] */
1289                                 if (prec > 1 || flags & ALT) {
1290                                         buf[0] = *cp++;
1291                                         buf[1] = *decimal_point;
1292                                         PRINT(buf, 2);
1293                                         PRINT(cp, ndig-1);
1294                                         PAD(prec - ndig, zeroes);
1295                                 } else  /* XeYYY */
1296                                         PRINT(cp, 1);
1297                                 PRINT(expstr, expsize);
1298                         }
1299                 }
1300 #else
1301                 PRINT(cp, size);
1302 #endif
1303                 /* left-adjusting padding (always blank) */
1304                 if (flags & LADJUST)
1305                         PAD(width - realsz, blanks);
1306
1307                 /* finally, adjust ret */
1308                 ret += prsize;
1309         }
1310 done:
1311 error:
1312 #ifndef NO_FLOATING_POINT
1313         if (dtoaresult != NULL)
1314                 free(dtoaresult);
1315 #endif
1316         va_end(orgap);
1317         if (convbuf != NULL)
1318                 free(convbuf);
1319         if (__sferror(fp))
1320                 ret = EOF;
1321         if ((argtable != NULL) && (argtable != statargtable))
1322                 free (argtable);
1323         return (ret);
1324         /* NOTREACHED */
1325 }
1326
1327 /*
1328  * Find all arguments when a positional parameter is encountered.  Returns a
1329  * table, indexed by argument number, of pointers to each arguments.  The
1330  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1331  * It will be replaces with a malloc-ed one if it overflows.
1332  */ 
1333 static void
1334 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1335 {
1336         wchar_t *fmt;           /* format string */
1337         wchar_t ch;             /* character from fmt */
1338         int n, n2;              /* handy integer (short term usage) */
1339         wchar_t *cp;            /* handy char pointer (short term usage) */
1340         int flags;              /* flags as above */
1341         enum typeid *typetable; /* table of types */
1342         enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1343         int tablesize;          /* current size of type table */
1344         int tablemax;           /* largest used index in table */
1345         int nextarg;            /* 1-based argument index */
1346
1347         /*
1348          * Add an argument type to the table, expanding if necessary.
1349          */
1350 #define ADDTYPE(type) \
1351         /*LINTED null effect*/ \
1352         (void)((nextarg >= tablesize) ? \
1353                 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1354         (nextarg > tablemax) ? tablemax = nextarg : 0, \
1355         typetable[nextarg++] = type)
1356
1357 #define ADDSARG() \
1358         (void)((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1359                 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1360                 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1361                 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1362                 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1363
1364 #define ADDUARG() \
1365         (void)((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1366                 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1367                 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1368                 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1369                 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1370
1371         /*
1372          * Add * arguments to the type array.
1373          */
1374 #define ADDASTER() \
1375         n2 = 0; \
1376         cp = fmt; \
1377         while (is_digit(*cp)) { \
1378                 n2 = 10 * n2 + to_digit(*cp); \
1379                 cp++; \
1380         } \
1381         if (*cp == '$') { \
1382                 int hold = nextarg; \
1383                 nextarg = n2; \
1384                 ADDTYPE (T_INT); \
1385                 nextarg = hold; \
1386                 fmt = ++cp; \
1387         } else { \
1388                 ADDTYPE (T_INT); \
1389         }
1390         fmt = __DECONST(wchar_t *, fmt0);
1391         typetable = stattypetable;
1392         tablesize = STATIC_ARG_TBL_SIZE;
1393         tablemax = 0; 
1394         nextarg = 1;
1395         for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1396                 typetable[n] = T_UNUSED;
1397
1398         /*
1399          * Scan the format for conversions (`%' character).
1400          */
1401         for (;;) {
1402                 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1403                         /* void */;
1404                 if (ch == '\0')
1405                         goto done;
1406                 fmt++;          /* skip over '%' */
1407
1408                 flags = 0;
1409
1410 rflag:          ch = *fmt++;
1411 reswitch:       switch (ch) {
1412                 case ' ':
1413                 case '#':
1414                         goto rflag;
1415                 case '*':
1416                         ADDASTER ();
1417                         goto rflag;
1418                 case '-':
1419                 case '+':
1420                 case '\'':
1421                         goto rflag;
1422                 case '.':
1423                         if ((ch = *fmt++) == '*') {
1424                                 ADDASTER ();
1425                                 goto rflag;
1426                         }
1427                         while (is_digit(ch)) {
1428                                 ch = *fmt++;
1429                         }
1430                         goto reswitch;
1431                 case '0':
1432                         goto rflag;
1433                 case '1': case '2': case '3': case '4':
1434                 case '5': case '6': case '7': case '8': case '9':
1435                         n = 0;
1436                         do {
1437                                 n = 10 * n + to_digit(ch);
1438                                 ch = *fmt++;
1439                         } while (is_digit(ch));
1440                         if (ch == '$') {
1441                                 nextarg = n;
1442                                 goto rflag;
1443                         }
1444                         goto reswitch;
1445 #ifndef NO_FLOATING_POINT
1446                 case 'L':
1447                         flags |= LONGDBL;
1448                         goto rflag;
1449 #endif
1450                 case 'h':
1451                         if (flags & SHORTINT) {
1452                                 flags &= ~SHORTINT;
1453                                 flags |= CHARINT;
1454                         } else
1455                                 flags |= SHORTINT;
1456                         goto rflag;
1457                 case 'j':
1458                         flags |= INTMAXT;
1459                         goto rflag;
1460                 case 'l':
1461                         if (flags & LONGINT) {
1462                                 flags &= ~LONGINT;
1463                                 flags |= LLONGINT;
1464                         } else
1465                                 flags |= LONGINT;
1466                         goto rflag;
1467                 case 'q':
1468                         flags |= LLONGINT;      /* not necessarily */
1469                         goto rflag;
1470                 case 't':
1471                         flags |= PTRDIFFT;
1472                         goto rflag;
1473                 case 'z':
1474                         flags |= SIZET;
1475                         goto rflag;
1476                 case 'C':
1477                         flags |= LONGINT;
1478                         /*FALLTHROUGH*/
1479                 case 'c':
1480                         if (flags & LONGINT)
1481                                 ADDTYPE(T_WINT);
1482                         else
1483                                 ADDTYPE(T_INT);
1484                         break;
1485                 case 'D':
1486                         flags |= LONGINT;
1487                         /*FALLTHROUGH*/
1488                 case 'd':
1489                 case 'i':
1490                         ADDSARG();
1491                         break;
1492 #ifndef NO_FLOATING_POINT
1493                 case 'a':
1494                 case 'A':
1495                 case 'e':
1496                 case 'E':
1497                 case 'f':
1498                 case 'g':
1499                 case 'G':
1500                         if (flags & LONGDBL)
1501                                 ADDTYPE(T_LONG_DOUBLE);
1502                         else
1503                                 ADDTYPE(T_DOUBLE);
1504                         break;
1505 #endif /* !NO_FLOATING_POINT */
1506                 case 'n':
1507                         if (flags & INTMAXT)
1508                                 ADDTYPE(TP_INTMAXT);
1509                         else if (flags & PTRDIFFT)
1510                                 ADDTYPE(TP_PTRDIFFT);
1511                         else if (flags & SIZET)
1512                                 ADDTYPE(TP_SIZET);
1513                         else if (flags & LLONGINT)
1514                                 ADDTYPE(TP_LLONG);
1515                         else if (flags & LONGINT)
1516                                 ADDTYPE(TP_LONG);
1517                         else if (flags & SHORTINT)
1518                                 ADDTYPE(TP_SHORT);
1519                         else if (flags & CHARINT)
1520                                 ADDTYPE(TP_SCHAR);
1521                         else
1522                                 ADDTYPE(TP_INT);
1523                         continue;       /* no output */
1524                 case 'O':
1525                         flags |= LONGINT;
1526                         /*FALLTHROUGH*/
1527                 case 'o':
1528                         ADDUARG();
1529                         break;
1530                 case 'p':
1531                         ADDTYPE(TP_VOID);
1532                         break;
1533                 case 'S':
1534                         flags |= LONGINT;
1535                         /*FALLTHROUGH*/
1536                 case 's':
1537                         if (flags & LONGINT)
1538                                 ADDTYPE(TP_WCHAR);
1539                         else
1540                                 ADDTYPE(TP_CHAR);
1541                         break;
1542                 case 'U':
1543                         flags |= LONGINT;
1544                         /*FALLTHROUGH*/
1545                 case 'u':
1546                 case 'X':
1547                 case 'x':
1548                         ADDUARG();
1549                         break;
1550                 default:        /* "%?" prints ?, unless ? is NUL */
1551                         if (ch == '\0')
1552                                 goto done;
1553                         break;
1554                 }
1555         }
1556 done:
1557         /*
1558          * Build the argument table.
1559          */
1560         if (tablemax >= STATIC_ARG_TBL_SIZE) {
1561                 *argtable = (union arg *)
1562                     malloc (sizeof (union arg) * (tablemax + 1));
1563         }
1564
1565         (*argtable) [0].intarg = 0;
1566         for (n = 1; n <= tablemax; n++) {
1567                 switch (typetable [n]) {
1568                     case T_UNUSED: /* whoops! */
1569                         (*argtable) [n].intarg = va_arg (ap, int);
1570                         break;
1571                     case TP_SCHAR:
1572                         (*argtable) [n].pschararg = va_arg (ap, signed char *);
1573                         break;
1574                     case TP_SHORT:
1575                         (*argtable) [n].pshortarg = va_arg (ap, short *);
1576                         break;
1577                     case T_INT:
1578                         (*argtable) [n].intarg = va_arg (ap, int);
1579                         break;
1580                     case T_U_INT:
1581                         (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1582                         break;
1583                     case TP_INT:
1584                         (*argtable) [n].pintarg = va_arg (ap, int *);
1585                         break;
1586                     case T_LONG:
1587                         (*argtable) [n].longarg = va_arg (ap, long);
1588                         break;
1589                     case T_U_LONG:
1590                         (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1591                         break;
1592                     case TP_LONG:
1593                         (*argtable) [n].plongarg = va_arg (ap, long *);
1594                         break;
1595                     case T_LLONG:
1596                         (*argtable) [n].longlongarg = va_arg (ap, quad_t);
1597                         break;
1598                     case T_U_LLONG:
1599                         (*argtable) [n].ulonglongarg = va_arg (ap, u_quad_t);
1600                         break;
1601                     case TP_LLONG:
1602                         (*argtable) [n].plonglongarg = va_arg (ap, quad_t *);
1603                         break;
1604                     case T_PTRDIFFT:
1605                         (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1606                         break;
1607                     case TP_PTRDIFFT:
1608                         (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1609                         break;
1610                     case T_SIZET:
1611                         (*argtable) [n].sizearg = va_arg (ap, size_t);
1612                         break;
1613                     case TP_SIZET:
1614                         (*argtable) [n].psizearg = va_arg (ap, size_t *);
1615                         break;
1616                     case T_INTMAXT:
1617                         (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1618                         break;
1619                     case T_UINTMAXT:
1620                         (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1621                         break;
1622                     case TP_INTMAXT:
1623                         (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1624                         break;
1625 #ifndef NO_FLOATING_POINT
1626                     case T_DOUBLE:
1627                         (*argtable) [n].doublearg = va_arg (ap, double);
1628                         break;
1629                     case T_LONG_DOUBLE:
1630                         (*argtable) [n].longdoublearg = va_arg (ap, long double);
1631                         break;
1632 #endif
1633                     case TP_CHAR:
1634                         (*argtable) [n].pchararg = va_arg (ap, char *);
1635                         break;
1636                     case TP_VOID:
1637                         (*argtable) [n].pvoidarg = va_arg (ap, void *);
1638                         break;
1639                     case T_WINT:
1640                         (*argtable) [n].wintarg = va_arg (ap, wint_t);
1641                         break;
1642                     case TP_WCHAR:
1643                         (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1644                         break;
1645                 }
1646         }
1647
1648         if ((typetable != NULL) && (typetable != stattypetable))
1649                 free (typetable);
1650 }
1651
1652 /*
1653  * Increase the size of the type table.
1654  */
1655 static void
1656 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1657 {
1658         enum typeid *const oldtable = *typetable;
1659         const int oldsize = *tablesize;
1660         enum typeid *newtable;
1661         int n, newsize = oldsize * 2;
1662
1663         if (newsize < nextarg + 1)
1664                 newsize = nextarg + 1;
1665         if (oldsize == STATIC_ARG_TBL_SIZE) {
1666                 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1667                         abort();                        /* XXX handle better */
1668                 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1669         } else {
1670                 newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1671                 if (newtable == NULL)
1672                         abort();                        /* XXX handle better */
1673         }
1674         for (n = oldsize; n < newsize; n++)
1675                 newtable[n] = T_UNUSED;
1676
1677         *typetable = newtable;
1678         *tablesize = newsize;
1679 }
1680
1681
1682 #ifndef NO_FLOATING_POINT
1683 extern char *__dtoa (double, int, int, int *, int *, char **, char **);
1684
1685 static wchar_t *
1686 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1687     int *length, char **dtoaresult)
1688 {
1689         int mode, dsgn;
1690         char *digits, *bp, *rve;
1691         static wchar_t buf[512];
1692
1693         _DIAGASSERT(decpt != NULL);
1694         _DIAGASSERT(length != NULL);
1695         _DIAGASSERT(sign != NULL);
1696
1697         if (ch == 'f') {
1698                 mode = 3;               /* ndigits after the decimal point */
1699         } else {
1700                 /* To obtain ndigits after the decimal point for the 'e' 
1701                  * and 'E' formats, round to ndigits + 1 significant 
1702                  * figures.
1703                  */
1704                 if (ch == 'e' || ch == 'E') {
1705                         ndigits++;
1706                 }
1707                 mode = 2;               /* ndigits significant digits */
1708         }
1709
1710         digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve, dtoaresult);
1711         if (dsgn) {
1712                 value = -value;
1713                 *sign = '-';
1714         } else
1715                 *sign = '\000';
1716         if ((ch != 'g' && ch != 'G') || flags & ALT) {  /* Print trailing zeros */
1717                 bp = digits + ndigits;
1718                 if (ch == 'f') {
1719                         if (*digits == '0' && value)
1720                                 *decpt = -ndigits + 1;
1721                         bp += *decpt;
1722                 }
1723                 if (value == 0) /* kludge for __dtoa irregularity */
1724                         rve = bp;
1725                 while (rve < bp)
1726                         *rve++ = '0';
1727         }
1728         *length = rve - digits;
1729         mbstowcs(buf, digits, sizeof(buf)/sizeof(buf[0]));
1730         return buf;
1731 }
1732 static int
1733 exponent(wchar_t *p0, int expo, wchar_t fmtch)
1734 {
1735         wchar_t *p, *t;
1736         wchar_t expbuf[MAXEXPDIG];
1737
1738         p = p0;
1739         *p++ = fmtch;
1740         if (expo < 0) {
1741                 expo = -expo;
1742                 *p++ = '-';
1743         }
1744         else
1745                 *p++ = '+';
1746         t = expbuf + MAXEXPDIG;
1747         if (expo > 9) {
1748                 do {
1749                         *--t = to_char(expo % 10);
1750                 } while ((expo /= 10) > 9);
1751                 *--t = to_char(expo);
1752                 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1753         }
1754         else {
1755                 /*
1756                  * Exponents for decimal floating point conversions
1757                  * (%[eEgG]) must be at least two characters long,
1758                  * whereas exponents for hexadecimal conversions can
1759                  * be only one character long.
1760                  */
1761                 if (fmtch == 'e' || fmtch == 'E')
1762                         *p++ = '0';
1763                 *p++ = to_char(expo);
1764         }
1765         return (p - p0);
1766 }
1767 #endif /* !NO_FLOATING_POINT */