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