1 /*	$OpenBSD: vfwprintf.c,v 1.12 2014/12/21 00:23:30 daniel Exp $ */
2 /*-
3  * Copyright (c) 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Chris Torek.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Actual wprintf innards.
36  *
37  * This code is large and complicated...
38  */
39 
40 #include <sys/types.h>
41 #include <sys/mman.h>
42 
43 #include <errno.h>
44 #include <langinfo.h>
45 #include <limits.h>
46 #include <stdarg.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdint.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 
54 #include "local.h"
55 #include "fvwrite.h"
56 
57 union arg {
58 	int			intarg;
59 	unsigned int		uintarg;
60 	long			longarg;
61 	unsigned long		ulongarg;
62 	long long		longlongarg;
63 	unsigned long long	ulonglongarg;
64 	ptrdiff_t		ptrdiffarg;
65 	size_t			sizearg;
66 	ssize_t			ssizearg;
67 	intmax_t		intmaxarg;
68 	uintmax_t		uintmaxarg;
69 	void			*pvoidarg;
70 	char			*pchararg;
71 	signed char		*pschararg;
72 	short			*pshortarg;
73 	int			*pintarg;
74 	long			*plongarg;
75 	long long		*plonglongarg;
76 	ptrdiff_t		*pptrdiffarg;
77 	ssize_t			*pssizearg;
78 	intmax_t		*pintmaxarg;
79 #ifdef FLOATING_POINT
80 	double			doublearg;
81 	long double		longdoublearg;
82 #endif
83 	wint_t			wintarg;
84 	wchar_t			*pwchararg;
85 };
86 
87 static int __find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
88     size_t *argtablesiz);
89 static int __grow_type_table(unsigned char **typetable, int *tablesize);
90 
91 /*
92  * Helper function for `fprintf to unbuffered unix file': creates a
93  * temporary buffer.  We only work on write-only files; this avoids
94  * worries about ungetc buffers and so forth.
95  */
96 static int
__sbprintf(FILE * fp,const wchar_t * fmt,va_list ap)97 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
98 {
99 	int ret;
100 	FILE fake;
101 	struct __sfileext fakeext;
102 	unsigned char buf[BUFSIZ];
103 
104 	_FILEEXT_SETUP(&fake, &fakeext);
105 	/* copy the important variables */
106 	fake._flags = fp->_flags & ~__SNBF;
107 	fake._file = fp->_file;
108 	fake._cookie = fp->_cookie;
109 	fake._write = fp->_write;
110 
111 	/* set up the buffer */
112 	fake._bf._base = fake._p = buf;
113 	fake._bf._size = fake._w = sizeof(buf);
114 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
115 
116 	/* do the work, then copy any error status */
117 	ret = __vfwprintf(&fake, fmt, ap);
118 	if (ret >= 0 && __sflush(&fake))
119 		ret = EOF;
120 	if (fake._flags & __SERR)
121 		fp->_flags |= __SERR;
122 	return (ret);
123 }
124 
125 /*
126  * Like __fputwc_unlock, but handles fake string (__SSTR) files properly.
127  * File must already be locked.
128  */
129 static wint_t
__xfputwc(wchar_t wc,FILE * fp)130 __xfputwc(wchar_t wc, FILE *fp)
131 {
132 	mbstate_t mbs;
133 	char buf[MB_LEN_MAX];
134 	struct __suio uio;
135 	struct __siov iov;
136 	size_t len;
137 
138 	if ((fp->_flags & __SSTR) == 0)
139 		return (__fputwc_unlock(wc, fp));
140 
141 	bzero(&mbs, sizeof(mbs));
142 	len = wcrtomb(buf, wc, &mbs);
143 	if (len == (size_t)-1) {
144 		fp->_flags |= __SERR;
145 		errno = EILSEQ;
146 		return (WEOF);
147 	}
148 	uio.uio_iov = &iov;
149 	uio.uio_resid = len;
150 	uio.uio_iovcnt = 1;
151 	iov.iov_base = buf;
152 	iov.iov_len = len;
153 	return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
154 }
155 
156 /*
157  * Convert a multibyte character string argument for the %s format to a wide
158  * string representation. ``prec'' specifies the maximum number of bytes
159  * to output. If ``prec'' is greater than or equal to zero, we can't assume
160  * that the multibyte character string ends in a null character.
161  *
162  * Returns NULL on failure.
163  * To find out what happened check errno for ENOMEM, EILSEQ and EINVAL.
164  */
165 static wchar_t *
__mbsconv(char * mbsarg,int prec)166 __mbsconv(char *mbsarg, int prec)
167 {
168 	mbstate_t mbs;
169 	wchar_t *convbuf, *wcp;
170 	const char *p;
171 	size_t insize, nchars, nconv;
172 
173 	if (mbsarg == NULL)
174 		return (NULL);
175 
176 	/*
177 	 * Supplied argument is a multibyte string; convert it to wide
178 	 * characters first.
179 	 */
180 	if (prec >= 0) {
181 		/*
182 		 * String is not guaranteed to be NUL-terminated. Find the
183 		 * number of characters to print.
184 		 */
185 		p = mbsarg;
186 		insize = nchars = nconv = 0;
187 		bzero(&mbs, sizeof(mbs));
188 		while (nchars != (size_t)prec) {
189 			nconv = mbrlen(p, MB_CUR_MAX, &mbs);
190 			if (nconv == (size_t)0 || nconv == (size_t)-1 ||
191 			    nconv == (size_t)-2)
192 				break;
193 			p += nconv;
194 			nchars++;
195 			insize += nconv;
196 		}
197 		if (nconv == (size_t)-1 || nconv == (size_t)-2)
198 			return (NULL);
199 	} else
200 		insize = strlen(mbsarg);
201 
202 	/*
203 	 * Allocate buffer for the result and perform the conversion,
204 	 * converting at most `size' bytes of the input multibyte string to
205 	 * wide characters for printing.
206 	 */
207 	convbuf = calloc(insize + 1, sizeof(*convbuf));
208 	if (convbuf == NULL)
209 		return (NULL);
210 	wcp = convbuf;
211 	p = mbsarg;
212 	bzero(&mbs, sizeof(mbs));
213 	nconv = 0;
214 	while (insize != 0) {
215 		nconv = mbrtowc(wcp, p, insize, &mbs);
216 		if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
217 			break;
218 		wcp++;
219 		p += nconv;
220 		insize -= nconv;
221 	}
222 	if (nconv == (size_t)-1 || nconv == (size_t)-2) {
223 		free(convbuf);
224 		return (NULL);
225 	}
226 	*wcp = '\0';
227 
228 	return (convbuf);
229 }
230 
231 #ifdef FLOATING_POINT
232 #include <float.h>
233 #include <locale.h>
234 #include <math.h>
235 #include "floatio.h"
236 #include "gdtoa.h"
237 
238 #define	DEFPREC		6
239 
240 static int exponent(wchar_t *, int, int);
241 #endif /* FLOATING_POINT */
242 
243 /*
244  * The size of the buffer we use as scratch space for integer
245  * conversions, among other things.  Technically, we would need the
246  * most space for base 10 conversions with thousands' grouping
247  * characters between each pair of digits.  100 bytes is a
248  * conservative overestimate even for a 128-bit uintmax_t.
249  */
250 #define BUF	100
251 
252 #define STATIC_ARG_TBL_SIZE 8	/* Size of static argument table. */
253 
254 
255 /*
256  * Macros for converting digits to letters and vice versa
257  */
258 #define	to_digit(c)	((c) - '0')
259 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
260 #define	to_char(n)	((wchar_t)((n) + '0'))
261 
262 /*
263  * Flags used during conversion.
264  */
265 #define	ALT		0x0001		/* alternate form */
266 #define	LADJUST		0x0004		/* left adjustment */
267 #define	LONGDBL		0x0008		/* long double */
268 #define	LONGINT		0x0010		/* long integer */
269 #define	LLONGINT	0x0020		/* long long integer */
270 #define	SHORTINT	0x0040		/* short integer */
271 #define	ZEROPAD		0x0080		/* zero (as opposed to blank) pad */
272 #define FPT		0x0100		/* Floating point number */
273 #define PTRINT		0x0200		/* (unsigned) ptrdiff_t */
274 #define SIZEINT		0x0400		/* (signed) size_t */
275 #define CHARINT		0x0800		/* 8 bit integer */
276 #define MAXINT		0x1000		/* largest integer size (intmax_t) */
277 
278 int
__vfwprintf(FILE * __restrict fp,const wchar_t * __restrict fmt0,__va_list ap)279 __vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, __va_list ap)
280 {
281 	wchar_t *fmt;		/* format string */
282 	wchar_t ch;		/* character from fmt */
283 	int n, n2, n3;		/* handy integers (short term usage) */
284 	wchar_t *cp;		/* handy char pointer (short term usage) */
285 	int flags;		/* flags as above */
286 	int ret;		/* return value accumulator */
287 	int width;		/* width from format (%8d), or 0 */
288 	int prec;		/* precision from format; <0 for N/A */
289 	wchar_t sign;		/* sign prefix (' ', '+', '-', or \0) */
290 #ifdef FLOATING_POINT
291 	/*
292 	 * We can decompose the printed representation of floating
293 	 * point numbers into several parts, some of which may be empty:
294 	 *
295 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
296 	 *    A       B     ---C---      D       E   F
297 	 *
298 	 * A:	'sign' holds this value if present; '\0' otherwise
299 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
300 	 * C:	cp points to the string MMMNNN.  Leading and trailing
301 	 *	zeros are not in the string and must be added.
302 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
303 	 * F:	at least two digits for decimal, at least one digit for hex
304 	 */
305 	char *decimal_point = NULL;
306 	int signflag;		/* true if float is negative */
307 	union {			/* floating point arguments %[aAeEfFgG] */
308 		double dbl;
309 		long double ldbl;
310 	} fparg;
311 	int expt;		/* integer value of exponent */
312 	char expchar;		/* exponent character: [eEpP\0] */
313 	char *dtoaend;		/* pointer to end of converted digits */
314 	int expsize;		/* character count for expstr */
315 	int lead;		/* sig figs before decimal or group sep */
316 	int ndig;		/* actual number of digits returned by dtoa */
317 	wchar_t expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
318 	char *dtoaresult = NULL;
319 #endif
320 
321 	uintmax_t _umax;	/* integer arguments %[diouxX] */
322 	enum { OCT, DEC, HEX } base;	/* base for %[diouxX] conversion */
323 	int dprec;		/* a copy of prec if %[diouxX], 0 otherwise */
324 	int realsz;		/* field size expanded by dprec */
325 	int size;		/* size of converted field or string */
326 	const char *xdigs;	/* digits for %[xX] conversion */
327 	wchar_t buf[BUF];	/* buffer with space for digits of uintmax_t */
328 	wchar_t ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
329 	union arg *argtable;	/* args, built due to positional arg */
330 	union arg statargtable[STATIC_ARG_TBL_SIZE];
331 	size_t argtablesiz;
332 	int nextarg;		/* 1-based argument index */
333 	va_list orgap;		/* original argument pointer */
334 	wchar_t *convbuf;	/* buffer for multibyte to wide conversion */
335 
336 	/*
337 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
338 	 * fields occur frequently, increase PADSIZE and make the initialisers
339 	 * below longer.
340 	 */
341 #define	PADSIZE	16		/* pad chunk size */
342 	static wchar_t blanks[PADSIZE] =
343 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
344 	static wchar_t zeroes[PADSIZE] =
345 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
346 
347 	static const char xdigs_lower[16] = "0123456789abcdef";
348 	static const char xdigs_upper[16] = "0123456789ABCDEF";
349 
350 	/*
351 	 * BEWARE, these `goto error' on error, PRINT uses 'n3',
352 	 * PAD uses `n' and 'n3', and PRINTANDPAD uses 'n', 'n2', and 'n3'.
353 	 */
354 #define	PRINT(ptr, len)	do {	\
355 	for (n3 = 0; n3 < (len); n3++) {	\
356 		if ((__xfputwc((ptr)[n3], fp)) == WEOF)	\
357 			goto error; \
358 	} \
359 } while (0)
360 #define	PAD(howmany, with) do { \
361 	if ((n = (howmany)) > 0) { \
362 		while (n > PADSIZE) { \
363 			PRINT(with, PADSIZE); \
364 			n -= PADSIZE; \
365 		} \
366 		PRINT(with, n); \
367 	} \
368 } while (0)
369 #define	PRINTANDPAD(p, ep, len, with) do {	\
370 	n2 = (ep) - (p);       			\
371 	if (n2 > (len))				\
372 		n2 = (len);			\
373 	if (n2 > 0)				\
374 		PRINT((p), n2);			\
375 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
376 } while(0)
377 
378 	/*
379 	 * To extend shorts properly, we need both signed and unsigned
380 	 * argument extraction methods.
381 	 */
382 #define	SARG() \
383 	((intmax_t)(flags&MAXINT ? GETARG(intmax_t) : \
384 	    flags&LLONGINT ? GETARG(long long) : \
385 	    flags&LONGINT ? GETARG(long) : \
386 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
387 	    flags&SIZEINT ? GETARG(ssize_t) : \
388 	    flags&SHORTINT ? (short)GETARG(int) : \
389 	    flags&CHARINT ? (signed char)GETARG(int) : \
390 	    GETARG(int)))
391 #define	UARG() \
392 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
393 	    flags&LLONGINT ? GETARG(unsigned long long) : \
394 	    flags&LONGINT ? GETARG(unsigned long) : \
395 	    flags&PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
396 	    flags&SIZEINT ? GETARG(size_t) : \
397 	    flags&SHORTINT ? (unsigned short)GETARG(int) : \
398 	    flags&CHARINT ? (unsigned char)GETARG(int) : \
399 	    GETARG(unsigned int)))
400 
401 	/*
402 	 * Append a digit to a value and check for overflow.
403 	 */
404 #define APPEND_DIGIT(val, dig) do { \
405 	if ((val) > INT_MAX / 10) \
406 		goto overflow; \
407 	(val) *= 10; \
408 	if ((val) > INT_MAX - to_digit((dig))) \
409 		goto overflow; \
410 	(val) += to_digit((dig)); \
411 } while (0)
412 
413 	 /*
414 	  * Get * arguments, including the form *nn$.  Preserve the nextarg
415 	  * that the argument can be gotten once the type is determined.
416 	  */
417 #define GETASTER(val) \
418 	n2 = 0; \
419 	cp = fmt; \
420 	while (is_digit(*cp)) { \
421 		APPEND_DIGIT(n2, *cp); \
422 		cp++; \
423 	} \
424 	if (*cp == '$') { \
425 		int hold = nextarg; \
426 		if (argtable == NULL) { \
427 			argtable = statargtable; \
428 			__find_arguments(fmt0, orgap, &argtable, &argtablesiz); \
429 		} \
430 		nextarg = n2; \
431 		val = GETARG(int); \
432 		nextarg = hold; \
433 		fmt = ++cp; \
434 	} else { \
435 		val = GETARG(int); \
436 	}
437 
438 /*
439 * Get the argument indexed by nextarg.   If the argument table is
440 * built, use it to get the argument.  If its not, get the next
441 * argument (and arguments must be gotten sequentially).
442 */
443 #define GETARG(type) \
444 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
445 		(nextarg++, va_arg(ap, type)))
446 
447 	_SET_ORIENTATION(fp, 1);
448 	/* sorry, fwprintf(read_only_file, "") returns EOF, not 0 */
449 	if (cantwrite(fp)) {
450 		errno = EBADF;
451 		return (EOF);
452 	}
453 
454 	/* optimise fwprintf(stderr) (and other unbuffered Unix files) */
455 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
456 	    fp->_file >= 0)
457 		return (__sbprintf(fp, fmt0, ap));
458 
459 	fmt = (wchar_t *)fmt0;
460 	argtable = NULL;
461 	nextarg = 1;
462 	va_copy(orgap, ap);
463 	ret = 0;
464 	convbuf = NULL;
465 
466 	/*
467 	 * Scan the format for conversions (`%' character).
468 	 */
469 	for (;;) {
470 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
471 			continue;
472 		if (fmt != cp) {
473 			ptrdiff_t m = fmt - cp;
474 			if (m < 0 || m > INT_MAX - ret)
475 				goto overflow;
476 			PRINT(cp, m);
477 			ret += m;
478 		}
479 		if (ch == '\0')
480 			goto done;
481 		fmt++;		/* skip over '%' */
482 
483 		flags = 0;
484 		dprec = 0;
485 		width = 0;
486 		prec = -1;
487 		sign = '\0';
488 		ox[1] = '\0';
489 
490 rflag:		ch = *fmt++;
491 reswitch:	switch (ch) {
492 		case ' ':
493 			/*
494 			 * ``If the space and + flags both appear, the space
495 			 * flag will be ignored.''
496 			 *	-- ANSI X3J11
497 			 */
498 			if (!sign)
499 				sign = ' ';
500 			goto rflag;
501 		case '#':
502 			flags |= ALT;
503 			goto rflag;
504 		case '\'':
505 			/* grouping not implemented */
506 			goto rflag;
507 		case '*':
508 			/*
509 			 * ``A negative field width argument is taken as a
510 			 * - flag followed by a positive field width.''
511 			 *	-- ANSI X3J11
512 			 * They don't exclude field widths read from args.
513 			 */
514 			GETASTER(width);
515 			if (width >= 0)
516 				goto rflag;
517 			if (width == INT_MIN)
518 				goto overflow;
519 			width = -width;
520 			/* FALLTHROUGH */
521 		case '-':
522 			flags |= LADJUST;
523 			goto rflag;
524 		case '+':
525 			sign = '+';
526 			goto rflag;
527 		case '.':
528 			if ((ch = *fmt++) == '*') {
529 				GETASTER(n);
530 				prec = n < 0 ? -1 : n;
531 				goto rflag;
532 			}
533 			n = 0;
534 			while (is_digit(ch)) {
535 				APPEND_DIGIT(n, ch);
536 				ch = *fmt++;
537 			}
538 			if (ch == '$') {
539 				nextarg = n;
540 				if (argtable == NULL) {
541 					argtable = statargtable;
542 					__find_arguments(fmt0, orgap,
543 					    &argtable, &argtablesiz);
544 				}
545 				goto rflag;
546 			}
547 			prec = n;
548 			goto reswitch;
549 		case '0':
550 			/*
551 			 * ``Note that 0 is taken as a flag, not as the
552 			 * beginning of a field width.''
553 			 *	-- ANSI X3J11
554 			 */
555 			flags |= ZEROPAD;
556 			goto rflag;
557 		case '1': case '2': case '3': case '4':
558 		case '5': case '6': case '7': case '8': case '9':
559 			n = 0;
560 			do {
561 				APPEND_DIGIT(n, ch);
562 				ch = *fmt++;
563 			} while (is_digit(ch));
564 			if (ch == '$') {
565 				nextarg = n;
566 				if (argtable == NULL) {
567 					argtable = statargtable;
568 					__find_arguments(fmt0, orgap,
569 					    &argtable, &argtablesiz);
570 				}
571 				goto rflag;
572 			}
573 			width = n;
574 			goto reswitch;
575 #ifdef FLOATING_POINT
576 		case 'L':
577 			flags |= LONGDBL;
578 			goto rflag;
579 #endif
580 		case 'h':
581 			if (*fmt == 'h') {
582 				fmt++;
583 				flags |= CHARINT;
584 			} else {
585 				flags |= SHORTINT;
586 			}
587 			goto rflag;
588 		case 'j':
589 			flags |= MAXINT;
590 			goto rflag;
591 		case 'l':
592 			if (*fmt == 'l') {
593 				fmt++;
594 				flags |= LLONGINT;
595 			} else {
596 				flags |= LONGINT;
597 			}
598 			goto rflag;
599 		case 'q':
600 			flags |= LLONGINT;
601 			goto rflag;
602 		case 't':
603 			flags |= PTRINT;
604 			goto rflag;
605 		case 'z':
606 			flags |= SIZEINT;
607 			goto rflag;
608 		case 'C':
609 			flags |= LONGINT;
610 			/*FALLTHROUGH*/
611 		case 'c':
612 			if (flags & LONGINT)
613 				*(cp = buf) = (wchar_t)GETARG(wint_t);
614 			else
615 				*(cp = buf) = (wchar_t)btowc(GETARG(int));
616 			size = 1;
617 			sign = '\0';
618 			break;
619 		case 'D':
620 			flags |= LONGINT;
621 			/*FALLTHROUGH*/
622 		case 'd':
623 		case 'i':
624 			_umax = SARG();
625 			if ((intmax_t)_umax < 0) {
626 				_umax = -_umax;
627 				sign = '-';
628 			}
629 			base = DEC;
630 			goto number;
631 #ifdef FLOATING_POINT
632 		case 'a':
633 		case 'A':
634 			if (ch == 'a') {
635 				ox[1] = 'x';
636 				xdigs = xdigs_lower;
637 				expchar = 'p';
638 			} else {
639 				ox[1] = 'X';
640 				xdigs = xdigs_upper;
641 				expchar = 'P';
642 			}
643 			if (prec >= 0)
644 				prec++;
645 			if (dtoaresult)
646 				__freedtoa(dtoaresult);
647 			if (flags & LONGDBL) {
648 				fparg.ldbl = GETARG(long double);
649 				dtoaresult =
650 				    __hldtoa(fparg.ldbl, xdigs, prec,
651 				    &expt, &signflag, &dtoaend);
652 				if (dtoaresult == NULL) {
653 					errno = ENOMEM;
654 					goto error;
655 				}
656 			} else {
657 				fparg.dbl = GETARG(double);
658 				dtoaresult =
659 				    __hdtoa(fparg.dbl, xdigs, prec,
660 				    &expt, &signflag, &dtoaend);
661 				if (dtoaresult == NULL) {
662 					errno = ENOMEM;
663 					goto error;
664 				}
665 			}
666 			if (prec < 0)
667 				prec = dtoaend - dtoaresult;
668 			if (expt == INT_MAX)
669 				ox[1] = '\0';
670 			if (convbuf) {
671 				free(convbuf);
672 				convbuf = NULL;
673 			}
674 			cp = convbuf = __mbsconv(dtoaresult, -1);
675 			if (cp == NULL)
676 				goto error;
677 			ndig = dtoaend - dtoaresult;
678 			goto fp_common;
679 		case 'e':
680 		case 'E':
681 			expchar = ch;
682 			if (prec < 0)	/* account for digit before decpt */
683 				prec = DEFPREC + 1;
684 			else
685 				prec++;
686 			goto fp_begin;
687 		case 'f':
688 		case 'F':
689 			expchar = '\0';
690 			goto fp_begin;
691 		case 'g':
692 		case 'G':
693 			expchar = ch - ('g' - 'e');
694  			if (prec == 0)
695  				prec = 1;
696 fp_begin:
697 			if (prec < 0)
698 				prec = DEFPREC;
699 			if (dtoaresult)
700 				__freedtoa(dtoaresult);
701 			if (flags & LONGDBL) {
702 				fparg.ldbl = GETARG(long double);
703 				dtoaresult =
704 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
705 				    &expt, &signflag, &dtoaend);
706 				if (dtoaresult == NULL) {
707 					errno = ENOMEM;
708 					goto error;
709 				}
710 			} else {
711 				fparg.dbl = GETARG(double);
712 				dtoaresult =
713 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
714 				    &expt, &signflag, &dtoaend);
715 				if (dtoaresult == NULL) {
716 					errno = ENOMEM;
717 					goto error;
718 				}
719 				if (expt == 9999)
720 					expt = INT_MAX;
721  			}
722 			if (convbuf) {
723 				free(convbuf);
724 				convbuf = NULL;
725 			}
726 			cp = convbuf = __mbsconv(dtoaresult, -1);
727 			if (cp == NULL)
728 				goto error;
729 			ndig = dtoaend - dtoaresult;
730 fp_common:
731 			if (signflag)
732 				sign = '-';
733 			if (expt == INT_MAX) {	/* inf or nan */
734 				if (*cp == 'N')
735 					cp = (ch >= 'a') ? L"nan" : L"NAN";
736 				else
737 					cp = (ch >= 'a') ? L"inf" : L"INF";
738  				size = 3;
739 				flags &= ~ZEROPAD;
740  				break;
741  			}
742 			flags |= FPT;
743  			if (ch == 'g' || ch == 'G') {
744 				if (expt > -4 && expt <= prec) {
745 					/* Make %[gG] smell like %[fF] */
746 					expchar = '\0';
747 					if (flags & ALT)
748 						prec -= expt;
749 					else
750 						prec = ndig - expt;
751 					if (prec < 0)
752 						prec = 0;
753 				} else {
754 					/*
755 					 * Make %[gG] smell like %[eE], but
756 					 * trim trailing zeroes if no # flag.
757 					 */
758 					if (!(flags & ALT))
759 						prec = ndig;
760 				}
761  			}
762 			if (expchar) {
763 				expsize = exponent(expstr, expt - 1, expchar);
764 				size = expsize + prec;
765 				if (prec > 1 || flags & ALT)
766  					++size;
767 			} else {
768 				/* space for digits before decimal point */
769 				if (expt > 0)
770 					size = expt;
771 				else	/* "0" */
772 					size = 1;
773 				/* space for decimal pt and following digits */
774 				if (prec || flags & ALT)
775 					size += prec + 1;
776 				lead = expt;
777 			}
778 			break;
779 #endif /* FLOATING_POINT */
780 #ifndef NO_PRINTF_PERCENT_N
781 		case 'n':
782 			if (flags & LLONGINT)
783 				*GETARG(long long *) = ret;
784 			else if (flags & LONGINT)
785 				*GETARG(long *) = ret;
786 			else if (flags & SHORTINT)
787 				*GETARG(short *) = ret;
788 			else if (flags & CHARINT)
789 				*GETARG(signed char *) = ret;
790 			else if (flags & PTRINT)
791 				*GETARG(ptrdiff_t *) = ret;
792 			else if (flags & SIZEINT)
793 				*GETARG(ssize_t *) = ret;
794 			else if (flags & MAXINT)
795 				*GETARG(intmax_t *) = ret;
796 			else
797 				*GETARG(int *) = ret;
798 			continue;	/* no output */
799 #endif /* NO_PRINTF_PERCENT_N */
800 		case 'O':
801 			flags |= LONGINT;
802 			/*FALLTHROUGH*/
803 		case 'o':
804 			_umax = UARG();
805 			base = OCT;
806 			goto nosign;
807 		case 'p':
808 			/*
809 			 * ``The argument shall be a pointer to void.  The
810 			 * value of the pointer is converted to a sequence
811 			 * of printable characters, in an implementation-
812 			 * defined manner.''
813 			 *	-- ANSI X3J11
814 			 */
815 			/* NOSTRICT */
816 			_umax = (u_long)GETARG(void *);
817 			base = HEX;
818 			xdigs = xdigs_lower;
819 			ox[1] = 'x';
820 			goto nosign;
821 		case 'S':
822 			flags |= LONGINT;
823 			/*FALLTHROUGH*/
824 		case 's':
825 			if (flags & LONGINT) {
826 				if ((cp = GETARG(wchar_t *)) == NULL)
827 					cp = L"(null)";
828 			} else {
829 				char *mbsarg;
830 				if ((mbsarg = GETARG(char *)) == NULL)
831 					mbsarg = "(null)";
832 				if (convbuf) {
833 					free(convbuf);
834 					convbuf = NULL;
835 				}
836 				convbuf = __mbsconv(mbsarg, prec);
837 				if (convbuf == NULL) {
838 					fp->_flags |= __SERR;
839 					goto error;
840 				} else
841 					cp = convbuf;
842 			}
843 			if (prec >= 0) {
844 				/*
845 				 * can't use wcslen; can only look for the
846 				 * NUL in the first `prec' characters, and
847 				 * wcslen() will go further.
848 				 */
849 				wchar_t *p = wmemchr(cp, 0, prec);
850 
851 				size = p ? (p - cp) : prec;
852 			} else {
853 				size_t len;
854 
855 				if ((len = wcslen(cp)) > INT_MAX)
856 					goto overflow;
857 				size = (int)len;
858 			}
859 			sign = '\0';
860 			break;
861 		case 'U':
862 			flags |= LONGINT;
863 			/*FALLTHROUGH*/
864 		case 'u':
865 			_umax = UARG();
866 			base = DEC;
867 			goto nosign;
868 		case 'X':
869 			xdigs = xdigs_upper;
870 			goto hex;
871 		case 'x':
872 			xdigs = xdigs_lower;
873 hex:			_umax = UARG();
874 			base = HEX;
875 			/* leading 0x/X only if non-zero */
876 			if (flags & ALT && _umax != 0)
877 				ox[1] = ch;
878 
879 			/* unsigned conversions */
880 nosign:			sign = '\0';
881 			/*
882 			 * ``... diouXx conversions ... if a precision is
883 			 * specified, the 0 flag will be ignored.''
884 			 *	-- ANSI X3J11
885 			 */
886 number:			if ((dprec = prec) >= 0)
887 				flags &= ~ZEROPAD;
888 
889 			/*
890 			 * ``The result of converting a zero value with an
891 			 * explicit precision of zero is no characters.''
892 			 *	-- ANSI X3J11
893 			 */
894 			cp = buf + BUF;
895 			if (_umax != 0 || prec != 0) {
896 				/*
897 				 * Unsigned mod is hard, and unsigned mod
898 				 * by a constant is easier than that by
899 				 * a variable; hence this switch.
900 				 */
901 				switch (base) {
902 				case OCT:
903 					do {
904 						*--cp = to_char(_umax & 7);
905 						_umax >>= 3;
906 					} while (_umax);
907 					/* handle octal leading 0 */
908 					if (flags & ALT && *cp != '0')
909 						*--cp = '0';
910 					break;
911 
912 				case DEC:
913 					/* many numbers are 1 digit */
914 					while (_umax >= 10) {
915 						*--cp = to_char(_umax % 10);
916 						_umax /= 10;
917 					}
918 					*--cp = to_char(_umax);
919 					break;
920 
921 				case HEX:
922 					do {
923 						*--cp = xdigs[_umax & 15];
924 						_umax >>= 4;
925 					} while (_umax);
926 					break;
927 
928 				default:
929 					cp = L"bug in vfwprintf: bad base";
930 					size = wcslen(cp);
931 					goto skipsize;
932 				}
933 			}
934 			size = buf + BUF - cp;
935 			if (size > BUF)	/* should never happen */
936 				abort();
937 		skipsize:
938 			break;
939 		default:	/* "%?" prints ?, unless ? is NUL */
940 			if (ch == '\0')
941 				goto done;
942 			/* pretend it was %c with argument ch */
943 			cp = buf;
944 			*cp = ch;
945 			size = 1;
946 			sign = '\0';
947 			break;
948 		}
949 
950 		/*
951 		 * All reasonable formats wind up here.  At this point, `cp'
952 		 * points to a string which (if not flags&LADJUST) should be
953 		 * padded out to `width' places.  If flags&ZEROPAD, it should
954 		 * first be prefixed by any sign or other prefix; otherwise,
955 		 * it should be blank padded before the prefix is emitted.
956 		 * After any left-hand padding and prefixing, emit zeroes
957 		 * required by a decimal %[diouxX] precision, then print the
958 		 * string proper, then emit zeroes required by any leftover
959 		 * floating precision; finally, if LADJUST, pad with blanks.
960 		 *
961 		 * Compute actual size, so we know how much to pad.
962 		 * size excludes decimal prec; realsz includes it.
963 		 */
964 		realsz = dprec > size ? dprec : size;
965 		if (sign)
966 			realsz++;
967 		if (ox[1])
968 			realsz+= 2;
969 
970 		/* right-adjusting blank padding */
971 		if ((flags & (LADJUST|ZEROPAD)) == 0)
972 			PAD(width - realsz, blanks);
973 
974 		/* prefix */
975 		if (sign)
976 			PRINT(&sign, 1);
977 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
978 			ox[0] = '0';
979 			PRINT(ox, 2);
980 		}
981 
982 		/* right-adjusting zero padding */
983 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
984 			PAD(width - realsz, zeroes);
985 
986 		/* leading zeroes from decimal precision */
987 		PAD(dprec - size, zeroes);
988 
989 		/* the string or number proper */
990 #ifdef FLOATING_POINT
991 		if ((flags & FPT) == 0) {
992 			PRINT(cp, size);
993 		} else {	/* glue together f_p fragments */
994 			if (decimal_point == NULL)
995 				decimal_point = nl_langinfo(RADIXCHAR);
996 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
997 				if (expt <= 0) {
998 					PRINT(zeroes, 1);
999 					if (prec || flags & ALT)
1000 						PRINT(decimal_point, 1);
1001 					PAD(-expt, zeroes);
1002 					/* already handled initial 0's */
1003 					prec += expt;
1004  				} else {
1005 					PRINTANDPAD(cp, convbuf + ndig,
1006 					    lead, zeroes);
1007 					cp += lead;
1008 					if (prec || flags & ALT)
1009 						PRINT(decimal_point, 1);
1010 				}
1011 				PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1012 			} else {	/* %[eE] or sufficiently long %[gG] */
1013 				if (prec > 1 || flags & ALT) {
1014 					buf[0] = *cp++;
1015 					buf[1] = *decimal_point;
1016 					PRINT(buf, 2);
1017 					PRINT(cp, ndig-1);
1018 					PAD(prec - ndig, zeroes);
1019 				} else { /* XeYYY */
1020 					PRINT(cp, 1);
1021 				}
1022 				PRINT(expstr, expsize);
1023 			}
1024 		}
1025 #else
1026 		PRINT(cp, size);
1027 #endif
1028 		/* left-adjusting padding (always blank) */
1029 		if (flags & LADJUST)
1030 			PAD(width - realsz, blanks);
1031 
1032 		/* finally, adjust ret */
1033 		if (width < realsz)
1034 			width = realsz;
1035 		if (width > INT_MAX - ret)
1036 			goto overflow;
1037 		ret += width;
1038 	}
1039 done:
1040 error:
1041 	va_end(orgap);
1042 	if (__sferror(fp))
1043 		ret = -1;
1044 	goto finish;
1045 
1046 overflow:
1047 	errno = ENOMEM;
1048 	ret = -1;
1049 
1050 finish:
1051 	if (convbuf)
1052 		free(convbuf);
1053 #ifdef FLOATING_POINT
1054 	if (dtoaresult)
1055 		__freedtoa(dtoaresult);
1056 #endif
1057 	if (argtable != NULL && argtable != statargtable) {
1058 		munmap(argtable, argtablesiz);
1059 		argtable = NULL;
1060 	}
1061 	return (ret);
1062 }
1063 
1064 int
vfwprintf(FILE * __restrict fp,const wchar_t * __restrict fmt0,__va_list ap)1065 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, __va_list ap)
1066 {
1067 	int r;
1068 
1069 	FLOCKFILE(fp);
1070 	r = __vfwprintf(fp, fmt0, ap);
1071 	FUNLOCKFILE(fp);
1072 
1073 	return (r);
1074 }
1075 
1076 /*
1077  * Type ids for argument type table.
1078  */
1079 #define T_UNUSED	0
1080 #define T_SHORT		1
1081 #define T_U_SHORT	2
1082 #define TP_SHORT	3
1083 #define T_INT		4
1084 #define T_U_INT		5
1085 #define TP_INT		6
1086 #define T_LONG		7
1087 #define T_U_LONG	8
1088 #define TP_LONG		9
1089 #define T_LLONG		10
1090 #define T_U_LLONG	11
1091 #define TP_LLONG	12
1092 #define T_DOUBLE	13
1093 #define T_LONG_DOUBLE	14
1094 #define TP_CHAR		15
1095 #define TP_VOID		16
1096 #define T_PTRINT	17
1097 #define TP_PTRINT	18
1098 #define T_SIZEINT	19
1099 #define T_SSIZEINT	20
1100 #define TP_SSIZEINT	21
1101 #define T_MAXINT	22
1102 #define T_MAXUINT	23
1103 #define TP_MAXINT	24
1104 #define T_CHAR		25
1105 #define T_U_CHAR	26
1106 #define T_WINT		27
1107 #define TP_WCHAR	28
1108 
1109 /*
1110  * Find all arguments when a positional parameter is encountered.  Returns a
1111  * table, indexed by argument number, of pointers to each arguments.  The
1112  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1113  * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1114  * used since we are attempting to make snprintf thread safe, and alloca is
1115  * problematic since we have nested functions..)
1116  */
1117 static int
__find_arguments(const wchar_t * fmt0,va_list ap,union arg ** argtable,size_t * argtablesiz)1118 __find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
1119     size_t *argtablesiz)
1120 {
1121 	wchar_t *fmt;		/* format string */
1122 	int ch;			/* character from fmt */
1123 	int n, n2;		/* handy integer (short term usage) */
1124 	wchar_t *cp;		/* handy char pointer (short term usage) */
1125 	int flags;		/* flags as above */
1126 	unsigned char *typetable; /* table of types */
1127 	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1128 	int tablesize;		/* current size of type table */
1129 	int tablemax;		/* largest used index in table */
1130 	int nextarg;		/* 1-based argument index */
1131 	int ret = 0;		/* return value */
1132 
1133 	/*
1134 	 * Add an argument type to the table, expanding if necessary.
1135 	 */
1136 #define ADDTYPE(type) \
1137 	((nextarg >= tablesize) ? \
1138 		__grow_type_table(&typetable, &tablesize) : 0, \
1139 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1140 	typetable[nextarg++] = type)
1141 
1142 #define	ADDSARG() \
1143         ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
1144 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1145 	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
1146 	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1147 	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
1148 	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
1149 	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
1150 
1151 #define	ADDUARG() \
1152         ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
1153 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1154 	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
1155 	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1156 	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
1157 	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
1158 	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
1159 
1160 	/*
1161 	 * Add * arguments to the type array.
1162 	 */
1163 #define ADDASTER() \
1164 	n2 = 0; \
1165 	cp = fmt; \
1166 	while (is_digit(*cp)) { \
1167 		APPEND_DIGIT(n2, *cp); \
1168 		cp++; \
1169 	} \
1170 	if (*cp == '$') { \
1171 		int hold = nextarg; \
1172 		nextarg = n2; \
1173 		ADDTYPE(T_INT); \
1174 		nextarg = hold; \
1175 		fmt = ++cp; \
1176 	} else { \
1177 		ADDTYPE(T_INT); \
1178 	}
1179 	fmt = (wchar_t *)fmt0;
1180 	typetable = stattypetable;
1181 	tablesize = STATIC_ARG_TBL_SIZE;
1182 	tablemax = 0;
1183 	nextarg = 1;
1184 	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1185 
1186 	/*
1187 	 * Scan the format for conversions (`%' character).
1188 	 */
1189 	for (;;) {
1190 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1191 			continue;
1192 		if (ch == '\0')
1193 			goto done;
1194 		fmt++;		/* skip over '%' */
1195 
1196 		flags = 0;
1197 
1198 rflag:		ch = *fmt++;
1199 reswitch:	switch (ch) {
1200 		case ' ':
1201 		case '#':
1202 		case '\'':
1203 			goto rflag;
1204 		case '*':
1205 			ADDASTER();
1206 			goto rflag;
1207 		case '-':
1208 		case '+':
1209 			goto rflag;
1210 		case '.':
1211 			if ((ch = *fmt++) == '*') {
1212 				ADDASTER();
1213 				goto rflag;
1214 			}
1215 			while (is_digit(ch)) {
1216 				ch = *fmt++;
1217 			}
1218 			goto reswitch;
1219 		case '0':
1220 			goto rflag;
1221 		case '1': case '2': case '3': case '4':
1222 		case '5': case '6': case '7': case '8': case '9':
1223 			n = 0;
1224 			do {
1225 				APPEND_DIGIT(n ,ch);
1226 				ch = *fmt++;
1227 			} while (is_digit(ch));
1228 			if (ch == '$') {
1229 				nextarg = n;
1230 				goto rflag;
1231 			}
1232 			goto reswitch;
1233 #ifdef FLOATING_POINT
1234 		case 'L':
1235 			flags |= LONGDBL;
1236 			goto rflag;
1237 #endif
1238 		case 'h':
1239 			if (*fmt == 'h') {
1240 				fmt++;
1241 				flags |= CHARINT;
1242 			} else {
1243 				flags |= SHORTINT;
1244 			}
1245 			goto rflag;
1246 		case 'l':
1247 			if (*fmt == 'l') {
1248 				fmt++;
1249 				flags |= LLONGINT;
1250 			} else {
1251 				flags |= LONGINT;
1252 			}
1253 			goto rflag;
1254 		case 'q':
1255 			flags |= LLONGINT;
1256 			goto rflag;
1257 		case 't':
1258 			flags |= PTRINT;
1259 			goto rflag;
1260 		case 'z':
1261 			flags |= SIZEINT;
1262 			goto rflag;
1263 		case 'C':
1264 			flags |= LONGINT;
1265 			/*FALLTHROUGH*/
1266 		case 'c':
1267 			if (flags & LONGINT)
1268 				ADDTYPE(T_WINT);
1269 			else
1270 				ADDTYPE(T_INT);
1271 			break;
1272 		case 'D':
1273 			flags |= LONGINT;
1274 			/*FALLTHROUGH*/
1275 		case 'd':
1276 		case 'i':
1277 			ADDSARG();
1278 			break;
1279 #ifdef FLOATING_POINT
1280 		case 'a':
1281 		case 'A':
1282 		case 'e':
1283 		case 'E':
1284 		case 'f':
1285 		case 'F':
1286 		case 'g':
1287 		case 'G':
1288 			if (flags & LONGDBL)
1289 				ADDTYPE(T_LONG_DOUBLE);
1290 			else
1291 				ADDTYPE(T_DOUBLE);
1292 			break;
1293 #endif /* FLOATING_POINT */
1294 #ifndef NO_PRINTF_PERCENT_N
1295 		case 'n':
1296 			if (flags & LLONGINT)
1297 				ADDTYPE(TP_LLONG);
1298 			else if (flags & LONGINT)
1299 				ADDTYPE(TP_LONG);
1300 			else if (flags & SHORTINT)
1301 				ADDTYPE(TP_SHORT);
1302 			else if (flags & PTRINT)
1303 				ADDTYPE(TP_PTRINT);
1304 			else if (flags & SIZEINT)
1305 				ADDTYPE(TP_SSIZEINT);
1306 			else if (flags & MAXINT)
1307 				ADDTYPE(TP_MAXINT);
1308 			else
1309 				ADDTYPE(TP_INT);
1310 			continue;	/* no output */
1311 #endif /* NO_PRINTF_PERCENT_N */
1312 		case 'O':
1313 			flags |= LONGINT;
1314 			/*FALLTHROUGH*/
1315 		case 'o':
1316 			ADDUARG();
1317 			break;
1318 		case 'p':
1319 			ADDTYPE(TP_VOID);
1320 			break;
1321 		case 'S':
1322 			flags |= LONGINT;
1323 			/*FALLTHROUGH*/
1324 		case 's':
1325 			if (flags & LONGINT)
1326 				ADDTYPE(TP_CHAR);
1327 			else
1328 				ADDTYPE(TP_WCHAR);
1329 			break;
1330 		case 'U':
1331 			flags |= LONGINT;
1332 			/*FALLTHROUGH*/
1333 		case 'u':
1334 		case 'X':
1335 		case 'x':
1336 			ADDUARG();
1337 			break;
1338 		default:	/* "%?" prints ?, unless ? is NUL */
1339 			if (ch == '\0')
1340 				goto done;
1341 			break;
1342 		}
1343 	}
1344 done:
1345 	/*
1346 	 * Build the argument table.
1347 	 */
1348 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1349 		*argtablesiz = sizeof(union arg) * (tablemax + 1);
1350 		*argtable = mmap(NULL, *argtablesiz,
1351 		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
1352 		if (*argtable == MAP_FAILED)
1353 			return (-1);
1354 	}
1355 
1356 #if 0
1357 	/* XXX is this required? */
1358 	(*argtable)[0].intarg = 0;
1359 #endif
1360 	for (n = 1; n <= tablemax; n++) {
1361 		switch (typetable[n]) {
1362 		case T_UNUSED:
1363 		case T_CHAR:
1364 		case T_U_CHAR:
1365 		case T_SHORT:
1366 		case T_U_SHORT:
1367 		case T_INT:
1368 			(*argtable)[n].intarg = va_arg(ap, int);
1369 			break;
1370 		case TP_SHORT:
1371 			(*argtable)[n].pshortarg = va_arg(ap, short *);
1372 			break;
1373 		case T_U_INT:
1374 			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
1375 			break;
1376 		case TP_INT:
1377 			(*argtable)[n].pintarg = va_arg(ap, int *);
1378 			break;
1379 		case T_LONG:
1380 			(*argtable)[n].longarg = va_arg(ap, long);
1381 			break;
1382 		case T_U_LONG:
1383 			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1384 			break;
1385 		case TP_LONG:
1386 			(*argtable)[n].plongarg = va_arg(ap, long *);
1387 			break;
1388 		case T_LLONG:
1389 			(*argtable)[n].longlongarg = va_arg(ap, long long);
1390 			break;
1391 		case T_U_LLONG:
1392 			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1393 			break;
1394 		case TP_LLONG:
1395 			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
1396 			break;
1397 #ifdef FLOATING_POINT
1398 		case T_DOUBLE:
1399 			(*argtable)[n].doublearg = va_arg(ap, double);
1400 			break;
1401 		case T_LONG_DOUBLE:
1402 			(*argtable)[n].longdoublearg = va_arg(ap, long double);
1403 			break;
1404 #endif
1405 		case TP_CHAR:
1406 			(*argtable)[n].pchararg = va_arg(ap, char *);
1407 			break;
1408 		case TP_VOID:
1409 			(*argtable)[n].pvoidarg = va_arg(ap, void *);
1410 			break;
1411 		case T_PTRINT:
1412 			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1413 			break;
1414 		case TP_PTRINT:
1415 			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
1416 			break;
1417 		case T_SIZEINT:
1418 			(*argtable)[n].sizearg = va_arg(ap, size_t);
1419 			break;
1420 		case T_SSIZEINT:
1421 			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
1422 			break;
1423 		case TP_SSIZEINT:
1424 			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
1425 			break;
1426 		case TP_MAXINT:
1427 			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1428 			break;
1429 		case T_WINT:
1430 			(*argtable)[n].wintarg = va_arg(ap, wint_t);
1431 			break;
1432 		case TP_WCHAR:
1433 			(*argtable)[n].pwchararg = va_arg(ap, wchar_t *);
1434 			break;
1435 		}
1436 	}
1437 	goto finish;
1438 
1439 overflow:
1440 	errno = ENOMEM;
1441 	ret = -1;
1442 
1443 finish:
1444 	if (typetable != NULL && typetable != stattypetable) {
1445 		munmap(typetable, *argtablesiz);
1446 		typetable = NULL;
1447 	}
1448 	return (ret);
1449 }
1450 
1451 /*
1452  * Increase the size of the type table.
1453  */
1454 static int
__grow_type_table(unsigned char ** typetable,int * tablesize)1455 __grow_type_table(unsigned char **typetable, int *tablesize)
1456 {
1457 	unsigned char *oldtable = *typetable;
1458 	int newsize = *tablesize * 2;
1459 
1460 	if (newsize < getpagesize())
1461 		newsize = getpagesize();
1462 
1463 	if (*tablesize == STATIC_ARG_TBL_SIZE) {
1464 		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1465 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1466 		if (*typetable == MAP_FAILED)
1467 			return (-1);
1468 		bcopy(oldtable, *typetable, *tablesize);
1469 	} else {
1470 		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
1471 		    MAP_ANON|MAP_PRIVATE, -1, 0);
1472 		if (new == MAP_FAILED)
1473 			return (-1);
1474 		memmove(new, *typetable, *tablesize);
1475 		munmap(*typetable, *tablesize);
1476 		*typetable = new;
1477 	}
1478 	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
1479 
1480 	*tablesize = newsize;
1481 	return (0);
1482 }
1483 
1484 
1485 #ifdef FLOATING_POINT
1486 static int
exponent(wchar_t * p0,int exp,int fmtch)1487 exponent(wchar_t *p0, int exp, int fmtch)
1488 {
1489 	wchar_t *p, *t;
1490 	wchar_t expbuf[MAXEXPDIG];
1491 
1492 	p = p0;
1493 	*p++ = fmtch;
1494 	if (exp < 0) {
1495 		exp = -exp;
1496 		*p++ = '-';
1497 	} else
1498 		*p++ = '+';
1499 	t = expbuf + MAXEXPDIG;
1500 	if (exp > 9) {
1501 		do {
1502 			*--t = to_char(exp % 10);
1503 		} while ((exp /= 10) > 9);
1504 		*--t = to_char(exp);
1505 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++)
1506 			/* nothing */;
1507 	} else {
1508 		/*
1509 		 * Exponents for decimal floating point conversions
1510 		 * (%[eEgG]) must be at least two characters long,
1511 		 * whereas exponents for hexadecimal conversions can
1512 		 * be only one character long.
1513 		 */
1514 		if (fmtch == 'e' || fmtch == 'E')
1515 			*p++ = '0';
1516 		*p++ = to_char(exp);
1517 	}
1518 	return (p - p0);
1519 }
1520 #endif /* FLOATING_POINT */
1521