2da898817d98102236d03b7babb2efdc173bd7c0
[platform/upstream/glibc.git] / stdio-common / vfprintf.c
1 /* Copyright (C) 1991, 92, 93, 94, 95, 96 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Library General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    The GNU C Library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Library General Public License for more details.
13
14    You should have received a copy of the GNU Library General Public
15    License along with the GNU C Library; see the file COPYING.LIB.  If not,
16    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17    Boston, MA 02111-1307, USA.  */
18
19 #include <ctype.h>
20 #include <limits.h>
21 #include <printf.h>
22 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <wchar.h>
26 #include <libc-lock.h>
27 #include "_itoa.h"
28 #include "../locale/localeinfo.h"
29
30 /* This code is shared between the standard stdio implementation found
31    in GNU C library and the libio implementation originally found in
32    GNU libg++.
33
34    Beside this it is also shared between the normal and wide character
35    implementation as defined in ISO/IEC 9899:1990/Amendment 1:1995.  */
36
37 #ifndef COMPILE_WPRINTF
38 # define CHAR_T         char
39 # define UCHAR_T        unsigned char
40 # define INT_T          int
41 # define L_(Str)        Str
42 # define ISDIGIT(Ch)    isdigit (Ch)
43
44 # ifdef USE_IN_LIBIO
45 #  define PUT(F, S, N)  _IO_sputn ((F), (S), (N))
46 #  define PAD(Padchar)                                                        \
47   if (width > 0)                                                              \
48     done += _IO_padn (s, (Padchar), width)
49 # else
50 #  define PUTC(C, F)    putc (C, F)
51 ssize_t __printf_pad __P ((FILE *, char pad, size_t n));
52 # define PAD(Padchar)                                                         \
53   if (width > 0)                                                              \
54     { ssize_t __res = __printf_pad (s, (Padchar), width);                     \
55       if (__res == -1) return -1;                                             \
56       done += __res; }
57 # endif
58 #else
59 # define vfprintf       vfwprintf
60 # define CHAR_T         wchar_t
61 # define UCHAR_T        uwchar_t
62 # define INT_T          wint_t
63 # define L_(Str)        L##Str
64 # define ISDIGIT(Ch)    iswdigit (Ch)
65
66 # ifdef USE_IN_LIBIO
67 #  define PUT(F, S, N)  _IO_sputn ((F), (S), (N))
68 #  define PAD(Padchar)                                                        \
69   if (width > 0)                                                              \
70     done += _IO_wpadn (s, (Padchar), width)
71 # else
72 #  define PUTC(C, F)    wputc (C, F)
73 ssize_t __wprintf_pad __P ((FILE *, wchar_t pad, size_t n));
74 #  define PAD(Padchar)                                                        \
75   if (width > 0)                                                              \
76     { ssize_t __res = __wprintf_pad (s, (Padchar), width);                    \
77       if (__res == -1) return -1;                                             \
78       done += __res; }
79 # endif
80 #endif
81
82 /* Include the shared code for parsing the format string.  */
83 #include "printf-parse.h"
84
85
86 #ifdef USE_IN_LIBIO
87 /* This code is for use in libio.  */
88 # include <libioP.h>
89 # define PUTC(C, F)     _IO_putc_unlocked (C, F)
90 # define vfprintf       _IO_vfprintf
91 # define FILE           _IO_FILE
92 # undef va_list
93 # define va_list        _IO_va_list
94 # undef BUFSIZ
95 # define BUFSIZ         _IO_BUFSIZ
96 # define ARGCHECK(S, Format)                                                  \
97   do                                                                          \
98     {                                                                         \
99       /* Check file argument for consistence.  */                             \
100       CHECK_FILE (S, -1);                                                     \
101       if (S->_flags & _IO_NO_WRITES || Format == NULL)                        \
102         {                                                                     \
103           MAYBE_SET_EINVAL;                                                   \
104           return -1;                                                          \
105         }                                                                     \
106     } while (0)
107 # define UNBUFFERED_P(S) ((S)->_IO_file_flags & _IO_UNBUFFERED)
108 #else /* ! USE_IN_LIBIO */
109 /* This code is for use in the GNU C library.  */
110 # include <stdio.h>
111 # define PUT(F, S, N)   fwrite (S, 1, N, F)
112 # define ARGCHECK(S, Format)                                                  \
113   do                                                                          \
114     {                                                                         \
115       /* Check file argument for consistence.  */                             \
116       if (!__validfp(S) || !S->__mode.__write || Format == NULL)              \
117         {                                                                     \
118           __set_errno (EINVAL);                                               \
119           return -1;                                                          \
120         }                                                                     \
121       if (!S->__seen)                                                         \
122         {                                                                     \
123           if (__flshfp (S, EOF) == EOF)                                       \
124             return -1;                                                        \
125         }                                                                     \
126     }                                                                         \
127    while (0)
128 # define UNBUFFERED_P(s) ((s)->__buffer == NULL)
129
130 /* XXX These declarations should go as soon as the stdio header files
131    have these prototypes.   */
132 extern void __flockfile (FILE *);
133 extern void __funlockfile (FILE *);
134 #endif /* USE_IN_LIBIO */
135
136
137 #define outchar(Ch)                                                           \
138   do                                                                          \
139     {                                                                         \
140       register const int outc = (Ch);                                         \
141       if (PUTC (outc, s) == EOF)                                              \
142         return -1;                                                            \
143       else                                                                    \
144         ++done;                                                               \
145     }                                                                         \
146   while (0)
147
148 #define outstring(String, Len)                                                \
149   do                                                                          \
150     {                                                                         \
151       if ((size_t) PUT (s, (String), (Len)) != (size_t) (Len))                \
152         return -1;                                                            \
153       done += (Len);                                                          \
154     }                                                                         \
155   while (0)
156
157 /* For handling long_double and longlong we use the same flag.  */
158 #ifndef is_longlong
159 # define is_longlong is_long_double
160 #endif
161
162
163 /* Global variables.  */
164 static const char null[] = "(null)";
165
166
167 /* Helper function to provide temporary buffering for unbuffered streams.  */
168 static int buffered_vfprintf __P ((FILE *stream, const CHAR_T *fmt, va_list));
169
170 /* Handle unknown format specifier.  */
171 static int printf_unknown __P ((FILE *, const struct printf_info *,
172                                 const void *const *));
173
174 /* Group digits of number string.  */
175 static char *group_number __P ((CHAR_T *, CHAR_T *, const CHAR_T *, wchar_t));
176
177
178 /* The function itself.  */
179 int
180 vfprintf (FILE *s, const CHAR_T *format, va_list ap)
181 {
182   /* The character used as thousands separator.  */
183   wchar_t thousands_sep;
184
185   /* The string describing the size of groups of digits.  */
186   const char *grouping;
187
188   /* Place to accumulate the result.  */
189   int done;
190
191   /* Current character in format string.  */
192   const UCHAR_T *f;
193
194   /* End of leading constant string.  */
195   const UCHAR_T *lead_str_end;
196
197   /* Points to next format specifier.  */
198   const UCHAR_T *end_of_spec;
199
200   /* Buffer intermediate results.  */
201   char work_buffer[1000];
202 #define workend (&work_buffer[sizeof (work_buffer) - 1])
203
204   /* State for restartable multibyte character handling functions.  */
205   mbstate_t mbstate;
206
207   /* We have to save the original argument pointer.  */
208   va_list ap_save;
209
210   /* Count number of specifiers we already processed.  */
211   int nspecs_done;
212
213
214   /* This table maps a character into a number representing a
215      class.  In each step there is a destination label for each
216      class.  */
217   static const int jump_table[] =
218   {
219     /* ' ' */  1,            0,            0, /* '#' */  4,
220                0, /* '%' */ 14,            0, /* '\''*/  6,
221                0,            0, /* '*' */  7, /* '+' */  2,
222                0, /* '-' */  3, /* '.' */  9,            0,
223     /* '0' */  5, /* '1' */  8, /* '2' */  8, /* '3' */  8,
224     /* '4' */  8, /* '5' */  8, /* '6' */  8, /* '7' */  8,
225     /* '8' */  8, /* '9' */  8,            0,            0,
226                0,            0,            0,            0,
227                0,            0,            0, /* 'C' */ 25,
228                0, /* 'E' */ 19,            0, /* 'G' */ 19,
229                0,            0,            0,            0,
230     /* 'L' */ 12,            0,            0,            0,
231                0,            0,            0, /* 'S' */ 21,
232                0,            0,            0,            0,
233     /* 'X' */ 18,            0, /* 'Z' */ 13,            0,
234                0,            0,            0,            0,
235                0,            0,            0, /* 'c' */ 20,
236     /* 'd' */ 15, /* 'e' */ 19, /* 'f' */ 19, /* 'g' */ 19,
237     /* 'h' */ 10, /* 'i' */ 15,            0,            0,
238     /* 'l' */ 11, /* 'm' */ 24, /* 'n' */ 23, /* 'o' */ 17,
239     /* 'p' */ 22, /* 'q' */ 12,            0, /* 's' */ 21,
240                0, /* 'u' */ 16,            0,            0,
241     /* 'x' */ 18
242   };
243
244 #define NOT_IN_JUMP_RANGE(Ch) ((Ch) < ' ' || (Ch) > 'x')
245 #define CHAR_CLASS(Ch) (jump_table[(int) (Ch) - ' '])
246 #define JUMP(ChExpr, table)                                                   \
247       do                                                                      \
248         {                                                                     \
249           const void *ptr;                                                    \
250           spec = (ChExpr);                                                    \
251           ptr = NOT_IN_JUMP_RANGE (spec) ? REF (form_unknown)                 \
252             : table[CHAR_CLASS (spec)];                                       \
253           goto *ptr;                                                          \
254         }                                                                     \
255       while (0)
256
257 #define STEP0_3_TABLE                                                         \
258     /* Step 0: at the beginning.  */                                          \
259     static const void *step0_jumps[26] =                                      \
260     {                                                                         \
261       REF (form_unknown),                                                     \
262       REF (flag_space),         /* for ' ' */                                 \
263       REF (flag_plus),          /* for '+' */                                 \
264       REF (flag_minus),         /* for '-' */                                 \
265       REF (flag_hash),          /* for '<hash>' */                            \
266       REF (flag_zero),          /* for '0' */                                 \
267       REF (flag_quote),         /* for '\'' */                                \
268       REF (width_asterics),     /* for '*' */                                 \
269       REF (width),              /* for '1'...'9' */                           \
270       REF (precision),          /* for '.' */                                 \
271       REF (mod_half),           /* for 'h' */                                 \
272       REF (mod_long),           /* for 'l' */                                 \
273       REF (mod_longlong),       /* for 'L', 'q' */                            \
274       REF (mod_size_t),         /* for 'Z' */                                 \
275       REF (form_percent),       /* for '%' */                                 \
276       REF (form_integer),       /* for 'd', 'i' */                            \
277       REF (form_unsigned),      /* for 'u' */                                 \
278       REF (form_octal),         /* for 'o' */                                 \
279       REF (form_hexa),          /* for 'X', 'x' */                            \
280       REF (form_float),         /* for 'E', 'e', 'f', 'G', 'g' */             \
281       REF (form_character),     /* for 'c' */                                 \
282       REF (form_string),        /* for 's', 'S' */                            \
283       REF (form_pointer),       /* for 'p' */                                 \
284       REF (form_number),        /* for 'n' */                                 \
285       REF (form_strerror),      /* for 'm' */                                 \
286       REF (form_wcharacter)     /* for 'C' */                                 \
287     };                                                                        \
288     /* Step 1: after processing width.  */                                    \
289     static const void *step1_jumps[26] =                                      \
290     {                                                                         \
291       REF (form_unknown),                                                     \
292       REF (form_unknown),       /* for ' ' */                                 \
293       REF (form_unknown),       /* for '+' */                                 \
294       REF (form_unknown),       /* for '-' */                                 \
295       REF (form_unknown),       /* for '<hash>' */                            \
296       REF (form_unknown),       /* for '0' */                                 \
297       REF (form_unknown),       /* for '\'' */                                \
298       REF (form_unknown),       /* for '*' */                                 \
299       REF (form_unknown),       /* for '1'...'9' */                           \
300       REF (precision),          /* for '.' */                                 \
301       REF (mod_half),           /* for 'h' */                                 \
302       REF (mod_long),           /* for 'l' */                                 \
303       REF (mod_longlong),       /* for 'L', 'q' */                            \
304       REF (mod_size_t),         /* for 'Z' */                                 \
305       REF (form_percent),       /* for '%' */                                 \
306       REF (form_integer),       /* for 'd', 'i' */                            \
307       REF (form_unsigned),      /* for 'u' */                                 \
308       REF (form_octal),         /* for 'o' */                                 \
309       REF (form_hexa),          /* for 'X', 'x' */                            \
310       REF (form_float),         /* for 'E', 'e', 'f', 'G', 'g' */             \
311       REF (form_character),     /* for 'c' */                                 \
312       REF (form_string),        /* for 's', 'S' */                            \
313       REF (form_pointer),       /* for 'p' */                                 \
314       REF (form_number),        /* for 'n' */                                 \
315       REF (form_strerror),      /* for 'm' */                                 \
316       REF (form_wcharacter)     /* for 'C' */                                 \
317     };                                                                        \
318     /* Step 2: after processing precision.  */                                \
319     static const void *step2_jumps[26] =                                      \
320     {                                                                         \
321       REF (form_unknown),                                                     \
322       REF (form_unknown),       /* for ' ' */                                 \
323       REF (form_unknown),       /* for '+' */                                 \
324       REF (form_unknown),       /* for '-' */                                 \
325       REF (form_unknown),       /* for '<hash>' */                            \
326       REF (form_unknown),       /* for '0' */                                 \
327       REF (form_unknown),       /* for '\'' */                                \
328       REF (form_unknown),       /* for '*' */                                 \
329       REF (form_unknown),       /* for '1'...'9' */                           \
330       REF (form_unknown),       /* for '.' */                                 \
331       REF (mod_half),           /* for 'h' */                                 \
332       REF (mod_long),           /* for 'l' */                                 \
333       REF (mod_longlong),       /* for 'L', 'q' */                            \
334       REF (mod_size_t),         /* for 'Z' */                                 \
335       REF (form_percent),       /* for '%' */                                 \
336       REF (form_integer),       /* for 'd', 'i' */                            \
337       REF (form_unsigned),      /* for 'u' */                                 \
338       REF (form_octal),         /* for 'o' */                                 \
339       REF (form_hexa),          /* for 'X', 'x' */                            \
340       REF (form_float),         /* for 'E', 'e', 'f', 'G', 'g' */             \
341       REF (form_character),     /* for 'c' */                                 \
342       REF (form_string),        /* for 's', 'S' */                            \
343       REF (form_pointer),       /* for 'p' */                                 \
344       REF (form_number),        /* for 'n' */                                 \
345       REF (form_strerror),      /* for 'm' */                                 \
346       REF (form_wcharacter)     /* for 'C' */                                 \
347     };                                                                        \
348     /* Step 3: after processing first 'l' modifier.  */                       \
349     static const void *step3_jumps[26] =                                      \
350     {                                                                         \
351       REF (form_unknown),                                                     \
352       REF (form_unknown),       /* for ' ' */                                 \
353       REF (form_unknown),       /* for '+' */                                 \
354       REF (form_unknown),       /* for '-' */                                 \
355       REF (form_unknown),       /* for '<hash>' */                            \
356       REF (form_unknown),       /* for '0' */                                 \
357       REF (form_unknown),       /* for '\'' */                                \
358       REF (form_unknown),       /* for '*' */                                 \
359       REF (form_unknown),       /* for '1'...'9' */                           \
360       REF (form_unknown),       /* for '.' */                                 \
361       REF (form_unknown),       /* for 'h' */                                 \
362       REF (mod_longlong),       /* for 'l' */                                 \
363       REF (form_unknown),       /* for 'L', 'q' */                            \
364       REF (form_unknown),       /* for 'Z' */                                 \
365       REF (form_percent),       /* for '%' */                                 \
366       REF (form_integer),       /* for 'd', 'i' */                            \
367       REF (form_unsigned),      /* for 'u' */                                 \
368       REF (form_octal),         /* for 'o' */                                 \
369       REF (form_hexa),          /* for 'X', 'x' */                            \
370       REF (form_float),         /* for 'E', 'e', 'f', 'G', 'g' */             \
371       REF (form_character),     /* for 'c' */                                 \
372       REF (form_string),        /* for 's', 'S' */                            \
373       REF (form_pointer),       /* for 'p' */                                 \
374       REF (form_number),        /* for 'n' */                                 \
375       REF (form_strerror),      /* for 'm' */                                 \
376       REF (form_wcharacter)     /* for 'C' */                                 \
377     }
378
379 #define STEP4_TABLE                                                           \
380     /* Step 4: processing format specifier.  */                               \
381     static const void *step4_jumps[26] =                                      \
382     {                                                                         \
383       REF (form_unknown),                                                     \
384       REF (form_unknown),       /* for ' ' */                                 \
385       REF (form_unknown),       /* for '+' */                                 \
386       REF (form_unknown),       /* for '-' */                                 \
387       REF (form_unknown),       /* for '<hash>' */                            \
388       REF (form_unknown),       /* for '0' */                                 \
389       REF (form_unknown),       /* for '\'' */                                \
390       REF (form_unknown),       /* for '*' */                                 \
391       REF (form_unknown),       /* for '1'...'9' */                           \
392       REF (form_unknown),       /* for '.' */                                 \
393       REF (form_unknown),       /* for 'h' */                                 \
394       REF (form_unknown),       /* for 'l' */                                 \
395       REF (form_unknown),       /* for 'L', 'q' */                            \
396       REF (form_unknown),       /* for 'Z' */                                 \
397       REF (form_percent),       /* for '%' */                                 \
398       REF (form_integer),       /* for 'd', 'i' */                            \
399       REF (form_unsigned),      /* for 'u' */                                 \
400       REF (form_octal),         /* for 'o' */                                 \
401       REF (form_hexa),          /* for 'X', 'x' */                            \
402       REF (form_float),         /* for 'E', 'e', 'f', 'G', 'g' */             \
403       REF (form_character),     /* for 'c' */                                 \
404       REF (form_string),        /* for 's', 'S' */                            \
405       REF (form_pointer),       /* for 'p' */                                 \
406       REF (form_number),        /* for 'n' */                                 \
407       REF (form_strerror),      /* for 'm' */                                 \
408       REF (form_wcharacter)     /* for 'C' */                                 \
409     }
410
411
412 #define process_arg(fspec)                                                    \
413       /* Start real work.  We know about all flags and modifiers and          \
414          now process the wanted format specifier.  */                         \
415     LABEL (form_percent):                                                     \
416       /* Write a literal "%".  */                                             \
417       outchar ('%');                                                          \
418       break;                                                                  \
419                                                                               \
420     LABEL (form_integer):                                                     \
421       /* Signed decimal integer.  */                                          \
422       base = 10;                                                              \
423                                                                               \
424       if (is_longlong)                                                        \
425         {                                                                     \
426           long long int signed_number;                                        \
427                                                                               \
428           if (fspec == NULL)                                                  \
429             signed_number = va_arg (ap, long long int);                       \
430           else                                                                \
431             signed_number = args_value[fspec->data_arg].pa_long_long_int;     \
432                                                                               \
433           is_negative = signed_number < 0;                                    \
434           number.longlong = is_negative ? (- signed_number) : signed_number;  \
435                                                                               \
436           goto LABEL (longlong_number);                                       \
437         }                                                                     \
438       else                                                                    \
439         {                                                                     \
440           long int signed_number;                                             \
441                                                                               \
442           if (fspec == NULL)                                                  \
443             if (is_long)                                                      \
444               signed_number = va_arg (ap, long int);                          \
445             else        /* `short int' will be promoted to `int'.  */         \
446               signed_number = va_arg (ap, int);                               \
447           else                                                                \
448             if (is_long)                                                      \
449               signed_number = args_value[fspec->data_arg].pa_long_int;        \
450             else                                                              \
451               signed_number = args_value[fspec->data_arg].pa_int;             \
452                                                                               \
453           is_negative = signed_number < 0;                                    \
454           number.word = is_negative ? (- signed_number) : signed_number;      \
455                                                                               \
456           goto LABEL (number);                                                \
457         }                                                                     \
458       /* NOTREACHED */                                                        \
459                                                                               \
460     LABEL (form_unsigned):                                                    \
461       /* Unsigned decimal integer.  */                                        \
462       base = 10;                                                              \
463       goto LABEL (unsigned_number);                                           \
464       /* NOTREACHED */                                                        \
465                                                                               \
466     LABEL (form_octal):                                                       \
467       /* Unsigned octal integer.  */                                          \
468       base = 8;                                                               \
469       goto LABEL (unsigned_number);                                           \
470       /* NOTREACHED */                                                        \
471                                                                               \
472     LABEL (form_hexa):                                                        \
473       /* Unsigned hexadecimal integer.  */                                    \
474       base = 16;                                                              \
475                                                                               \
476     LABEL (unsigned_number):      /* Unsigned number of base BASE.  */        \
477                                                                               \
478       /* ANSI specifies the `+' and ` ' flags only for signed                 \
479          conversions.  */                                                     \
480       is_negative = 0;                                                        \
481       showsign = 0;                                                           \
482       space = 0;                                                              \
483                                                                               \
484       if (is_longlong)                                                        \
485         {                                                                     \
486           if (fspec == NULL)                                                  \
487             number.longlong = va_arg (ap, unsigned long long int);            \
488           else                                                                \
489             number.longlong = args_value[fspec->data_arg].pa_u_long_long_int; \
490                                                                               \
491         LABEL (longlong_number):                                              \
492           if (prec < 0)                                                       \
493             /* Supply a default precision if none was given.  */              \
494             prec = 1;                                                         \
495           else                                                                \
496             /* We have to take care for the '0' flag.  If a precision         \
497                is given it must be ignored.  */                               \
498             pad = ' ';                                                        \
499                                                                               \
500           /* If the precision is 0 and the number is 0 nothing has to         \
501              be written for the number.  */                                   \
502           if (prec == 0 && number.longlong == 0)                              \
503             string = workend;                                                 \
504           else                                                                \
505             {                                                                 \
506               /* Put the number in WORK.  */                                  \
507               string = _itoa (number.longlong, workend + 1, base,             \
508                               spec == 'X');                                   \
509               string -= 1;                                                    \
510               if (group && grouping)                                          \
511                 string = group_number (string, workend, grouping,             \
512                                        thousands_sep);                        \
513             }                                                                 \
514           /* Simply further test for num != 0.  */                            \
515           number.word = number.longlong != 0;                                 \
516         }                                                                     \
517       else                                                                    \
518         {                                                                     \
519           if (fspec == NULL)                                                  \
520             if (is_long)                                                      \
521               number.word = va_arg (ap, unsigned long int);                   \
522             else if (!is_short)                                               \
523               number.word = va_arg (ap, unsigned int);                        \
524             else                                                              \
525               number.word = (unsigned short int) va_arg (ap, unsigned int);   \
526           else                                                                \
527             if (is_long)                                                      \
528               number.word = args_value[fspec->data_arg].pa_u_long_int;        \
529             else if (!is_short)                                               \
530               number.word = args_value[fspec->data_arg].pa_u_int;             \
531             else                                                              \
532               number.word = (unsigned short int)                              \
533                 args_value[fspec->data_arg].pa_u_short_int;                   \
534                                                                               \
535         LABEL (number):                                                       \
536           if (prec < 0)                                                       \
537             /* Supply a default precision if none was given.  */              \
538             prec = 1;                                                         \
539           else                                                                \
540             /* We have to take care for the '0' flag.  If a precision         \
541                is given it must be ignored.  */                               \
542             pad = ' ';                                                        \
543                                                                               \
544           /* If the precision is 0 and the number is 0 nothing has to         \
545              be written for the number.  */                                   \
546           if (prec == 0 && number.word == 0)                                  \
547             string = workend;                                                 \
548           else                                                                \
549             {                                                                 \
550               /* Put the number in WORK.  */                                  \
551               string = _itoa_word (number.word, workend + 1, base,            \
552                                    spec == 'X');                              \
553               string -= 1;                                                    \
554               if (group && grouping)                                          \
555                 string = group_number (string, workend, grouping,             \
556                                        thousands_sep);                        \
557             }                                                                 \
558         }                                                                     \
559                                                                               \
560       prec -= workend - string;                                               \
561                                                                               \
562       if (prec > 0)                                                           \
563         /* Add zeros to the precision.  */                                    \
564         while (prec-- > 0)                                                    \
565           *string-- = '0';                                                    \
566       else if (number.word != 0 && alt && base == 8)                          \
567         /* Add octal marker.  */                                              \
568         *string-- = '0';                                                      \
569                                                                               \
570       if (!left)                                                              \
571         {                                                                     \
572           width -= workend - string;                                          \
573                                                                               \
574           if (number.word != 0 && alt && base == 16)                          \
575             /* Account for 0X hex marker.  */                                 \
576             width -= 2;                                                       \
577                                                                               \
578           if (is_negative || showsign || space)                               \
579             --width;                                                          \
580                                                                               \
581           if (pad == '0')                                                     \
582             {                                                                 \
583               while (width-- > 0)                                             \
584                 *string-- = '0';                                              \
585                                                                               \
586               if (number.word != 0 && alt && base == 16)                      \
587                 {                                                             \
588                   *string-- = spec;                                           \
589                   *string-- = '0';                                            \
590                 }                                                             \
591                                                                               \
592               if (is_negative)                                                \
593                 *string-- = '-';                                              \
594               else if (showsign)                                              \
595                 *string-- = '+';                                              \
596               else if (space)                                                 \
597                 *string-- = ' ';                                              \
598             }                                                                 \
599           else                                                                \
600             {                                                                 \
601               if (number.word != 0 && alt && base == 16)                      \
602                 {                                                             \
603                   *string-- = spec;                                           \
604                   *string-- = '0';                                            \
605                 }                                                             \
606                                                                               \
607               if (is_negative)                                                \
608                 *string-- = '-';                                              \
609               else if (showsign)                                              \
610                 *string-- = '+';                                              \
611               else if (space)                                                 \
612                 *string-- = ' ';                                              \
613                                                                               \
614               while (width-- > 0)                                             \
615                 *string-- = ' ';                                              \
616             }                                                                 \
617                                                                               \
618           outstring (string + 1, workend - string);                           \
619                                                                               \
620           break;                                                              \
621         }                                                                     \
622       else                                                                    \
623         {                                                                     \
624           if (number.word != 0 && alt && base == 16)                          \
625             {                                                                 \
626               *string-- = spec;                                               \
627               *string-- = '0';                                                \
628             }                                                                 \
629                                                                               \
630           if (is_negative)                                                    \
631             *string-- = '-';                                                  \
632           else if (showsign)                                                  \
633             *string-- = '+';                                                  \
634           else if (space)                                                     \
635             *string-- = ' ';                                                  \
636                                                                               \
637           width -= workend - string;                                          \
638           outstring (string + 1, workend - string);                           \
639                                                                               \
640           PAD (' ');                                                          \
641           break;                                                              \
642         }                                                                     \
643                                                                               \
644     LABEL (form_float):                                                       \
645       {                                                                       \
646         /* Floating-point number.  This is handled by printf_fp.c.  */        \
647         extern int __printf_fp __P ((FILE *, const struct printf_info *,      \
648                                      const void **const));                    \
649         const void *ptr;                                                      \
650         int function_done;                                                    \
651                                                                               \
652         if (fspec == NULL)                                                    \
653           {                                                                   \
654             struct printf_info info = { prec: prec,                           \
655                                         width: width,                         \
656                                         spec: spec,                           \
657                                         is_long_double: is_long_double,       \
658                                         is_short: is_short,                   \
659                                         is_long: is_long,                     \
660                                         alt: alt,                             \
661                                         space: space,                         \
662                                         left: left,                           \
663                                         showsign: showsign,                   \
664                                         group: group,                         \
665                                         pad: pad,                             \
666                                         extra: 0 };                           \
667                                                                               \
668             if (is_long_double)                                               \
669               the_arg.pa_long_double = va_arg (ap, long double);              \
670             else                                                              \
671               the_arg.pa_double = va_arg (ap, double);                        \
672             ptr = (const void *) &the_arg;                                    \
673                                                                               \
674             function_done = __printf_fp (s, &info, &ptr);                     \
675           }                                                                   \
676         else                                                                  \
677           {                                                                   \
678             ptr = (const void *) &args_value[fspec->data_arg];                \
679                                                                               \
680             function_done = __printf_fp (s, &fspec->info, &ptr);              \
681           }                                                                   \
682                                                                               \
683         if (function_done < 0)                                                \
684           /* Error in print handler.  */                                      \
685           return -1;                                                          \
686                                                                               \
687         done += function_done;                                                \
688       }                                                                       \
689       break;                                                                  \
690                                                                               \
691     LABEL (form_character):                                                   \
692       /* Character.  */                                                       \
693       if (is_long)                                                            \
694         goto LABEL (form_wcharacter);                                         \
695       --width;  /* Account for the character itself.  */                      \
696       if (!left)                                                              \
697         PAD (' ');                                                            \
698       if (fspec == NULL)                                                      \
699         outchar ((unsigned char) va_arg (ap, int)); /* Promoted.  */          \
700       else                                                                    \
701         outchar ((unsigned char) args_value[fspec->data_arg].pa_char);        \
702       if (left)                                                               \
703         PAD (' ');                                                            \
704       break;                                                                  \
705                                                                               \
706     LABEL (form_wcharacter):                                                  \
707       {                                                                       \
708         /* Wide character.  */                                                \
709         char buf[MB_CUR_MAX];                                                 \
710         mbstate_t mbstate;                                                    \
711         size_t len;                                                           \
712                                                                               \
713         len = __wcrtomb (buf, (fspec == NULL ? va_arg (ap, wint_t)            \
714                                : args_value[fspec->data_arg].pa_wchar),       \
715                          &mbstate);                                           \
716         width -= len;                                                         \
717         if (!left)                                                            \
718           PAD (' ');                                                          \
719         outstring (buf, len);                                                 \
720         if (left)                                                             \
721           PAD (' ');                                                          \
722       }                                                                       \
723       break;                                                                  \
724                                                                               \
725     LABEL (form_string):                                                      \
726       {                                                                       \
727         size_t len;                                                           \
728                                                                               \
729         /* The string argument could in fact be `char *' or `wchar_t *'.      \
730            But this should not make a difference here.  */                    \
731         if (fspec == NULL)                                                    \
732           string = (char *) va_arg (ap, const char *);                        \
733         else                                                                  \
734           string = (char *) args_value[fspec->data_arg].pa_string;            \
735                                                                               \
736         /* Entry point for printing other strings.  */                        \
737       LABEL (print_string):                                                   \
738                                                                               \
739         if (string == NULL)                                                   \
740           {                                                                   \
741             /* Write "(null)" if there's space.  */                           \
742             if (prec == -1 || prec >= (int) sizeof (null) - 1)                \
743               {                                                               \
744                 string = (char *) null;                                       \
745                 len = sizeof (null) - 1;                                      \
746               }                                                               \
747             else                                                              \
748               {                                                               \
749                 string = (char *) "";                                         \
750                 len = 0;                                                      \
751               }                                                               \
752           }                                                                   \
753         else if (!is_long && spec != L_('S'))                                 \
754           {                                                                   \
755             if (prec != -1)                                                   \
756               /* Search for the end of the string, but don't search past      \
757                  the length specified by the precision.  */                   \
758               len = strnlen (string, prec);                                   \
759             else                                                              \
760               len = strlen (string);                                          \
761           }                                                                   \
762         else                                                                  \
763           {                                                                   \
764             const wchar_t *s2 = (const wchar_t *) string;                     \
765             mbstate_t mbstate;                                                \
766                                                                               \
767             len = __wcsrtombs (NULL, &s2, 0, &mbstate);                       \
768             if (len == (size_t) -1)                                           \
769               /* Illegal wide-character string.  */                           \
770               return -1;                                                      \
771                                                                               \
772             s2 = (const wchar_t *) string;                                    \
773             string = alloca (len + 1);                                        \
774             (void) __wcsrtombs (string, &s2, prec != -1 ? prec : UINT_MAX,    \
775                                 &mbstate);                                    \
776           }                                                                   \
777                                                                               \
778         if ((width -= len) < 0)                                               \
779           {                                                                   \
780             outstring (string, len);                                          \
781             break;                                                            \
782           }                                                                   \
783                                                                               \
784         if (!left)                                                            \
785           PAD (' ');                                                          \
786         outstring (string, len);                                              \
787         if (left)                                                             \
788           PAD (' ');                                                          \
789       }                                                                       \
790       break;                                                                  \
791                                                                               \
792     LABEL (form_pointer):                                                     \
793       /* Generic pointer.  */                                                 \
794       {                                                                       \
795         const void *ptr;                                                      \
796         if (fspec == NULL)                                                    \
797           ptr = va_arg (ap, void *);                                          \
798         else                                                                  \
799           ptr = args_value[fspec->data_arg].pa_pointer;                       \
800         if (ptr != NULL)                                                      \
801           {                                                                   \
802             /* If the pointer is not NULL, write it as a %#x spec.  */        \
803             base = 16;                                                        \
804             number.word = (unsigned long int) ptr;                            \
805             is_negative = 0;                                                  \
806             alt = 1;                                                          \
807             group = 0;                                                        \
808             spec = 'x';                                                       \
809             goto LABEL (number);                                              \
810           }                                                                   \
811         else                                                                  \
812           {                                                                   \
813             /* Write "(nil)" for a nil pointer.  */                           \
814             string = (char *) "(nil)";                                        \
815             /* Make sure the full string "(nil)" is printed.  */              \
816             if (prec < 5)                                                     \
817               prec = 5;                                                       \
818             is_long = 0;        /* This is no wide-char string.  */           \
819             goto LABEL (print_string);                                        \
820           }                                                                   \
821       }                                                                       \
822       /* NOTREACHED */                                                        \
823                                                                               \
824     LABEL (form_number):                                                      \
825       /* Answer the count of characters written.  */                          \
826       if (fspec == NULL)                                                      \
827         if (is_longlong)                                                      \
828           *(long long int *) va_arg (ap, void *) = done;                      \
829         else if (is_long)                                                     \
830           *(long int *) va_arg (ap, void *) = done;                           \
831         else if (!is_short)                                                   \
832           *(int *) va_arg (ap, void *) = done;                                \
833         else                                                                  \
834           *(short int *) va_arg (ap, void *) = done;                          \
835       else                                                                    \
836         if (is_longlong)                                                      \
837           *(long long int *) args_value[fspec->data_arg].pa_pointer = done;   \
838         else if (is_long)                                                     \
839           *(long int *) args_value[fspec->data_arg].pa_pointer = done;        \
840         else if (!is_short)                                                   \
841           *(int *) args_value[fspec->data_arg].pa_pointer = done;             \
842         else                                                                  \
843           *(short int *) args_value[fspec->data_arg].pa_pointer = done;       \
844       break;                                                                  \
845                                                                               \
846     LABEL (form_strerror):                                                    \
847       /* Print description of error ERRNO.  */                                \
848       {                                                                       \
849         extern char *_strerror_internal __P ((int, char *buf, size_t));       \
850                                                                               \
851         string = (char *)                                                     \
852           _strerror_internal (errno, work_buffer, sizeof work_buffer);        \
853       }                                                                       \
854       is_long = 0;              /* This is no wide-char string.  */           \
855       goto LABEL (print_string)
856
857
858   /* Sanity check of arguments.  */
859   ARGCHECK (s, format);
860
861   if (UNBUFFERED_P (s))
862     /* Use a helper function which will allocate a local temporary buffer
863        for the stream and then call us again.  */
864     return buffered_vfprintf (s, format, ap);
865
866   /* Initialize local variables.  */
867   done = 0;
868   grouping = (const char *) -1;
869   ap_save = ap;
870   nspecs_done = 0;
871
872   /* Find the first format specifier.  */
873   f = lead_str_end = find_spec (format, &mbstate);
874
875   /* Lock stream.  */
876 #ifdef USE_IN_LIBIO
877   __libc_cleanup_region_start ((void (*) (void *)) &_IO_funlockfile, s);
878   _IO_flockfile (s);
879 #else
880   __libc_cleanup_region_start ((void (*) (void *)) &__funlockfile, s);
881   __flockfile (s);
882 #endif
883
884   /* Write the literal text before the first format.  */
885   outstring ((const UCHAR_T *) format,
886              lead_str_end - (const UCHAR_T *) format);
887
888   /* If we only have to print a simple string, return now.  */
889   if (*f == L_('\0'))
890     goto all_done;
891
892   /* Process whole format string.  */
893   do
894     {
895 #define REF(Name) &&do_##Name
896 #define LABEL(Name) do_##Name
897       STEP0_3_TABLE;
898       STEP4_TABLE;
899
900       union printf_arg *args_value;     /* This is not used here but ... */
901       int is_negative;  /* Flag for negative number.  */
902       union
903       {
904         unsigned long long int longlong;
905         unsigned long int word;
906       } number;
907       int base;
908       union printf_arg the_arg;
909       char *string;     /* Pointer to argument string.  */
910       int alt = 0;      /* Alternate format.  */
911       int space = 0;    /* Use space prefix if no sign is needed.  */
912       int left = 0;     /* Left-justify output.  */
913       int showsign = 0; /* Always begin with plus or minus sign.  */
914       int group = 0;    /* Print numbers according grouping rules.  */
915       int is_long_double = 0; /* Argument is long double/ long long int.  */
916       int is_short = 0; /* Argument is long int.  */
917       int is_long = 0;  /* Argument is short int.  */
918       int width = 0;    /* Width of output; 0 means none specified.  */
919       int prec = -1;    /* Precision of output; -1 means none specified.  */
920       char pad = ' ';   /* Padding character.  */
921       CHAR_T spec;
922
923       /* Get current character in format string.  */
924       JUMP (*++f, step0_jumps);
925
926       /* ' ' flag.  */
927     LABEL (flag_space):
928       space = 1;
929       JUMP (*++f, step0_jumps);
930
931       /* '+' flag.  */
932     LABEL (flag_plus):
933       showsign = 1;
934       JUMP (*++f, step0_jumps);
935
936       /* The '-' flag.  */
937     LABEL (flag_minus):
938       left = 1;
939       pad = L_(' ');
940       JUMP (*++f, step0_jumps);
941
942       /* The '#' flag.  */
943     LABEL (flag_hash):
944       alt = 1;
945       JUMP (*++f, step0_jumps);
946
947       /* The '0' flag.  */
948     LABEL (flag_zero):
949       if (!left)
950         pad = L_('0');
951       JUMP (*++f, step0_jumps);
952
953       /* The '\'' flag.  */
954     LABEL (flag_quote):
955       group = 1;
956
957       /* XXX Completely wrong.  Use wctob.  */
958       if (grouping == (const char *) -1)
959         {
960           /* Figure out the thousands separator character.  */
961           if (mbtowc (&thousands_sep,
962                       _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
963                       strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
964             thousands_sep = (wchar_t)
965               *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
966           grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
967           if (*grouping == '\0' || *grouping == CHAR_MAX
968               || thousands_sep == L'\0')
969             grouping = NULL;
970         }
971       JUMP (*++f, step0_jumps);
972
973       /* Get width from argument.  */
974     LABEL (width_asterics):
975       {
976         const UCHAR_T *tmp;     /* Temporary value.  */
977
978         tmp = ++f;
979         if (ISDIGIT (*tmp) && read_int (&tmp) && *tmp == L_('$'))
980           /* The width comes from a positional parameter.  */
981           goto do_positional;
982
983         width = va_arg (ap, int);
984
985         /* Negative width means left justified.  */
986         if (width < 0)
987           {
988             width = -width;
989             pad = L_(' ');
990             left = 1;
991           }
992       }
993       JUMP (*f, step1_jumps);
994
995       /* Given width in format string.  */
996     LABEL (width):
997       width = read_int (&f);
998       if (*f == L_('$'))
999         /* Oh, oh.  The argument comes from a positional parameter.  */
1000         goto do_positional;
1001       JUMP (*f, step1_jumps);
1002
1003     LABEL (precision):
1004       ++f;
1005       if (*f == L_('*'))
1006         {
1007           const UCHAR_T *tmp;   /* Temporary value.  */
1008
1009           tmp = ++f;
1010           if (ISDIGIT (*tmp) && read_int (&tmp) > 0 && *tmp == L_('$'))
1011             /* The precision comes from a positional parameter.  */
1012             goto do_positional;
1013
1014           prec = va_arg (ap, int);
1015
1016           /* If the precision is negative the precision is omitted.  */
1017           if (prec < 0)
1018             prec = -1;
1019         }
1020       else if (ISDIGIT (*f))
1021         prec = read_int (&f);
1022       else
1023         prec = 0;
1024       JUMP (*f, step2_jumps);
1025
1026       /* Process 'h' modifier.  No other modifier is allowed to
1027          follow.  */
1028     LABEL (mod_half):
1029       is_short = 1;
1030       JUMP (*++f, step4_jumps);
1031
1032       /* Process 'l' modifier.  There might another 'l' follow.  */
1033     LABEL (mod_long):
1034       is_long = 1;
1035       JUMP (*++f, step3_jumps);
1036
1037       /* Process 'L', 'q', or 'll' modifier.  No other modifier is
1038          allowed to follow.  */
1039     LABEL (mod_longlong):
1040       is_long_double = 1;
1041       JUMP (*++f, step4_jumps);
1042
1043     LABEL (mod_size_t):
1044       is_longlong = sizeof (size_t) > sizeof (unsigned long int);
1045       is_long = sizeof (size_t) > sizeof (unsigned int);
1046       JUMP (*++f, step4_jumps);
1047
1048
1049       /* Process current format.  */
1050       while (1)
1051         {
1052           process_arg (((struct printf_spec *) NULL));
1053
1054         LABEL (form_unknown):
1055           if (spec == L_('\0'))
1056             {
1057               /* The format string ended before the specifier is complete.  */
1058               done = -1;
1059               goto all_done;
1060             }
1061
1062           /* If we are in the fast loop force entering the complicated
1063              one.  */
1064           goto do_positional;
1065         }
1066
1067       /* Look for next format specifier.  */
1068       f = find_spec ((end_of_spec = ++f), &mbstate);
1069
1070       /* Write the following constant string.  */
1071       outstring (end_of_spec, f - end_of_spec);
1072     }
1073   while (*f != L_('\0'));
1074
1075   /* Unlock stream and return.  */
1076   goto all_done;
1077
1078   /* Here starts the more complex loop to handle positional parameters.  */
1079 do_positional:
1080   {
1081     /* Array with information about the needed arguments.  This has to
1082        be dynamically extendable.  */
1083     size_t nspecs = 0;
1084     size_t nspecs_max = 32;     /* A more or less arbitrary start value.  */
1085     struct printf_spec *specs
1086       = alloca (nspecs_max * sizeof (struct printf_spec));
1087
1088     /* The number of arguments the format string requests.  This will
1089        determine the size of the array needed to store the argument
1090        attributes.  */
1091     size_t nargs = 0;
1092     int *args_type;
1093     union printf_arg *args_value;
1094
1095     /* Positional parameters refer to arguments directly.  This could
1096        also determine the maximum number of arguments.  Track the
1097        maximum number.  */
1098     size_t max_ref_arg = 0;
1099
1100     /* Just a counter.  */
1101     size_t cnt;
1102
1103
1104     if (grouping == (const char *) -1)
1105       {
1106         /* XXX Use wctob.  But this is incompatible for now.  */
1107         /* Figure out the thousands separator character.  */
1108         if (mbtowc (&thousands_sep,
1109                     _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
1110                     strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
1111           thousands_sep = (wchar_t) *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
1112         grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
1113         if (*grouping == '\0' || *grouping == CHAR_MAX
1114             || thousands_sep == L'\0')
1115           grouping = NULL;
1116       }
1117
1118     for (f = lead_str_end; *f != '\0'; f = specs[nspecs++].next_fmt)
1119       {
1120         if (nspecs >= nspecs_max)
1121           {
1122             /* Extend the array of format specifiers.  */
1123             struct printf_spec *old = specs;
1124
1125             nspecs_max *= 2;
1126             specs = alloca (nspecs_max * sizeof (struct printf_spec));
1127
1128             if (specs == &old[nspecs])
1129               /* Stack grows up, OLD was the last thing allocated;
1130                  extend it.  */
1131               nspecs_max += nspecs_max / 2;
1132             else
1133               {
1134                 /* Copy the old array's elements to the new space.  */
1135                 memcpy (specs, old, nspecs * sizeof (struct printf_spec));
1136                 if (old == &specs[nspecs])
1137                   /* Stack grows down, OLD was just below the new
1138                      SPECS.  We can use that space when the new space
1139                      runs out.  */
1140                   nspecs_max += nspecs_max / 2;
1141               }
1142           }
1143
1144         /* Parse the format specifier.  */
1145         nargs += parse_one_spec (f, nargs, &specs[nspecs], &max_ref_arg,
1146                                  &mbstate);
1147       }
1148
1149     /* Determine the number of arguments the format string consumes.  */
1150     nargs = MAX (nargs, max_ref_arg);
1151
1152     /* Allocate memory for the argument descriptions.  */
1153     args_type = alloca (nargs * sizeof (int));
1154     memset (args_type, 0, nargs * sizeof (int));
1155     args_value = alloca (nargs * sizeof (union printf_arg));
1156
1157     /* XXX Could do sanity check here: If any element in ARGS_TYPE is
1158        still zero after this loop, format is invalid.  For now we
1159        simply use 0 as the value.  */
1160
1161     /* Fill in the types of all the arguments.  */
1162     for (cnt = 0; cnt < nspecs; ++cnt)
1163       {
1164         /* If the width is determined by an argument this is an int.  */
1165         if (specs[cnt].width_arg != -1)
1166           args_type[specs[cnt].width_arg] = PA_INT;
1167
1168         /* If the precision is determined by an argument this is an int.  */
1169         if (specs[cnt].prec_arg != -1)
1170           args_type[specs[cnt].prec_arg] = PA_INT;
1171
1172         switch (specs[cnt].ndata_args)
1173           {
1174           case 0:               /* No arguments.  */
1175             break;
1176           case 1:               /* One argument; we already have the type.  */
1177             args_type[specs[cnt].data_arg] = specs[cnt].data_arg_type;
1178             break;
1179           default:
1180             /* We have more than one argument for this format spec.
1181                We must call the arginfo function again to determine
1182                all the types.  */
1183             (void) (*__printf_arginfo_table[specs[cnt].info.spec])
1184               (&specs[cnt].info,
1185                specs[cnt].ndata_args, &args_type[specs[cnt].data_arg]);
1186             break;
1187           }
1188       }
1189
1190     /* Now we know all the types and the order.  Fill in the argument
1191        values.  */
1192     for (cnt = 0, ap = ap_save; cnt < nargs; ++cnt)
1193       switch (args_type[cnt])
1194         {
1195 #define T(tag, mem, type)                                                     \
1196         case tag:                                                             \
1197           args_value[cnt].mem = va_arg (ap, type);                            \
1198           break
1199
1200         T (PA_CHAR, pa_char, int); /* Promoted.  */
1201         T (PA_WCHAR, pa_wchar, wint_t);
1202         T (PA_INT|PA_FLAG_SHORT, pa_short_int, int); /* Promoted.  */
1203         T (PA_INT, pa_int, int);
1204         T (PA_INT|PA_FLAG_LONG, pa_long_int, long int);
1205         T (PA_INT|PA_FLAG_LONG_LONG, pa_long_long_int, long long int);
1206         T (PA_FLOAT, pa_float, double); /* Promoted.  */
1207         T (PA_DOUBLE, pa_double, double);
1208         T (PA_DOUBLE|PA_FLAG_LONG_DOUBLE, pa_long_double, long double);
1209         T (PA_STRING, pa_string, const char *);
1210         T (PA_WSTRING, pa_wstring, const wchar_t *);
1211         T (PA_POINTER, pa_pointer, void *);
1212 #undef T
1213         default:
1214           if ((args_type[cnt] & PA_FLAG_PTR) != 0)
1215             args_value[cnt].pa_pointer = va_arg (ap, void *);
1216           else
1217             args_value[cnt].pa_long_double = 0.0;
1218           break;
1219         }
1220
1221     /* Now walk through all format specifiers and process them.  */
1222     for (; (size_t) nspecs_done < nspecs; ++nspecs_done)
1223       {
1224 #undef REF
1225 #define REF(Name) &&do2_##Name
1226 #undef LABEL
1227 #define LABEL(Name) do2_##Name
1228         STEP4_TABLE;
1229
1230         int is_negative;
1231         union
1232         {
1233           unsigned long long int longlong;
1234           unsigned long int word;
1235         } number;
1236         int base;
1237         union printf_arg the_arg;
1238         char *string;   /* Pointer to argument string.  */
1239
1240         /* Fill variables from values in struct.  */
1241         int alt = specs[nspecs_done].info.alt;
1242         int space = specs[nspecs_done].info.space;
1243         int left = specs[nspecs_done].info.left;
1244         int showsign = specs[nspecs_done].info.showsign;
1245         int group = specs[nspecs_done].info.group;
1246         int is_long_double = specs[nspecs_done].info.is_long_double;
1247         int is_short = specs[nspecs_done].info.is_short;
1248         int is_long = specs[nspecs_done].info.is_long;
1249         int width = specs[nspecs_done].info.width;
1250         int prec = specs[nspecs_done].info.prec;
1251         char pad = specs[nspecs_done].info.pad;
1252         CHAR_T spec = specs[nspecs_done].info.spec;
1253
1254         /* Fill in last information.  */
1255         if (specs[nspecs_done].width_arg != -1)
1256           {
1257             /* Extract the field width from an argument.  */
1258             specs[nspecs_done].info.width =
1259               args_value[specs[nspecs_done].width_arg].pa_int;
1260
1261             if (specs[nspecs_done].info.width < 0)
1262               /* If the width value is negative left justification is
1263                  selected and the value is taken as being positive.  */
1264               {
1265                 specs[nspecs_done].info.width *= -1;
1266                 left = specs[nspecs_done].info.left = 1;
1267               }
1268             width = specs[nspecs_done].info.width;
1269           }
1270
1271         if (specs[nspecs_done].prec_arg != -1)
1272           {
1273             /* Extract the precision from an argument.  */
1274             specs[nspecs_done].info.prec =
1275               args_value[specs[nspecs_done].prec_arg].pa_int;
1276
1277             if (specs[nspecs_done].info.prec < 0)
1278               /* If the precision is negative the precision is
1279                  omitted.  */
1280               specs[nspecs_done].info.prec = -1;
1281
1282             prec = specs[nspecs_done].info.prec;
1283           }
1284
1285         /* Process format specifiers.  */
1286         while (1)
1287           {
1288             JUMP (spec, step4_jumps);
1289
1290             process_arg ((&specs[nspecs_done]));
1291
1292           LABEL (form_unknown):
1293             {
1294               extern printf_function **__printf_function_table;
1295               int function_done;
1296               printf_function *function;
1297               unsigned int i;
1298               const void **ptr;
1299
1300               function =
1301                 (__printf_function_table == NULL ? NULL :
1302                  __printf_function_table[specs[nspecs_done].info.spec]);
1303
1304               if (function == NULL)
1305                 function = &printf_unknown;
1306
1307               ptr = alloca (specs[nspecs_done].ndata_args
1308                             * sizeof (const void *));
1309
1310               /* Fill in an array of pointers to the argument values.  */
1311               for (i = 0; i < specs[nspecs_done].ndata_args; ++i)
1312                 ptr[i] = &args_value[specs[nspecs_done].data_arg + i];
1313
1314               /* Call the function.  */
1315               function_done = (*function) (s, &specs[nspecs_done].info, ptr);
1316
1317               /* If an error occured we don't have information about #
1318                  of chars.  */
1319               if (function_done < 0)
1320                 {
1321                   done = -1;
1322                   goto all_done;
1323                 }
1324
1325               done += function_done;
1326             }
1327             break;
1328           }
1329
1330         /* Write the following constant string.  */
1331         outstring (specs[nspecs_done].end_of_fmt,
1332                    specs[nspecs_done].next_fmt
1333                    - specs[nspecs_done].end_of_fmt);
1334       }
1335   }
1336
1337 all_done:
1338   /* Unlock the stream.  */
1339   __libc_cleanup_region_end (1);
1340
1341   return done;
1342 }
1343
1344 #ifdef USE_IN_LIBIO
1345 # undef vfprintf
1346 # ifdef strong_alias
1347 /* This is for glibc.  */
1348 strong_alias (_IO_vfprintf, vfprintf);
1349 # else
1350 #  if defined __ELF__ || defined __GNU_LIBRARY__
1351 #   include <gnu-stabs.h>
1352 #   ifdef weak_alias
1353 weak_alias (_IO_vfprintf, vfprintf);
1354 #   endif
1355 #  endif
1356 # endif
1357 #endif
1358 \f
1359 /* Handle an unknown format specifier.  This prints out a canonicalized
1360    representation of the format spec itself.  */
1361 static int
1362 printf_unknown (FILE *s, const struct printf_info *info,
1363                 const void *const *args)
1364
1365 {
1366   int done = 0;
1367   char work_buffer[BUFSIZ];
1368   register char *w;
1369
1370   outchar ('%');
1371
1372   if (info->alt)
1373     outchar ('#');
1374   if (info->group)
1375     outchar ('\'');
1376   if (info->showsign)
1377     outchar ('+');
1378   else if (info->space)
1379     outchar (' ');
1380   if (info->left)
1381     outchar ('-');
1382   if (info->pad == '0')
1383     outchar ('0');
1384
1385   if (info->width != 0)
1386     {
1387       w = _itoa_word (info->width, workend + 1, 10, 0);
1388       while (++w <= workend)
1389         outchar (*w);
1390     }
1391
1392   if (info->prec != -1)
1393     {
1394       outchar ('.');
1395       w = _itoa_word (info->prec, workend + 1, 10, 0);
1396       while (++w <= workend)
1397         outchar (*w);
1398     }
1399
1400   if (info->spec != '\0')
1401     outchar (info->spec);
1402
1403   return done;
1404 }
1405 \f
1406 /* Group the digits according to the grouping rules of the current locale.
1407    The interpretation of GROUPING is as in `struct lconv' from <locale.h>.  */
1408 static char *
1409 group_number (CHAR_T *w, CHAR_T *rear_ptr, const CHAR_T *grouping,
1410               wchar_t thousands_sep)
1411 {
1412   int len;
1413   char *src, *s;
1414
1415   /* We treat all negative values like CHAR_MAX.  */
1416
1417   if (*grouping == CHAR_MAX || *grouping < 0)
1418     /* No grouping should be done.  */
1419     return w;
1420
1421   len = *grouping;
1422
1423   /* Copy existing string so that nothing gets overwritten.  */
1424   src = (char *) alloca (rear_ptr - w);
1425   memcpy (src, w + 1, rear_ptr - w);
1426   s = &src[rear_ptr - w - 1];
1427   w = rear_ptr;
1428
1429   /* Process all characters in the string.  */
1430   while (s >= src)
1431     {
1432       *w-- = *s--;
1433
1434       if (--len == 0 && s >= src)
1435         {
1436           /* A new group begins.  */
1437           *w-- = thousands_sep;
1438
1439           len = *grouping++;
1440           if (*grouping == '\0')
1441             /* The previous grouping repeats ad infinitum.  */
1442             --grouping;
1443           else if (*grouping == CHAR_MAX || *grouping < 0)
1444             {
1445               /* No further grouping to be done.
1446                  Copy the rest of the number.  */
1447               do
1448                 *w-- = *s--;
1449               while (s >= src);
1450               break;
1451             }
1452         }
1453     }
1454   return w;
1455 }
1456 \f
1457 #ifdef USE_IN_LIBIO
1458 /* Helper "class" for `fprintf to unbuffered': creates a temporary buffer.  */
1459 struct helper_file
1460   {
1461     struct _IO_FILE_plus _f;
1462     _IO_FILE *_put_stream;
1463 #ifdef _IO_MTSAFE_IO
1464     _IO_lock_t lock;
1465 #endif
1466   };
1467
1468 static int
1469 _IO_helper_overflow (_IO_FILE *s, int c)
1470 {
1471   _IO_FILE *target = ((struct helper_file*) s)->_put_stream;
1472   int used = s->_IO_write_ptr - s->_IO_write_base;
1473   if (used)
1474     {
1475       _IO_size_t written = _IO_sputn (target, s->_IO_write_base, used);
1476       s->_IO_write_ptr -= written;
1477     }
1478   return PUTC (c, s);
1479 }
1480
1481 static const struct _IO_jump_t _IO_helper_jumps =
1482 {
1483   JUMP_INIT_DUMMY,
1484   JUMP_INIT (finish, _IO_default_finish),
1485   JUMP_INIT (overflow, _IO_helper_overflow),
1486   JUMP_INIT (underflow, _IO_default_underflow),
1487   JUMP_INIT (uflow, _IO_default_uflow),
1488   JUMP_INIT (pbackfail, _IO_default_pbackfail),
1489   JUMP_INIT (xsputn, _IO_default_xsputn),
1490   JUMP_INIT (xsgetn, _IO_default_xsgetn),
1491   JUMP_INIT (seekoff, _IO_default_seekoff),
1492   JUMP_INIT (seekpos, _IO_default_seekpos),
1493   JUMP_INIT (setbuf, _IO_default_setbuf),
1494   JUMP_INIT (sync, _IO_default_sync),
1495   JUMP_INIT (doallocate, _IO_default_doallocate),
1496   JUMP_INIT (read, _IO_default_read),
1497   JUMP_INIT (write, _IO_default_write),
1498   JUMP_INIT (seek, _IO_default_seek),
1499   JUMP_INIT (close, _IO_default_close),
1500   JUMP_INIT (stat, _IO_default_stat)
1501 };
1502
1503 static int
1504 buffered_vfprintf (register _IO_FILE *s, const CHAR_T *format,
1505                    _IO_va_list args)
1506 {
1507   char buf[_IO_BUFSIZ];
1508   struct helper_file helper;
1509   register _IO_FILE *hp = (_IO_FILE *) &helper;
1510   int result, to_flush;
1511
1512   /* Initialize helper.  */
1513   helper._put_stream = s;
1514   hp->_IO_write_base = buf;
1515   hp->_IO_write_ptr = buf;
1516   hp->_IO_write_end = buf + sizeof buf;
1517   hp->_IO_file_flags = _IO_MAGIC|_IO_NO_READS;
1518 #ifdef _IO_MTSAFE_IO
1519   hp->_lock = &helper.lock;
1520   __libc_lock_init (*hp->_lock);
1521 #endif
1522   _IO_JUMPS (hp) = (struct _IO_jump_t *) &_IO_helper_jumps;
1523
1524   /* Now print to helper instead.  */
1525   result = _IO_vfprintf (hp, format, args);
1526
1527   /* Now flush anything from the helper to the S. */
1528   if ((to_flush = hp->_IO_write_ptr - hp->_IO_write_base) > 0)
1529     {
1530       if ((int) _IO_sputn (s, hp->_IO_write_base, to_flush) != to_flush)
1531         return -1;
1532     }
1533
1534   return result;
1535 }
1536
1537 #else /* !USE_IN_LIBIO */
1538
1539 static int
1540 buffered_vfprintf (register FILE *s, const CHAR_T *format, va_list args)
1541 {
1542   char buf[BUFSIZ];
1543   int result;
1544
1545   s->__bufp = s->__buffer = buf;
1546   s->__bufsize = sizeof buf;
1547   s->__put_limit = s->__buffer + s->__bufsize;
1548   s->__get_limit = s->__buffer;
1549
1550   /* Now use buffer to print.  */
1551   result = vfprintf (s, format, args);
1552
1553   if (fflush (s) == EOF)
1554     result = -1;
1555   s->__buffer = s->__bufp = s->__get_limit = s->__put_limit = NULL;
1556   s->__bufsize = 0;
1557
1558   return result;
1559 }
1560 \f
1561 /* Pads string with given number of a specified character.
1562    This code is taken from iopadn.c of the GNU I/O library.  */
1563 #define PADSIZE 16
1564 static const CHAR_T blanks[PADSIZE] =
1565 { L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '),
1566   L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' ') };
1567 static const CHAR_T zeroes[PADSIZE] =
1568 { L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'),
1569   L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0') };
1570
1571 ssize_t
1572 #ifndef COMPILE_WPRINTF
1573 __printf_pad (FILE *s, char pad, size_t count)
1574 #else
1575 __wprintf_pad (FILE *s, wchar_t pad, size_t count)
1576 #endif
1577 {
1578   const CHAR_T *padptr;
1579   register size_t i;
1580
1581   padptr = pad == L_(' ') ? blanks : zeroes;
1582
1583   for (i = count; i >= PADSIZE; i -= PADSIZE)
1584     if (PUT (s, padptr, PADSIZE) != PADSIZE)
1585       return -1;
1586   if (i > 0)
1587     if (PUT (s, padptr, i) != i)
1588       return -1;
1589
1590   return count;
1591 }
1592 #undef PADSIZE
1593 #endif /* USE_IN_LIBIO */