Correct BSD License clause numbering from 1-2-4 to 1-2-3.
[dragonfly.git] / lib / libc / stdio / vfprintf.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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)vfprintf.c       8.1 (Berkeley) 6/4/93
33  * $FreeBSD: src/lib/libc/stdio/vfprintf.c,v 1.90 2009/02/28 06:06:57 das Exp $
34  * $DragonFly: src/lib/libc/stdio/vfprintf.c,v 1.16 2006/07/05 15:04:54 joerg Exp $
35  */
36
37 /*
38  * Actual printf innards.
39  *
40  * This code is large and complicated...
41  */
42
43 #include "namespace.h"
44 #include <sys/types.h>
45
46 #include <ctype.h>
47 #include <limits.h>
48 #include <locale.h>
49 #include <stddef.h>
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <wchar.h>
55 #include <printf.h>
56
57 #include <stdarg.h>
58 #include "un-namespace.h"
59
60 #include "libc_private.h"
61 #include "local.h"
62 #include "priv_stdio.h"
63 #include "printflocal.h"
64
65 static int      __sprint(FILE *, struct __suio *);
66 static int      __sbprintf(FILE *, const char *, va_list) __printflike(2, 0)
67                            __noinline;
68 static char     *__wcsconv(wchar_t *, int);
69
70 #define CHAR    char
71 #include "printfcommon.h"
72
73 struct grouping_state {
74         char *thousands_sep;    /* locale-specific thousands separator */
75         int thousep_len;        /* length of thousands_sep */
76         const char *grouping;   /* locale-specific numeric grouping rules */
77         int lead;               /* sig figs before decimal or group sep */
78         int nseps;              /* number of group separators with ' */
79         int nrepeats;           /* number of repeats of the last group */
80 };
81
82 /*
83  * Initialize the thousands' grouping state in preparation to print a
84  * number with ndigits digits. This routine returns the total number
85  * of bytes that will be needed.
86  */
87 static int
88 grouping_init(struct grouping_state *gs, int ndigits)
89 {
90         struct lconv *locale;
91
92         locale = localeconv();
93         gs->grouping = locale->grouping;
94         gs->thousands_sep = locale->thousands_sep;
95         gs->thousep_len = strlen(gs->thousands_sep);
96
97         gs->nseps = gs->nrepeats = 0;
98         gs->lead = ndigits;
99         while (*gs->grouping != CHAR_MAX) {
100                 if (gs->lead <= *gs->grouping)
101                         break;
102                 gs->lead -= *gs->grouping;
103                 if (*(gs->grouping+1)) {
104                         gs->nseps++;
105                         gs->grouping++;
106                 } else
107                         gs->nrepeats++;
108         }
109         return ((gs->nseps + gs->nrepeats) * gs->thousep_len);
110 }
111
112 /*
113  * Print a number with thousands' separators.
114  */
115 static int
116 grouping_print(struct grouping_state *gs, struct io_state *iop,
117                const CHAR *cp, const CHAR *ep)
118 {
119         const CHAR *cp0 = cp;
120
121         if (io_printandpad(iop, cp, ep, gs->lead, zeroes))
122                 return (-1);
123         cp += gs->lead;
124         while (gs->nseps > 0 || gs->nrepeats > 0) {
125                 if (gs->nrepeats > 0)
126                         gs->nrepeats--;
127                 else {
128                         gs->grouping--;
129                         gs->nseps--;
130                 }
131                 if (io_print(iop, gs->thousands_sep, gs->thousep_len))
132                         return (-1);
133                 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes))
134                         return (-1);
135                 cp += *gs->grouping;
136         }
137         if (cp > ep)
138                 cp = ep;
139         return (cp - cp0);
140 }
141
142 /*
143  * Flush out all the vectors defined by the given uio,
144  * then reset it so that it can be reused.
145  */
146 static int
147 __sprint(FILE *fp, struct __suio *uio)
148 {
149         int err;
150
151         if (uio->uio_resid == 0) {
152                 uio->uio_iovcnt = 0;
153                 return (0);
154         }
155         err = __sfvwrite(fp, uio);
156         uio->uio_resid = 0;
157         uio->uio_iovcnt = 0;
158         return (err);
159 }
160
161 /*
162  * Helper function for `fprintf to unbuffered unix file': creates a
163  * temporary buffer.  We only work on write-only files; this avoids
164  * worries about ungetc buffers and so forth.
165  */
166 static int
167 __sbprintf(FILE *fp, const char *fmt, va_list ap)
168 {
169         int ret;
170         FILE fake;
171         unsigned char buf[BUFSIZ];
172
173         /* XXX This is probably not needed. */
174         if (prepwrite(fp) != 0)
175                 return (EOF);
176
177         /* copy the important variables */
178         fake.pub._flags = fp->pub._flags & ~__SNBF;
179         fake.pub._fileno = fp->pub._fileno;
180         fake._cookie = fp->_cookie;
181         fake._write = fp->_write;
182         memcpy(WCIO_GET(&fake), WCIO_GET(fp), sizeof(struct wchar_io_data));
183
184         /* set up the buffer */
185         fake._bf._base = fake.pub._p = buf;
186         fake._bf._size = fake.pub._w = sizeof(buf);
187         fake.pub._lbfsize = 0;  /* not actually used, but Just In Case */
188
189         /* do the work, then copy any error status */
190         ret = __vfprintf(&fake, fmt, ap);
191         if (ret >= 0 && __fflush(&fake))
192                 ret = EOF;
193         if (fake.pub._flags & __SERR)
194                 fp->pub._flags |= __SERR;
195         return (ret);
196 }
197
198 /*
199  * Convert a wide character string argument for the %ls format to a multibyte
200  * string representation. If not -1, prec specifies the maximum number of
201  * bytes to output, and also means that we can't assume that the wide char.
202  * string ends is null-terminated.
203  */
204 static char *
205 __wcsconv(wchar_t *wcsarg, int prec)
206 {
207         static const mbstate_t initial;
208         mbstate_t mbs;
209         char buf[MB_LEN_MAX];
210         wchar_t *p;
211         char *convbuf;
212         size_t clen, nbytes;
213
214         /* Allocate space for the maximum number of bytes we could output. */
215         if (prec < 0) {
216                 p = wcsarg;
217                 mbs = initial;
218                 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
219                 if (nbytes == (size_t)-1)
220                         return (NULL);
221         } else {
222                 /*
223                  * Optimisation: if the output precision is small enough,
224                  * just allocate enough memory for the maximum instead of
225                  * scanning the string.
226                  */
227                 if (prec < 128) {
228                         nbytes = prec;
229                 } else {
230                         nbytes = 0;
231                         p = wcsarg;
232                         mbs = initial;
233                         for (;;) {
234                                 clen = wcrtomb(buf, *p++, &mbs);
235                                 if (clen == 0 || clen == (size_t)-1 ||
236                                     nbytes + clen > prec)
237                                         break;
238                                 nbytes += clen;
239                         }
240                 }
241         }
242         if ((convbuf = malloc(nbytes + 1)) == NULL)
243                 return (NULL);
244
245         /* Fill the output buffer. */
246         p = wcsarg;
247         mbs = initial;
248         if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
249             nbytes, &mbs)) == (size_t)-1) {
250                 free(convbuf);
251                 return (NULL);
252         }
253         convbuf[nbytes] = '\0';
254         return (convbuf);
255 }
256
257 /*
258  * MT-safe version
259  */
260 int
261 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
262 {
263         int ret;
264
265         FLOCKFILE(fp);
266         /* optimise fprintf(stderr) (and other unbuffered Unix files) */
267         if ((fp->pub._flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
268             fp->pub._fileno >= 0)
269                 ret = __sbprintf(fp, fmt0, ap);
270         else
271                 ret = __vfprintf(fp, fmt0, ap);
272         FUNLOCKFILE(fp);
273         return (ret);
274 }
275
276 /*
277  * The size of the buffer we use as scratch space for integer
278  * conversions, among other things.  We need enough space to
279  * write a uintmax_t in octal (plus one byte).
280  */
281 #if UINTMAX_MAX <= UINT64_MAX
282 #define BUF     32
283 #else
284 #error "BUF must be large enough to format a uintmax_t"
285 #endif
286
287 /*
288  * Non-MT-safe version
289  */
290 int
291 __vfprintf(FILE *fp, const char *fmt0, va_list ap)
292 {
293         char *fmt;              /* format string */
294         int ch;                 /* character from fmt */
295         int n, n2;              /* handy integer (short term usage) */
296         char *cp;               /* handy char pointer (short term usage) */
297         int flags;              /* flags as above */
298         int ret;                /* return value accumulator */
299         int width;              /* width from format (%8d), or 0 */
300         int prec;               /* precision from format; <0 for N/A */
301         char sign;              /* sign prefix (' ', '+', '-', or \0) */
302         struct grouping_state gs; /* thousands' grouping info */
303
304 #ifndef NO_FLOATING_POINT
305         /*
306          * We can decompose the printed representation of floating
307          * point numbers into several parts, some of which may be empty:
308          *
309          * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
310          *    A       B     ---C---      D       E   F
311          *
312          * A:   'sign' holds this value if present; '\0' otherwise
313          * B:   ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
314          * C:   cp points to the string MMMNNN.  Leading and trailing
315          *      zeros are not in the string and must be added.
316          * D:   expchar holds this character; '\0' if no exponent, e.g. %f
317          * F:   at least two digits for decimal, at least one digit for hex
318          */
319         char *decimal_point;    /* locale specific decimal point */
320         int decpt_len;          /* length of decimal_point */
321         int signflag;           /* true if float is negative */
322         union {                 /* floating point arguments %[aAeEfFgG] */
323                 double dbl;
324                 long double ldbl;
325         } fparg;
326         int expt;               /* integer value of exponent */
327         char expchar;           /* exponent character: [eEpP\0] */
328         char *dtoaend;          /* pointer to end of converted digits */
329         int expsize;            /* character count for expstr */
330         int ndig;               /* actual number of digits returned by dtoa */
331         char expstr[MAXEXPDIG+2];       /* buffer for exponent string: e+ZZZ */
332         char *dtoaresult;       /* buffer allocated by dtoa */
333 #endif
334         u_long  ulval;          /* integer arguments %[diouxX] */
335         uintmax_t ujval;        /* %j, %ll, %q, %t, %z integers */
336         int base;               /* base for [diouxX] conversion */
337         int dprec;              /* a copy of prec if [diouxX], 0 otherwise */
338         int realsz;             /* field size expanded by dprec, sign, etc */
339         int size;               /* size of converted field or string */
340         int prsize;             /* max size of printed field */
341         const char *xdigs;      /* digits for %[xX] conversion */
342         struct io_state io;     /* I/O buffering state */
343         char buf[BUF];          /* buffer with space for digits of uintmax_t */
344         char ox[2];             /* space for 0x; ox[1] is either x, X, or \0 */
345         union arg *argtable;    /* args, built due to positional arg */
346         union arg statargtable [STATIC_ARG_TBL_SIZE];
347         int nextarg;            /* 1-based argument index */
348         va_list orgap;          /* original argument pointer */
349         char *convbuf;          /* wide to multibyte conversion result */
350
351         static const char xdigs_lower[16] = "0123456789abcdef";
352         static const char xdigs_upper[16] = "0123456789ABCDEF";
353
354         /* BEWARE, these `goto error' on error. */
355 #define PRINT(ptr, len) { \
356         if (io_print(&io, (ptr), (len)))        \
357                 goto error; \
358 }
359 #define PAD(howmany, with) { \
360         if (io_pad(&io, (howmany), (with))) \
361                 goto error; \
362 }
363 #define PRINTANDPAD(p, ep, len, with) { \
364         if (io_printandpad(&io, (p), (ep), (len), (with))) \
365                 goto error; \
366 }
367 #define FLUSH() { \
368         if (io_flush(&io)) \
369                 goto error; \
370 }
371
372         /*
373          * Get the argument indexed by nextarg.   If the argument table is
374          * built, use it to get the argument.  If its not, get the next
375          * argument (and arguments must be gotten sequentially).
376          */
377 #define GETARG(type) \
378         ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
379             (nextarg++, va_arg(ap, type)))
380
381         /*
382          * To extend shorts properly, we need both signed and unsigned
383          * argument extraction methods.
384          */
385 #define SARG() \
386         (flags&LONGINT ? GETARG(long) : \
387             flags&SHORTINT ? (long)(short)GETARG(int) : \
388             flags&CHARINT ? (long)(signed char)GETARG(int) : \
389             (long)GETARG(int))
390 #define UARG() \
391         (flags&LONGINT ? GETARG(u_long) : \
392             flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
393             flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
394             (u_long)GETARG(u_int))
395 #define INTMAX_SIZE     (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
396 #define SJARG() \
397         (flags&INTMAXT ? GETARG(intmax_t) : \
398             flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
399             flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
400             (intmax_t)GETARG(long long))
401 #define UJARG() \
402         (flags&INTMAXT ? GETARG(uintmax_t) : \
403             flags&SIZET ? (uintmax_t)GETARG(size_t) : \
404             flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
405             (uintmax_t)GETARG(unsigned long long))
406
407         /*
408          * Get * arguments, including the form *nn$.  Preserve the nextarg
409          * that the argument can be gotten once the type is determined.
410          */
411 #define GETASTER(val) \
412         n2 = 0; \
413         cp = fmt; \
414         while (is_digit(*cp)) { \
415                 n2 = 10 * n2 + to_digit(*cp); \
416                 cp++; \
417         } \
418         if (*cp == '$') { \
419                 int hold = nextarg; \
420                 if (argtable == NULL) { \
421                         argtable = statargtable; \
422                         if (__find_arguments (fmt0, orgap, &argtable)) { \
423                                 ret = EOF; \
424                                 goto error; \
425                         } \
426                 } \
427                 nextarg = n2; \
428                 val = GETARG (int); \
429                 nextarg = hold; \
430                 fmt = ++cp; \
431         } else { \
432                 val = GETARG (int); \
433         }
434
435         if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
436                 __use_xprintf = 1;
437         if (__use_xprintf > 0)
438                 return (__xvprintf(fp, fmt0, ap));
439
440         /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
441         if (prepwrite(fp) != 0)
442                 return (EOF);
443
444         convbuf = NULL;
445         fmt = __DECONST(char *, fmt0);
446         argtable = NULL;
447         nextarg = 1;
448         va_copy(orgap, ap);
449         io_init(&io, fp);
450         ret = 0;
451 #ifndef NO_FLOATING_POINT
452         dtoaresult = NULL;
453         decimal_point = localeconv()->decimal_point;
454         /* The overwhelmingly common case is decpt_len == 1. */
455         decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
456 #endif
457
458         /*
459          * Scan the format for conversions (`%' character).
460          */
461         for (;;) {
462                 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
463                         /* void */;
464                 if ((n = fmt - cp) != 0) {
465                         if ((unsigned)ret + n > INT_MAX) {
466                                 ret = EOF;
467                                 goto error;
468                         }
469                         PRINT(cp, n);
470                         ret += n;
471                 }
472                 if (ch == '\0')
473                         goto done;
474                 fmt++;          /* skip over '%' */
475
476                 flags = 0;
477                 dprec = 0;
478                 width = 0;
479                 prec = -1;
480                 gs.grouping = NULL;
481                 sign = '\0';
482                 ox[1] = '\0';
483
484 rflag:          ch = *fmt++;
485 reswitch:       switch (ch) {
486                 case ' ':
487                         /*-
488                          * ``If the space and + flags both appear, the space
489                          * flag will be ignored.''
490                          *      -- ANSI X3J11
491                          */
492                         if (!sign)
493                                 sign = ' ';
494                         goto rflag;
495                 case '#':
496                         flags |= ALT;
497                         goto rflag;
498                 case '*':
499                         /*-
500                          * ``A negative field width argument is taken as a
501                          * - flag followed by a positive field width.''
502                          *      -- ANSI X3J11
503                          * They don't exclude field widths read from args.
504                          */
505                         GETASTER(width);
506                         if (width >= 0)
507                                 goto rflag;
508                         width = -width;
509                         /* FALLTHROUGH */
510                 case '-':
511                         flags |= LADJUST;
512                         goto rflag;
513                 case '+':
514                         sign = '+';
515                         goto rflag;
516                 case '\'':
517                         flags |= GROUPING;
518                         goto rflag;
519                 case '.':
520                         if ((ch = *fmt++) == '*') {
521                                 GETASTER(prec);
522                                 goto rflag;
523                         }
524                         prec = 0;
525                         while (is_digit(ch)) {
526                                 prec = 10 * prec + to_digit(ch);
527                                 ch = *fmt++;
528                         }
529                         goto reswitch;
530                 case '0':
531                         /*-
532                          * ``Note that 0 is taken as a flag, not as the
533                          * beginning of a field width.''
534                          *      -- ANSI X3J11
535                          */
536                         flags |= ZEROPAD;
537                         goto rflag;
538                 case '1': case '2': case '3': case '4':
539                 case '5': case '6': case '7': case '8': case '9':
540                         n = 0;
541                         do {
542                                 n = 10 * n + to_digit(ch);
543                                 ch = *fmt++;
544                         } while (is_digit(ch));
545                         if (ch == '$') {
546                                 nextarg = n;
547                                 if (argtable == NULL) {
548                                         argtable = statargtable;
549                                         if (__find_arguments (fmt0, orgap,
550                                                               &argtable)) {
551                                                 ret = EOF;
552                                                 goto error;
553                                         }
554                                 }
555                                 goto rflag;
556                         }
557                         width = n;
558                         goto reswitch;
559 #ifndef NO_FLOATING_POINT
560                 case 'L':
561                         flags |= LONGDBL;
562                         goto rflag;
563 #endif
564                 case 'h':
565                         if (flags & SHORTINT) {
566                                 flags &= ~SHORTINT;
567                                 flags |= CHARINT;
568                         } else
569                                 flags |= SHORTINT;
570                         goto rflag;
571                 case 'j':
572                         flags |= INTMAXT;
573                         goto rflag;
574                 case 'l':
575                         if (flags & LONGINT) {
576                                 flags &= ~LONGINT;
577                                 flags |= LLONGINT;
578                         } else
579                                 flags |= LONGINT;
580                         goto rflag;
581                 case 'q':
582                         flags |= LLONGINT;      /* not necessarily */
583                         goto rflag;
584                 case 't':
585                         flags |= PTRDIFFT;
586                         goto rflag;
587                 case 'z':
588                         flags |= SIZET;
589                         goto rflag;
590                 case 'C':
591                         flags |= LONGINT;
592                         /*FALLTHROUGH*/
593                 case 'c':
594                         if (flags & LONGINT) {
595                                 static const mbstate_t initial;
596                                 mbstate_t mbs;
597                                 size_t mbseqlen;
598
599                                 mbs = initial;
600                                 mbseqlen = wcrtomb(cp = buf,
601                                     (wchar_t)GETARG(wint_t), &mbs);
602                                 if (mbseqlen == (size_t)-1) {
603                                         fp->pub._flags |= __SERR;
604                                         goto error;
605                                 }
606                                 size = (int)mbseqlen;
607                         } else {
608                                 *(cp = buf) = GETARG(int);
609                                 size = 1;
610                         }
611                         sign = '\0';
612                         break;
613                 case 'D':
614                         flags |= LONGINT;
615                         /*FALLTHROUGH*/
616                 case 'd':
617                 case 'i':
618                         if (flags & INTMAX_SIZE) {
619                                 ujval = SJARG();
620                                 if ((intmax_t)ujval < 0) {
621                                         ujval = -ujval;
622                                         sign = '-';
623                                 }
624                         } else {
625                                 ulval = SARG();
626                                 if ((long)ulval < 0) {
627                                         ulval = -ulval;
628                                         sign = '-';
629                                 }
630                         }
631                         base = 10;
632                         goto number;
633 #ifndef NO_FLOATING_POINT
634                 case 'a':
635                 case 'A':
636                         if (ch == 'a') {
637                                 ox[1] = 'x';
638                                 xdigs = xdigs_lower;
639                                 expchar = 'p';
640                         } else {
641                                 ox[1] = 'X';
642                                 xdigs = xdigs_upper;
643                                 expchar = 'P';
644                         }
645                         if (prec >= 0)
646                                 prec++;
647                         if (dtoaresult != NULL)
648                                 freedtoa(dtoaresult);
649                         if (flags & LONGDBL) {
650                                 fparg.ldbl = GETARG(long double);
651                                 dtoaresult = cp =
652                                     __hldtoa(fparg.ldbl, xdigs, prec,
653                                     &expt, &signflag, &dtoaend);
654                         } else {
655                                 fparg.dbl = GETARG(double);
656                                 dtoaresult = cp =
657                                     __hdtoa(fparg.dbl, xdigs, prec,
658                                     &expt, &signflag, &dtoaend);
659                         }
660                         if (prec < 0)
661                                 prec = dtoaend - cp;
662                         if (expt == INT_MAX)
663                                 ox[1] = '\0';
664                         goto fp_common;
665                 case 'e':
666                 case 'E':
667                         expchar = ch;
668                         if (prec < 0)   /* account for digit before decpt */
669                                 prec = DEFPREC + 1;
670                         else
671                                 prec++;
672                         goto fp_begin;
673                 case 'f':
674                 case 'F':
675                         expchar = '\0';
676                         goto fp_begin;
677                 case 'g':
678                 case 'G':
679                         expchar = ch - ('g' - 'e');
680                         if (prec == 0)
681                                 prec = 1;
682 fp_begin:
683                         if (prec < 0)
684                                 prec = DEFPREC;
685                         if (dtoaresult != NULL)
686                                 freedtoa(dtoaresult);
687                         if (flags & LONGDBL) {
688                                 fparg.ldbl = GETARG(long double);
689                                 dtoaresult = cp =
690                                     __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
691                                     &expt, &signflag, &dtoaend);
692                         } else {
693                                 fparg.dbl = GETARG(double);
694                                 dtoaresult = cp =
695                                     dtoa(fparg.dbl, expchar ? 2 : 3, prec,
696                                     &expt, &signflag, &dtoaend);
697                                 if (expt == 9999)
698                                         expt = INT_MAX;
699                         }
700 fp_common:
701                         if (signflag)
702                                 sign = '-';
703                         if (expt == INT_MAX) {  /* inf or nan */
704                                 if (*cp == 'N') {
705                                         cp = (ch >= 'a') ? "nan" : "NAN";
706                                         sign = '\0';
707                                 } else
708                                         cp = (ch >= 'a') ? "inf" : "INF";
709                                 size = 3;
710                                 flags &= ~ZEROPAD;
711                                 break;
712                         }
713                         flags |= FPT;
714                         ndig = dtoaend - cp;
715                         if (ch == 'g' || ch == 'G') {
716                                 if (expt > -4 && expt <= prec) {
717                                         /* Make %[gG] smell like %[fF] */
718                                         expchar = '\0';
719                                         if (flags & ALT)
720                                                 prec -= expt;
721                                         else
722                                                 prec = ndig - expt;
723                                         if (prec < 0)
724                                                 prec = 0;
725                                 } else {
726                                         /*
727                                          * Make %[gG] smell like %[eE], but
728                                          * trim trailing zeroes if no # flag.
729                                          */
730                                         if (!(flags & ALT))
731                                                 prec = ndig;
732                                 }
733                         }
734                         if (expchar) {
735                                 expsize = exponent(expstr, expt - 1, expchar);
736                                 size = expsize + prec;
737                                 if (prec > 1 || flags & ALT)
738                                         size += decpt_len;
739                         } else {
740                                 /* space for digits before decimal point */
741                                 if (expt > 0)
742                                         size = expt;
743                                 else    /* "0" */
744                                         size = 1;
745                                 /* space for decimal pt and following digits */
746                                 if (prec || flags & ALT)
747                                         size += prec + decpt_len;
748                                 if ((flags & GROUPING) && expt > 0)
749                                         size += grouping_init(&gs, expt);
750                         }
751                         break;
752 #endif /* !NO_FLOATING_POINT */
753                 case 'n':
754                         /*
755                          * Assignment-like behavior is specified if the
756                          * value overflows or is otherwise unrepresentable.
757                          * C99 says to use `signed char' for %hhn conversions.
758                          */
759                         if (flags & LLONGINT)
760                                 *GETARG(long long *) = ret;
761                         else if (flags & SIZET)
762                                 *GETARG(ssize_t *) = (ssize_t)ret;
763                         else if (flags & PTRDIFFT)
764                                 *GETARG(ptrdiff_t *) = ret;
765                         else if (flags & INTMAXT)
766                                 *GETARG(intmax_t *) = ret;
767                         else if (flags & LONGINT)
768                                 *GETARG(long *) = ret;
769                         else if (flags & SHORTINT)
770                                 *GETARG(short *) = ret;
771                         else if (flags & CHARINT)
772                                 *GETARG(signed char *) = ret;
773                         else
774                                 *GETARG(int *) = ret;
775                         continue;       /* no output */
776                 case 'O':
777                         flags |= LONGINT;
778                         /*FALLTHROUGH*/
779                 case 'o':
780                         if (flags & INTMAX_SIZE)
781                                 ujval = UJARG();
782                         else
783                                 ulval = UARG();
784                         base = 8;
785                         goto nosign;
786                 case 'p':
787                         /*-
788                          * ``The argument shall be a pointer to void.  The
789                          * value of the pointer is converted to a sequence
790                          * of printable characters, in an implementation-
791                          * defined manner.''
792                          *      -- ANSI X3J11
793                          */
794                         ujval = (uintmax_t)(uintptr_t)GETARG(void *);
795                         base = 16;
796                         xdigs = xdigs_lower;
797                         flags = flags | INTMAXT;
798                         ox[1] = 'x';
799                         goto nosign;
800                 case 'S':
801                         flags |= LONGINT;
802                         /*FALLTHROUGH*/
803                 case 's':
804                         if (flags & LONGINT) {
805                                 wchar_t *wcp;
806
807                                 if (convbuf != NULL)
808                                         free(convbuf);
809                                 if ((wcp = GETARG(wchar_t *)) == NULL)
810                                         cp = "(null)";
811                                 else {
812                                         convbuf = __wcsconv(wcp, prec);
813                                         if (convbuf == NULL) {
814                                                 fp->pub._flags |= __SERR;
815                                                 goto error;
816                                         }
817                                         cp = convbuf;
818                                 }
819                         } else if ((cp = GETARG(char *)) == NULL)
820                                 cp = "(null)";
821                         size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
822                         sign = '\0';
823                         break;
824                 case 'U':
825                         flags |= LONGINT;
826                         /*FALLTHROUGH*/
827                 case 'u':
828                         if (flags & INTMAX_SIZE)
829                                 ujval = UJARG();
830                         else
831                                 ulval = UARG();
832                         base = 10;
833                         goto nosign;
834                 case 'X':
835                         xdigs = xdigs_upper;
836                         goto hex;
837                 case 'x':
838                         xdigs = xdigs_lower;
839 hex:
840                         if (flags & INTMAX_SIZE)
841                                 ujval = UJARG();
842                         else
843                                 ulval = UARG();
844                         base = 16;
845                         /* leading 0x/X only if non-zero */
846                         if (flags & ALT &&
847                             (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
848                                 ox[1] = ch;
849
850                         flags &= ~GROUPING;
851                         /* unsigned conversions */
852 nosign:                 sign = '\0';
853                         /*-
854                          * ``... diouXx conversions ... if a precision is
855                          * specified, the 0 flag will be ignored.''
856                          *      -- ANSI X3J11
857                          */
858 number:                 if ((dprec = prec) >= 0)
859                                 flags &= ~ZEROPAD;
860
861                         /*-
862                          * ``The result of converting a zero value with an
863                          * explicit precision of zero is no characters.''
864                          *      -- ANSI X3J11
865                          *
866                          * ``The C Standard is clear enough as is.  The call
867                          * printf("%#.0o", 0) should print 0.''
868                          *      -- Defect Report #151
869                          */
870                         cp = buf + BUF;
871                         if (flags & INTMAX_SIZE) {
872                                 if (ujval != 0 || prec != 0 ||
873                                     (flags & ALT && base == 8))
874                                         cp = __ujtoa(ujval, cp, base,
875                                             flags & ALT, xdigs);
876                         } else {
877                                 if (ulval != 0 || prec != 0 ||
878                                     (flags & ALT && base == 8))
879                                         cp = __ultoa(ulval, cp, base,
880                                             flags & ALT, xdigs);
881                         }
882                         size = buf + BUF - cp;
883                         if (size > BUF) /* should never happen */
884                                 abort();
885                         if ((flags & GROUPING) && size != 0)
886                                 size += grouping_init(&gs, size);
887                         break;
888                 default:        /* "%?" prints ?, unless ? is NUL */
889                         if (ch == '\0')
890                                 goto done;
891                         /* pretend it was %c with argument ch */
892                         cp = buf;
893                         *cp = ch;
894                         size = 1;
895                         sign = '\0';
896                         break;
897                 }
898
899                 /*
900                  * All reasonable formats wind up here.  At this point, `cp'
901                  * points to a string which (if not flags&LADJUST) should be
902                  * padded out to `width' places.  If flags&ZEROPAD, it should
903                  * first be prefixed by any sign or other prefix; otherwise,
904                  * it should be blank padded before the prefix is emitted.
905                  * After any left-hand padding and prefixing, emit zeroes
906                  * required by a decimal [diouxX] precision, then print the
907                  * string proper, then emit zeroes required by any leftover
908                  * floating precision; finally, if LADJUST, pad with blanks.
909                  *
910                  * Compute actual size, so we know how much to pad.
911                  * size excludes decimal prec; realsz includes it.
912                  */
913                 realsz = dprec > size ? dprec : size;
914                 if (sign)
915                         realsz++;
916                 if (ox[1])
917                         realsz += 2;
918
919                 prsize = width > realsz ? width : realsz;
920                 if ((unsigned)ret + prsize > INT_MAX) {
921                         ret = EOF;
922                         goto error;
923                 }
924
925                 /* right-adjusting blank padding */
926                 if ((flags & (LADJUST|ZEROPAD)) == 0)
927                         PAD(width - realsz, blanks);
928
929                 /* prefix */
930                 if (sign)
931                         PRINT(&sign, 1);
932
933                 if (ox[1]) {    /* ox[1] is either x, X, or \0 */
934                         ox[0] = '0';
935                         PRINT(ox, 2);
936                 }
937
938                 /* right-adjusting zero padding */
939                 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
940                         PAD(width - realsz, zeroes);
941
942                 /* the string or number proper */
943 #ifndef NO_FLOATING_POINT
944                 if ((flags & FPT) == 0) {
945 #endif
946                         /* leading zeroes from decimal precision */
947                         PAD(dprec - size, zeroes);
948                         if (gs.grouping) {
949                                 if (grouping_print(&gs, &io, cp, buf+BUF) < 0)
950                                         goto error;
951                         } else {
952                                 PRINT(cp, size);
953                         }
954 #ifndef NO_FLOATING_POINT
955                 } else {        /* glue together f_p fragments */
956                         if (!expchar) { /* %[fF] or sufficiently short %[gG] */
957                                 if (expt <= 0) {
958                                         PRINT(zeroes, 1);
959                                         if (prec || flags & ALT)
960                                                 PRINT(decimal_point,decpt_len);
961                                         PAD(-expt, zeroes);
962                                         /* already handled initial 0's */
963                                         prec += expt;
964                                 } else {
965                                         if (gs.grouping) {
966                                                 n = grouping_print(&gs, &io,
967                                                     cp, dtoaend);
968                                                 if (n < 0)
969                                                         goto error;
970                                                 cp += n;
971                                         } else {
972                                                 PRINTANDPAD(cp, dtoaend,
973                                                     expt, zeroes);
974                                                 cp += expt;
975                                         }
976                                         if (prec || flags & ALT)
977                                                 PRINT(decimal_point,decpt_len);
978                                 }
979                                 PRINTANDPAD(cp, dtoaend, prec, zeroes);
980                         } else {        /* %[eE] or sufficiently long %[gG] */
981                                 if (prec > 1 || flags & ALT) {
982                                         PRINT(cp++, 1);
983                                         PRINT(decimal_point, decpt_len);
984                                         PRINT(cp, ndig-1);
985                                         PAD(prec - ndig, zeroes);
986                                 } else  /* XeYYY */
987                                         PRINT(cp, 1);
988                                 PRINT(expstr, expsize);
989                         }
990                 }
991 #endif
992                 /* left-adjusting padding (always blank) */
993                 if (flags & LADJUST)
994                         PAD(width - realsz, blanks);
995
996                 /* finally, adjust ret */
997                 ret += prsize;
998
999                 FLUSH();        /* copy out the I/O vectors */
1000         }
1001 done:
1002         FLUSH();
1003 error:
1004         va_end(orgap);
1005 #ifndef NO_FLOATING_POINT
1006         if (dtoaresult != NULL)
1007                 freedtoa(dtoaresult);
1008 #endif
1009         if (convbuf != NULL)
1010                 free(convbuf);
1011         if (__sferror(fp))
1012                 ret = EOF;
1013         if ((argtable != NULL) && (argtable != statargtable))
1014                 free(argtable);
1015         return (ret);
1016         /* NOTREACHED */
1017 }
1018