e69a2d5e36b0d75a306effc080c78c9dea8f649c
[musl] / src / stdio / vfwprintf.c
1 #include "stdio_impl.h"
2 #include <errno.h>
3 #include <ctype.h>
4 #include <limits.h>
5 #include <string.h>
6 #include <stdarg.h>
7 #include <stddef.h>
8 #include <stdlib.h>
9 #include <wchar.h>
10 #include <inttypes.h>
11
12 /* Convenient bit representation for modifier flags, which all fall
13  * within 31 codepoints of the space character. */
14
15 #define ALT_FORM   (1U<<'#'-' ')
16 #define ZERO_PAD   (1U<<'0'-' ')
17 #define LEFT_ADJ   (1U<<'-'-' ')
18 #define PAD_POS    (1U<<' '-' ')
19 #define MARK_POS   (1U<<'+'-' ')
20 #define GROUPED    (1U<<'\''-' ')
21
22 #define FLAGMASK (ALT_FORM|ZERO_PAD|LEFT_ADJ|PAD_POS|MARK_POS|GROUPED)
23
24 /* State machine to accept length modifiers + conversion specifiers.
25  * Result is 0 on failure, or an argument type to pop on success. */
26
27 enum {
28         BARE, LPRE, LLPRE, HPRE, HHPRE, BIGLPRE,
29         ZTPRE, JPRE,
30         STOP,
31         PTR, INT, UINT, ULLONG,
32         LONG, ULONG,
33         SHORT, USHORT, CHAR, UCHAR,
34         LLONG, SIZET, IMAX, UMAX, PDIFF, UIPTR,
35         DBL, LDBL,
36         NOARG,
37         MAXSTATE
38 };
39
40 #define S(x) [(x)-'A']
41
42 static const unsigned char states[]['z'-'A'+1] = {
43         { /* 0: bare types */
44                 S('d') = INT, S('i') = INT,
45                 S('o') = UINT, S('u') = UINT, S('x') = UINT, S('X') = UINT,
46                 S('e') = DBL, S('f') = DBL, S('g') = DBL, S('a') = DBL,
47                 S('E') = DBL, S('F') = DBL, S('G') = DBL, S('A') = DBL,
48                 S('c') = CHAR, S('C') = INT,
49                 S('s') = PTR, S('S') = PTR, S('p') = UIPTR, S('n') = PTR,
50                 S('m') = NOARG,
51                 S('l') = LPRE, S('h') = HPRE, S('L') = BIGLPRE,
52                 S('z') = ZTPRE, S('j') = JPRE, S('t') = ZTPRE,
53         }, { /* 1: l-prefixed */
54                 S('d') = LONG, S('i') = LONG,
55                 S('o') = ULONG, S('u') = ULONG, S('x') = ULONG, S('X') = ULONG,
56                 S('e') = DBL, S('f') = DBL, S('g') = DBL, S('a') = DBL,
57                 S('E') = DBL, S('F') = DBL, S('G') = DBL, S('A') = DBL,
58                 S('c') = INT, S('s') = PTR, S('n') = PTR,
59                 S('l') = LLPRE,
60         }, { /* 2: ll-prefixed */
61                 S('d') = LLONG, S('i') = LLONG,
62                 S('o') = ULLONG, S('u') = ULLONG,
63                 S('x') = ULLONG, S('X') = ULLONG,
64                 S('n') = PTR,
65         }, { /* 3: h-prefixed */
66                 S('d') = SHORT, S('i') = SHORT,
67                 S('o') = USHORT, S('u') = USHORT,
68                 S('x') = USHORT, S('X') = USHORT,
69                 S('n') = PTR,
70                 S('h') = HHPRE,
71         }, { /* 4: hh-prefixed */
72                 S('d') = CHAR, S('i') = CHAR,
73                 S('o') = UCHAR, S('u') = UCHAR,
74                 S('x') = UCHAR, S('X') = UCHAR,
75                 S('n') = PTR,
76         }, { /* 5: L-prefixed */
77                 S('e') = LDBL, S('f') = LDBL, S('g') = LDBL, S('a') = LDBL,
78                 S('E') = LDBL, S('F') = LDBL, S('G') = LDBL, S('A') = LDBL,
79                 S('n') = PTR,
80         }, { /* 6: z- or t-prefixed (assumed to be same size) */
81                 S('d') = PDIFF, S('i') = PDIFF,
82                 S('o') = SIZET, S('u') = SIZET,
83                 S('x') = SIZET, S('X') = SIZET,
84                 S('n') = PTR,
85         }, { /* 7: j-prefixed */
86                 S('d') = IMAX, S('i') = IMAX,
87                 S('o') = UMAX, S('u') = UMAX,
88                 S('x') = UMAX, S('X') = UMAX,
89                 S('n') = PTR,
90         }
91 };
92
93 #define OOB(x) ((unsigned)(x)-'A' > 'z'-'A')
94
95 union arg
96 {
97         uintmax_t i;
98         long double f;
99         void *p;
100 };
101
102 static void pop_arg(union arg *arg, int type, va_list *ap)
103 {
104         switch (type) {
105                case PTR:        arg->p = va_arg(*ap, void *);
106         break; case INT:        arg->i = va_arg(*ap, int);
107         break; case UINT:       arg->i = va_arg(*ap, unsigned int);
108         break; case LONG:       arg->i = va_arg(*ap, long);
109         break; case ULONG:      arg->i = va_arg(*ap, unsigned long);
110         break; case ULLONG:     arg->i = va_arg(*ap, unsigned long long);
111         break; case SHORT:      arg->i = (short)va_arg(*ap, int);
112         break; case USHORT:     arg->i = (unsigned short)va_arg(*ap, int);
113         break; case CHAR:       arg->i = (signed char)va_arg(*ap, int);
114         break; case UCHAR:      arg->i = (unsigned char)va_arg(*ap, int);
115         break; case LLONG:      arg->i = va_arg(*ap, long long);
116         break; case SIZET:      arg->i = va_arg(*ap, size_t);
117         break; case IMAX:       arg->i = va_arg(*ap, intmax_t);
118         break; case UMAX:       arg->i = va_arg(*ap, uintmax_t);
119         break; case PDIFF:      arg->i = va_arg(*ap, ptrdiff_t);
120         break; case UIPTR:      arg->i = (uintptr_t)va_arg(*ap, void *);
121         break; case DBL:        arg->f = va_arg(*ap, double);
122         break; case LDBL:       arg->f = va_arg(*ap, long double);
123         }
124 }
125
126 static void out(FILE *f, const wchar_t *s, size_t l)
127 {
128         while (l-- && !(f->flags & F_ERR)) fputwc(*s++, f);
129 }
130
131 static int getint(wchar_t **s) {
132         int i;
133         for (i=0; iswdigit(**s); (*s)++) {
134                 if (i > INT_MAX/10U || **s-'0' > INT_MAX-10*i) i = -1;
135                 else i = 10*i + (**s-'0');
136         }
137         return i;
138 }
139
140 static const char sizeprefix['y'-'a'] = {
141 ['a'-'a']='L', ['e'-'a']='L', ['f'-'a']='L', ['g'-'a']='L',
142 ['d'-'a']='j', ['i'-'a']='j', ['o'-'a']='j', ['u'-'a']='j', ['x'-'a']='j',
143 ['p'-'a']='j'
144 };
145
146 static int wprintf_core(FILE *f, const wchar_t *fmt, va_list *ap, union arg *nl_arg, int *nl_type)
147 {
148         wchar_t *a, *z, *s=(wchar_t *)fmt;
149         unsigned l10n=0, fl;
150         int w, p, xp;
151         union arg arg;
152         int argpos;
153         unsigned st, ps;
154         int cnt=0, l=0;
155         int i;
156         int t;
157         char *bs;
158         char charfmt[16];
159         wchar_t wc;
160
161         for (;;) {
162                 /* This error is only specified for snprintf, but since it's
163                  * unspecified for other forms, do the same. Stop immediately
164                  * on overflow; otherwise %n could produce wrong results. */
165                 if (l > INT_MAX - cnt) goto overflow;
166
167                 /* Update output count, end loop when fmt is exhausted */
168                 cnt += l;
169                 if (!*s) break;
170
171                 /* Handle literal text and %% format specifiers */
172                 for (a=s; *s && *s!='%'; s++);
173                 for (z=s; s[0]=='%' && s[1]=='%'; z++, s+=2);
174                 if (z-a > INT_MAX-cnt) goto overflow;
175                 l = z-a;
176                 if (f) out(f, a, l);
177                 if (l) continue;
178
179                 if (iswdigit(s[1]) && s[2]=='$') {
180                         l10n=1;
181                         argpos = s[1]-'0';
182                         s+=3;
183                 } else {
184                         argpos = -1;
185                         s++;
186                 }
187
188                 /* Read modifier flags */
189                 for (fl=0; (unsigned)*s-' '<32 && (FLAGMASK&(1U<<*s-' ')); s++)
190                         fl |= 1U<<*s-' ';
191
192                 /* Read field width */
193                 if (*s=='*') {
194                         if (iswdigit(s[1]) && s[2]=='$') {
195                                 l10n=1;
196                                 nl_type[s[1]-'0'] = INT;
197                                 w = nl_arg[s[1]-'0'].i;
198                                 s+=3;
199                         } else if (!l10n) {
200                                 w = f ? va_arg(*ap, int) : 0;
201                                 s++;
202                         } else goto inval;
203                         if (w<0) fl|=LEFT_ADJ, w=-w;
204                 } else if ((w=getint(&s))<0) goto overflow;
205
206                 /* Read precision */
207                 if (*s=='.' && s[1]=='*') {
208                         if (isdigit(s[2]) && s[3]=='$') {
209                                 nl_type[s[2]-'0'] = INT;
210                                 p = nl_arg[s[2]-'0'].i;
211                                 s+=4;
212                         } else if (!l10n) {
213                                 p = f ? va_arg(*ap, int) : 0;
214                                 s+=2;
215                         } else goto inval;
216                         xp = (p>=0);
217                 } else if (*s=='.') {
218                         s++;
219                         p = getint(&s);
220                         xp = 1;
221                 } else {
222                         p = -1;
223                         xp = 0;
224                 }
225
226                 /* Format specifier state machine */
227                 st=0;
228                 do {
229                         if (OOB(*s)) goto inval;
230                         ps=st;
231                         st=states[st]S(*s++);
232                 } while (st-1<STOP);
233                 if (!st) goto inval;
234
235                 /* Check validity of argument type (nl/normal) */
236                 if (st==NOARG) {
237                         if (argpos>=0) goto inval;
238                 } else {
239                         if (argpos>=0) nl_type[argpos]=st, arg=nl_arg[argpos];
240                         else if (f) pop_arg(&arg, st, ap);
241                         else return 0;
242                 }
243
244                 if (!f) continue;
245                 t = s[-1];
246                 if (ps && (t&15)==3) t&=~32;
247
248                 switch (t) {
249                 case 'n':
250                         switch(ps) {
251                         case BARE: *(int *)arg.p = cnt; break;
252                         case LPRE: *(long *)arg.p = cnt; break;
253                         case LLPRE: *(long long *)arg.p = cnt; break;
254                         case HPRE: *(unsigned short *)arg.p = cnt; break;
255                         case HHPRE: *(unsigned char *)arg.p = cnt; break;
256                         case ZTPRE: *(size_t *)arg.p = cnt; break;
257                         case JPRE: *(uintmax_t *)arg.p = cnt; break;
258                         }
259                         continue;
260                 case 'c':
261                 case 'C':
262                         if (w<1) w=1;
263                         if (w>1 && !(fl&LEFT_ADJ)) fprintf(f, "%*s", w-1, "");
264                         fputwc(t=='C' ? arg.i : btowc(arg.i), f);
265                         if (w>1 && (fl&LEFT_ADJ)) fprintf(f, "%*s", w-1, "");
266                         l = w;
267                         continue;
268                 case 'S':
269                         a = arg.p;
270                         z = a + wcsnlen(a, p<0 ? INT_MAX : p);
271                         if (p<0 && *z) goto overflow;
272                         p = z-a;
273                         if (w<p) w=p;
274                         if (!(fl&LEFT_ADJ)) fprintf(f, "%*s", w-p, "");
275                         out(f, a, p);
276                         if ((fl&LEFT_ADJ)) fprintf(f, "%*s", w-p, "");
277                         l=w;
278                         continue;
279                 case 'm':
280                         arg.p = strerror(errno);
281                 case 's':
282                         if (!arg.p) arg.p = "(null)";
283                         bs = arg.p;
284                         for (i=l=0; l<(p<0?INT_MAX:p) && (i=mbtowc(&wc, bs, MB_LEN_MAX))>0; bs+=i, l++);
285                         if (i<0) return -1;
286                         if (p<0 && *bs) goto overflow;
287                         p=l;
288                         if (w<p) w=p;
289                         if (!(fl&LEFT_ADJ)) fprintf(f, "%*s", w-p, "");
290                         bs = arg.p;
291                         while (l--) {
292                                 i=mbtowc(&wc, bs, MB_LEN_MAX);
293                                 bs+=i;
294                                 fputwc(wc, f);
295                         }
296                         if ((fl&LEFT_ADJ)) fprintf(f, "%*s", w-p, "");
297                         l=w;
298                         continue;
299                 }
300
301                 if (xp && p<0) goto overflow;
302                 snprintf(charfmt, sizeof charfmt, "%%%s%s%s%s%s*.*%c%c",
303                         "#"+!(fl & ALT_FORM),
304                         "+"+!(fl & MARK_POS),
305                         "-"+!(fl & LEFT_ADJ),
306                         " "+!(fl & PAD_POS),
307                         "0"+!(fl & ZERO_PAD),
308                         sizeprefix[(t|32)-'a'], t);
309
310                 switch (t|32) {
311                 case 'a': case 'e': case 'f': case 'g':
312                         l = fprintf(f, charfmt, w, p, arg.f);
313                         break;
314                 case 'd': case 'i': case 'o': case 'u': case 'x': case 'p':
315                         l = fprintf(f, charfmt, w, p, arg.i);
316                         break;
317                 }
318         }
319
320         if (f) return cnt;
321         if (!l10n) return 0;
322
323         for (i=1; i<=NL_ARGMAX && nl_type[i]; i++)
324                 pop_arg(nl_arg+i, nl_type[i], ap);
325         for (; i<=NL_ARGMAX && !nl_type[i]; i++);
326         if (i<=NL_ARGMAX) return -1;
327         return 1;
328
329 inval:
330         errno = EINVAL;
331         return -1;
332 overflow:
333         errno = EOVERFLOW;
334         return -1;
335 }
336
337 int vfwprintf(FILE *restrict f, const wchar_t *restrict fmt, va_list ap)
338 {
339         va_list ap2;
340         int nl_type[NL_ARGMAX] = {0};
341         union arg nl_arg[NL_ARGMAX];
342         int olderr;
343         int ret;
344
345         /* the copy allows passing va_list* even if va_list is an array */
346         va_copy(ap2, ap);
347         if (wprintf_core(0, fmt, &ap2, nl_arg, nl_type) < 0) {
348                 va_end(ap2);
349                 return -1;
350         }
351
352         FLOCK(f);
353         fwide(f, 1);
354         olderr = f->flags & F_ERR;
355         f->flags &= ~F_ERR;
356         ret = wprintf_core(f, fmt, &ap2, nl_arg, nl_type);
357         if (f->flags & F_ERR) ret = -1;
358         f->flags |= olderr;
359         FUNLOCK(f);
360         va_end(ap2);
361         return ret;
362 }