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