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