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