blob: fe2e338e72da7d38425e5d696ecb757a6f394910 [file] [log] [blame]
Elliott Hughes506c6de2016-01-15 16:30:18 -08001/* $OpenBSD: vfprintf.c,v 1.71 2016/01/04 15:47:47 schwarze Exp $ */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002/*-
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
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -070034#define CHAR_TYPE char
Elliott Hughes93a1f8b2017-11-07 22:52:29 -080035#define FUNCTION_NAME __vfprintf
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080036
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080037#include <sys/mman.h>
Elliott Hughesc8f2c522017-10-31 13:07:51 -070038#include <sys/types.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080039
40#include <errno.h>
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -070041#include <float.h>
Elliott Hughes05493712014-04-17 17:30:03 -070042#include <langinfo.h>
43#include <limits.h>
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -070044#include <locale.h>
45#include <math.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080046#include <stdarg.h>
47#include <stddef.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080048#include <stdint.h>
Elliott Hughesc8f2c522017-10-31 13:07:51 -070049#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080050#include <stdlib.h>
51#include <string.h>
Elliott Hughes05493712014-04-17 17:30:03 -070052#include <unistd.h>
53#include <wchar.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080054
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080055#include "fvwrite.h"
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -070056#include "gdtoa.h"
Elliott Hughesc8f2c522017-10-31 13:07:51 -070057#include "local.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058
Alexander Ivchenkoedd7c2e2014-04-01 17:01:39 +040059union arg {
Elliott Hughesc8f2c522017-10-31 13:07:51 -070060 int intarg;
61 unsigned int uintarg;
62 long longarg;
63 unsigned long ulongarg;
64 long long longlongarg;
65 unsigned long long ulonglongarg;
66 ptrdiff_t ptrdiffarg;
67 size_t sizearg;
68 ssize_t ssizearg;
69 intmax_t intmaxarg;
70 uintmax_t uintmaxarg;
71 void* pvoidarg;
72 char* pchararg;
73 signed char* pschararg;
74 short* pshortarg;
75 int* pintarg;
76 long* plongarg;
77 long long* plonglongarg;
78 ptrdiff_t* pptrdiffarg;
79 ssize_t* pssizearg;
80 intmax_t* pintmaxarg;
81 double doublearg;
82 long double longdoublearg;
83 wint_t wintarg;
84 wchar_t* pwchararg;
Alexander Ivchenkoedd7c2e2014-04-01 17:01:39 +040085};
86
Elliott Hughes618303c2017-11-02 16:58:44 -070087static int __find_arguments(const CHAR_TYPE* fmt0, va_list ap, union arg** argtable, size_t* argtablesiz);
Elliott Hughesc8f2c522017-10-31 13:07:51 -070088static int __grow_type_table(unsigned char** typetable, int* tablesize);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080089
90/*
91 * Flush out all the vectors defined by the given uio,
92 * then reset it so that it can be reused.
93 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -070094static int __sprint(FILE* fp, struct __suio* uio) {
95 int err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080096
Elliott Hughesc8f2c522017-10-31 13:07:51 -070097 if (uio->uio_resid == 0) {
98 uio->uio_iovcnt = 0;
99 return (0);
100 }
101 err = __sfvwrite(fp, uio);
102 uio->uio_resid = 0;
103 uio->uio_iovcnt = 0;
104 return (err);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800105}
106
107/*
108 * Helper function for `fprintf to unbuffered unix file': creates a
109 * temporary buffer. We only work on write-only files; this avoids
110 * worries about ungetc buffers and so forth.
111 */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800112static int __sbprintf(FILE* fp, const CHAR_TYPE* fmt, va_list ap) {
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700113 FILE fake;
114 struct __sfileext fakeext;
115 unsigned char buf[BUFSIZ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800116
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700117 _FILEEXT_SETUP(&fake, &fakeext);
118 /* copy the important variables */
119 fake._flags = fp->_flags & ~__SNBF;
120 fake._file = fp->_file;
121 fake._cookie = fp->_cookie;
122 fake._write = fp->_write;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700124 /* set up the buffer */
125 fake._bf._base = fake._p = buf;
126 fake._bf._size = fake._w = sizeof(buf);
127 fake._lbfsize = 0; /* not actually used, but Just In Case */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800128
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700129 /* do the work, then copy any error status */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800130 int ret = FUNCTION_NAME(&fake, fmt, ap);
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700131 if (ret >= 0 && __sflush(&fake)) ret = EOF;
132 if (fake._flags & __SERR) fp->_flags |= __SERR;
133 return (ret);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800134}
135
Elliott Hughes05493712014-04-17 17:30:03 -0700136/*
137 * Convert a wide character string argument for the %ls format to a multibyte
138 * string representation. If not -1, prec specifies the maximum number of
139 * bytes to output, and also means that we can't assume that the wide char
140 * string is null-terminated.
141 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700142static char* __wcsconv(wchar_t* wcsarg, int prec) {
143 mbstate_t mbs;
144 char buf[MB_LEN_MAX];
145 wchar_t* p;
146 char* convbuf;
147 size_t clen, nbytes;
Elliott Hughes05493712014-04-17 17:30:03 -0700148
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700149 /* Allocate space for the maximum number of bytes we could output. */
150 if (prec < 0) {
151 memset(&mbs, 0, sizeof(mbs));
152 p = wcsarg;
153 nbytes = wcsrtombs(NULL, (const wchar_t**)&p, 0, &mbs);
154 if (nbytes == (size_t)-1) return (NULL);
155 } else {
156 /*
157 * Optimisation: if the output precision is small enough,
158 * just allocate enough memory for the maximum instead of
159 * scanning the string.
160 */
161 if (prec < 128)
162 nbytes = prec;
163 else {
164 nbytes = 0;
165 p = wcsarg;
166 memset(&mbs, 0, sizeof(mbs));
167 for (;;) {
168 clen = wcrtomb(buf, *p++, &mbs);
169 if (clen == 0 || clen == (size_t)-1 || nbytes + clen > (size_t)prec) break;
170 nbytes += clen;
171 }
172 if (clen == (size_t)-1) return (NULL);
173 }
174 }
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700175 if ((convbuf = static_cast<char*>(malloc(nbytes + 1))) == NULL) return NULL;
Elliott Hughes05493712014-04-17 17:30:03 -0700176
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700177 /* Fill the output buffer. */
178 p = wcsarg;
179 memset(&mbs, 0, sizeof(mbs));
180 if ((nbytes = wcsrtombs(convbuf, (const wchar_t**)&p, nbytes, &mbs)) == (size_t)-1) {
181 free(convbuf);
182 return (NULL);
183 }
184 convbuf[nbytes] = '\0';
185 return (convbuf);
Elliott Hughes05493712014-04-17 17:30:03 -0700186}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800187
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700188#define DEFPREC 6
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800189
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700190#define to_digit(c) ((c) - '0')
191#define is_digit(c) ((unsigned)to_digit(c) <= 9)
192#define to_char(n) ((CHAR_TYPE)((n) + '0'))
193
194template <typename CharT>
195static int exponent(CharT* p0, int exp, int fmtch) {
196 CharT* p = p0;
197 *p++ = fmtch;
198 if (exp < 0) {
199 exp = -exp;
200 *p++ = '-';
201 } else {
202 *p++ = '+';
203 }
204
205 CharT expbuf[MAXEXPDIG];
206 CharT* t = expbuf + MAXEXPDIG;
207 if (exp > 9) {
208 do {
209 *--t = to_char(exp % 10);
210 } while ((exp /= 10) > 9);
211 *--t = to_char(exp);
212 for (; t < expbuf + MAXEXPDIG; *p++ = *t++) /* nothing */;
213 } else {
214 /*
215 * Exponents for decimal floating point conversions
216 * (%[eEgG]) must be at least two characters long,
217 * whereas exponents for hexadecimal conversions can
218 * be only one character long.
219 */
220 if (fmtch == 'e' || fmtch == 'E') *p++ = '0';
221 *p++ = to_char(exp);
222 }
223 return (p - p0);
224}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800225
Elliott Hughes05493712014-04-17 17:30:03 -0700226/*
227 * The size of the buffer we use as scratch space for integer
228 * conversions, among other things. Technically, we would need the
229 * most space for base 10 conversions with thousands' grouping
230 * characters between each pair of digits. 100 bytes is a
231 * conservative overestimate even for a 128-bit uintmax_t.
232 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700233#define BUF 100
Elliott Hughes05493712014-04-17 17:30:03 -0700234
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700235#define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
Elliott Hughes05493712014-04-17 17:30:03 -0700236
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800237/*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800238 * Flags used during conversion.
239 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700240#define ALT 0x0001 /* alternate form */
241#define LADJUST 0x0004 /* left adjustment */
242#define LONGDBL 0x0008 /* long double */
243#define LONGINT 0x0010 /* long integer */
244#define LLONGINT 0x0020 /* long long integer */
245#define SHORTINT 0x0040 /* short integer */
246#define ZEROPAD 0x0080 /* zero (as opposed to blank) pad */
247#define FPT 0x0100 /* Floating point number */
248#define PTRINT 0x0200 /* (unsigned) ptrdiff_t */
249#define SIZEINT 0x0400 /* (signed) size_t */
250#define CHARINT 0x0800 /* 8 bit integer */
251#define MAXINT 0x1000 /* largest integer size (intmax_t) */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800252
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800253int FUNCTION_NAME(FILE* fp, const CHAR_TYPE* fmt0, __va_list ap) {
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700254 int ch; /* character from fmt */
255 int n, n2; /* handy integers (short term usage) */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800256 CHAR_TYPE* cp; /* handy char pointer (short term usage) */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700257 struct __siov* iovp; /* for PRINT macro */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800258 CHAR_TYPE sign; /* sign prefix (' ', '+', '-', or \0) */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700259 int flags; /* flags as above */
260 int ret; /* return value accumulator */
261 int width; /* width from format (%8d), or 0 */
262 int prec; /* precision from format; <0 for N/A */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700263 /*
264 * We can decompose the printed representation of floating
265 * point numbers into several parts, some of which may be empty:
266 *
267 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
268 * A B ---C--- D E F
269 *
270 * A: 'sign' holds this value if present; '\0' otherwise
271 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
272 * C: cp points to the string MMMNNN. Leading and trailing
273 * zeros are not in the string and must be added.
274 * D: expchar holds this character; '\0' if no exponent, e.g. %f
275 * F: at least two digits for decimal, at least one digit for hex
276 */
277 char* decimal_point = NULL;
278 int signflag; /* true if float is negative */
279 union { /* floating point arguments %[aAeEfFgG] */
280 double dbl;
281 long double ldbl;
282 } fparg;
283 int expt; /* integer value of exponent */
284 char expchar; /* exponent character: [eEpP\0] */
285 char* dtoaend; /* pointer to end of converted digits */
286 int expsize; /* character count for expstr */
287 int lead; /* sig figs before decimal or group sep */
288 int ndig; /* actual number of digits returned by dtoa */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800289 CHAR_TYPE expstr[MAXEXPDIG + 2]; /* buffer for exponent string: e+ZZZ */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700290 char* dtoaresult = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800291
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700292 uintmax_t _umax; /* integer arguments %[diouxX] */
293 enum { OCT, DEC, HEX } base; /* base for %[diouxX] conversion */
294 int dprec; /* a copy of prec if %[diouxX], 0 otherwise */
295 int realsz; /* field size expanded by dprec */
296 int size; /* size of converted field or string */
297 const char* xdigs; /* digits for %[xX] conversion */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800298#define NIOV 8
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700299 struct __suio uio; /* output information: summary */
300 struct __siov iov[NIOV]; /* ... and individual io vectors */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800301 CHAR_TYPE buf[BUF]; /* buffer with space for digits of uintmax_t */
302 CHAR_TYPE ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700303 union arg* argtable; /* args, built due to positional arg */
304 union arg statargtable[STATIC_ARG_TBL_SIZE];
305 size_t argtablesiz;
306 int nextarg; /* 1-based argument index */
307 va_list orgap; /* original argument pointer */
Elliott Hughes93a1f8b2017-11-07 22:52:29 -0800308 CHAR_TYPE* convbuf; /* buffer for wide/multibyte conversion */
Elliott Hughes05493712014-04-17 17:30:03 -0700309
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700310 /*
311 * Choose PADSIZE to trade efficiency vs. size. If larger printf
312 * fields occur frequently, increase PADSIZE and make the initialisers
313 * below longer.
314 */
315#define PADSIZE 16 /* pad chunk size */
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700316 static CHAR_TYPE blanks[PADSIZE] = {
317 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
318 };
319 static CHAR_TYPE zeroes[PADSIZE] = {
320 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'
321 };
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800322
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700323 static const char xdigs_lower[] = "0123456789abcdef";
324 static const char xdigs_upper[] = "0123456789ABCDEF";
Elliott Hughes05493712014-04-17 17:30:03 -0700325
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700326 /*
327 * BEWARE, these `goto error' on error, and PAD uses `n'.
328 */
329#define PRINT(ptr, len) \
330 do { \
331 iovp->iov_base = (ptr); \
332 iovp->iov_len = (len); \
333 uio.uio_resid += (len); \
334 iovp++; \
335 if (++uio.uio_iovcnt >= NIOV) { \
336 if (__sprint(fp, &uio)) goto error; \
337 iovp = iov; \
338 } \
339 } while (0)
340#define PAD(howmany, with) \
341 do { \
342 if ((n = (howmany)) > 0) { \
343 while (n > PADSIZE) { \
344 PRINT(with, PADSIZE); \
345 n -= PADSIZE; \
346 } \
347 PRINT(with, n); \
348 } \
349 } while (0)
350#define PRINTANDPAD(p, ep, len, with) \
351 do { \
352 n2 = (ep) - (p); \
353 if (n2 > (len)) n2 = (len); \
354 if (n2 > 0) PRINT((p), n2); \
355 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
356 } while (0)
357#define FLUSH() \
358 do { \
359 if (uio.uio_resid && __sprint(fp, &uio)) goto error; \
360 uio.uio_iovcnt = 0; \
361 iovp = iov; \
362 } while (0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800363
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700364 /*
365 * To extend shorts properly, we need both signed and unsigned
366 * argument extraction methods.
367 */
368#define SARG() \
369 ((intmax_t)(flags & MAXINT \
370 ? GETARG(intmax_t) \
371 : flags & LLONGINT \
372 ? GETARG(long long) \
373 : flags & LONGINT \
374 ? GETARG(long) \
375 : flags & PTRINT \
376 ? GETARG(ptrdiff_t) \
377 : flags & SIZEINT \
378 ? GETARG(ssize_t) \
379 : flags & SHORTINT \
380 ? (short)GETARG(int) \
381 : flags & CHARINT ? (signed char)GETARG(int) \
382 : GETARG(int)))
383#define UARG() \
384 ((uintmax_t)(flags & MAXINT \
385 ? GETARG(uintmax_t) \
386 : flags & LLONGINT \
387 ? GETARG(unsigned long long) \
388 : flags & LONGINT \
389 ? GETARG(unsigned long) \
390 : flags & PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
391 flags & SIZEINT \
392 ? GETARG(size_t) \
393 : flags & SHORTINT \
394 ? (unsigned short)GETARG(int) \
395 : flags & CHARINT ? (unsigned char)GETARG(int) \
396 : GETARG(unsigned int)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800397
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700398 /*
399 * Append a digit to a value and check for overflow.
400 */
401#define APPEND_DIGIT(val, dig) \
402 do { \
403 if ((val) > INT_MAX / 10) goto overflow; \
404 (val) *= 10; \
405 if ((val) > INT_MAX - to_digit((dig))) goto overflow; \
406 (val) += to_digit((dig)); \
407 } while (0)
Elliott Hughes05493712014-04-17 17:30:03 -0700408
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700409 /*
410 * Get * arguments, including the form *nn$. Preserve the nextarg
411 * that the argument can be gotten once the type is determined.
412 */
413#define GETASTER(val) \
414 n2 = 0; \
415 cp = fmt; \
416 while (is_digit(*cp)) { \
417 APPEND_DIGIT(n2, *cp); \
418 cp++; \
419 } \
420 if (*cp == '$') { \
421 int hold = nextarg; \
422 if (argtable == NULL) { \
423 argtable = statargtable; \
424 if (__find_arguments(fmt0, orgap, &argtable, &argtablesiz) == -1) { \
425 ret = -1; \
426 goto error; \
427 } \
428 } \
429 nextarg = n2; \
430 val = GETARG(int); \
431 nextarg = hold; \
432 fmt = ++cp; \
433 } else { \
434 val = GETARG(int); \
435 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800436
437/*
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700438 * Get the argument indexed by nextarg. If the argument table is
439 * built, use it to get the argument. If its not, get the next
440 * argument (and arguments must be gotten sequentially).
441 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800442#define GETARG(type) \
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700443 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : (nextarg++, va_arg(ap, type)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800444
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700445 _SET_ORIENTATION(fp, -1);
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700446
447 // Writing "" to a read only file returns EOF, not 0.
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700448 if (cantwrite(fp)) {
449 errno = EBADF;
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700450 return EOF;
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700451 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800452
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700453 // Optimize writes to stderr and other unbuffered files).
454 if ((fp->_flags & (__SNBF | __SWR | __SRW)) == (__SNBF | __SWR) && fp->_file >= 0) {
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700455 return (__sbprintf(fp, fmt0, ap));
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700456 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800457
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700458 CHAR_TYPE* fmt = const_cast<CHAR_TYPE*>(fmt0);
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700459 argtable = NULL;
460 nextarg = 1;
461 va_copy(orgap, ap);
462 uio.uio_iov = iovp = iov;
463 uio.uio_resid = 0;
464 uio.uio_iovcnt = 0;
465 ret = 0;
466 convbuf = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800467
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700468 /*
469 * Scan the format for conversions (`%' character).
470 */
471 for (;;) {
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700472 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) continue;
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700473 if (fmt != cp) {
474 ptrdiff_t m = fmt - cp;
475 if (m < 0 || m > INT_MAX - ret) goto overflow;
476 PRINT(cp, m);
477 ret += m;
478 }
Elliott Hughes5305a4d2017-11-03 14:00:37 -0700479 if (ch == '\0') goto done;
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700480 fmt++; /* skip over '%' */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800481
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700482 flags = 0;
483 dprec = 0;
484 width = 0;
485 prec = -1;
486 sign = '\0';
487 ox[1] = '\0';
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800488
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700489 rflag:
490 ch = *fmt++;
491 reswitch:
492 switch (ch) {
493 case ' ':
494 /*
495 * ``If the space and + flags both appear, the space
496 * flag will be ignored.''
497 * -- ANSI X3J11
498 */
499 if (!sign) 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) goto rflag;
516 if (width == INT_MIN) goto overflow;
517 width = -width;
518 /* FALLTHROUGH */
519 case '-':
520 flags |= LADJUST;
521 goto rflag;
522 case '+':
523 sign = '+';
524 goto rflag;
525 case '.':
526 if ((ch = *fmt++) == '*') {
527 GETASTER(n);
528 prec = n < 0 ? -1 : n;
529 goto rflag;
530 }
531 n = 0;
532 while (is_digit(ch)) {
533 APPEND_DIGIT(n, ch);
534 ch = *fmt++;
535 }
536 if (ch == '$') {
537 nextarg = n;
538 if (argtable == NULL) {
539 argtable = statargtable;
540 if (__find_arguments(fmt0, orgap, &argtable, &argtablesiz) == -1) {
541 ret = -1;
542 goto error;
543 }
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':
558 case '2':
559 case '3':
560 case '4':
561 case '5':
562 case '6':
563 case '7':
564 case '8':
565 case '9':
566 n = 0;
567 do {
568 APPEND_DIGIT(n, ch);
569 ch = *fmt++;
570 } while (is_digit(ch));
571 if (ch == '$') {
572 nextarg = n;
573 if (argtable == NULL) {
574 argtable = statargtable;
575 if (__find_arguments(fmt0, orgap, &argtable, &argtablesiz) == -1) {
576 ret = -1;
577 goto error;
578 }
579 }
580 goto rflag;
581 }
582 width = n;
583 goto reswitch;
584 case 'L':
585 flags |= LONGDBL;
586 goto rflag;
587 case 'h':
588 if (*fmt == 'h') {
589 fmt++;
590 flags |= CHARINT;
591 } else {
592 flags |= SHORTINT;
593 }
594 goto rflag;
595 case 'j':
596 flags |= MAXINT;
597 goto rflag;
598 case 'l':
599 if (*fmt == 'l') {
600 fmt++;
601 flags |= LLONGINT;
602 } else {
603 flags |= LONGINT;
604 }
605 goto rflag;
606 case 'q':
607 flags |= LLONGINT;
608 goto rflag;
609 case 't':
610 flags |= PTRINT;
611 goto rflag;
612 case 'z':
613 flags |= SIZEINT;
614 goto rflag;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700615 case 'C':
616 flags |= LONGINT;
617 /*FALLTHROUGH*/
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700618 case 'c':
619 if (flags & LONGINT) {
620 mbstate_t mbs;
621 size_t mbseqlen;
Elliott Hughes05493712014-04-17 17:30:03 -0700622
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700623 memset(&mbs, 0, sizeof(mbs));
624 mbseqlen = wcrtomb(buf, (wchar_t)GETARG(wint_t), &mbs);
625 if (mbseqlen == (size_t)-1) {
626 ret = -1;
627 goto error;
628 }
629 cp = buf;
630 size = (int)mbseqlen;
631 } else {
632 *(cp = buf) = GETARG(int);
633 size = 1;
634 }
635 sign = '\0';
636 break;
637 case 'D':
638 flags |= LONGINT;
639 /*FALLTHROUGH*/
640 case 'd':
641 case 'i':
642 _umax = SARG();
643 if ((intmax_t)_umax < 0) {
644 _umax = -_umax;
645 sign = '-';
646 }
647 base = DEC;
648 goto number;
649 case 'a':
650 case 'A':
651 if (ch == 'a') {
652 ox[1] = 'x';
653 xdigs = xdigs_lower;
654 expchar = 'p';
655 } else {
656 ox[1] = 'X';
657 xdigs = xdigs_upper;
658 expchar = 'P';
659 }
660 if (prec >= 0) prec++;
661 if (dtoaresult) __freedtoa(dtoaresult);
662 if (flags & LONGDBL) {
663 fparg.ldbl = GETARG(long double);
664 dtoaresult = cp = __hldtoa(fparg.ldbl, xdigs, prec, &expt, &signflag, &dtoaend);
665 if (dtoaresult == NULL) {
666 errno = ENOMEM;
667 goto error;
668 }
669 } else {
670 fparg.dbl = GETARG(double);
671 dtoaresult = cp = __hdtoa(fparg.dbl, xdigs, prec, &expt, &signflag, &dtoaend);
672 if (dtoaresult == NULL) {
673 errno = ENOMEM;
674 goto error;
675 }
676 }
677 if (prec < 0) prec = dtoaend - cp;
678 if (expt == INT_MAX) ox[1] = '\0';
679 goto fp_common;
680 case 'e':
681 case 'E':
682 expchar = ch;
683 if (prec < 0) /* account for digit before decpt */
684 prec = DEFPREC + 1;
685 else
686 prec++;
687 goto fp_begin;
688 case 'f':
689 case 'F':
690 expchar = '\0';
691 goto fp_begin;
692 case 'g':
693 case 'G':
694 expchar = ch - ('g' - 'e');
695 if (prec == 0) prec = 1;
696 fp_begin:
697 if (prec < 0) prec = DEFPREC;
698 if (dtoaresult) __freedtoa(dtoaresult);
699 if (flags & LONGDBL) {
700 fparg.ldbl = GETARG(long double);
701 dtoaresult = cp = __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, &expt, &signflag, &dtoaend);
702 if (dtoaresult == NULL) {
703 errno = ENOMEM;
704 goto error;
705 }
706 } else {
707 fparg.dbl = GETARG(double);
708 dtoaresult = cp = __dtoa(fparg.dbl, expchar ? 2 : 3, prec, &expt, &signflag, &dtoaend);
709 if (dtoaresult == NULL) {
710 errno = ENOMEM;
711 goto error;
712 }
713 if (expt == 9999) expt = INT_MAX;
714 }
715 fp_common:
716 if (signflag) sign = '-';
717 if (expt == INT_MAX) { /* inf or nan */
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700718 if (*cp == 'N') {
719 cp = const_cast<char*>((ch >= 'a') ? "nan" : "NAN");
720 } else {
721 cp = const_cast<char*>((ch >= 'a') ? "inf" : "INF");
722 }
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700723 size = 3;
724 flags &= ~ZEROPAD;
725 break;
726 }
727 flags |= FPT;
728 ndig = dtoaend - cp;
729 if (ch == 'g' || ch == 'G') {
730 if (expt > -4 && expt <= prec) {
731 /* Make %[gG] smell like %[fF] */
732 expchar = '\0';
733 if (flags & ALT)
734 prec -= expt;
735 else
736 prec = ndig - expt;
737 if (prec < 0) prec = 0;
738 } else {
739 /*
740 * Make %[gG] smell like %[eE], but
741 * trim trailing zeroes if no # flag.
742 */
743 if (!(flags & ALT)) prec = ndig;
744 }
745 }
746 if (expchar) {
747 expsize = exponent(expstr, expt - 1, expchar);
748 size = expsize + prec;
749 if (prec > 1 || flags & ALT) ++size;
750 } else {
751 /* space for digits before decimal point */
752 if (expt > 0)
753 size = expt;
754 else /* "0" */
755 size = 1;
756 /* space for decimal pt and following digits */
757 if (prec || flags & ALT) size += prec + 1;
758 lead = expt;
759 }
760 break;
Elliott Hughese2341d02014-05-02 18:16:32 -0700761#ifndef NO_PRINTF_PERCENT_N
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700762 case 'n':
763 if (flags & LLONGINT)
764 *GETARG(long long*) = ret;
765 else if (flags & LONGINT)
766 *GETARG(long*) = ret;
767 else if (flags & SHORTINT)
768 *GETARG(short*) = ret;
769 else if (flags & CHARINT)
770 *GETARG(signed char*) = ret;
771 else if (flags & PTRINT)
772 *GETARG(ptrdiff_t*) = ret;
773 else if (flags & SIZEINT)
774 *GETARG(ssize_t*) = ret;
775 else if (flags & MAXINT)
776 *GETARG(intmax_t*) = ret;
777 else
778 *GETARG(int*) = ret;
779 continue; /* no output */
780#endif /* NO_PRINTF_PERCENT_N */
781 case 'O':
782 flags |= LONGINT;
783 /*FALLTHROUGH*/
784 case 'o':
785 _umax = UARG();
786 base = OCT;
787 goto nosign;
788 case 'p':
789 /*
790 * ``The argument shall be a pointer to void. The
791 * value of the pointer is converted to a sequence
792 * of printable characters, in an implementation-
793 * defined manner.''
794 * -- ANSI X3J11
795 */
796 _umax = (u_long)GETARG(void*);
797 base = HEX;
798 xdigs = xdigs_lower;
799 ox[1] = 'x';
800 goto nosign;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700801 case 'S':
802 flags |= LONGINT;
803 /*FALLTHROUGH*/
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700804 case 's':
805 if (flags & LONGINT) {
806 wchar_t* wcp;
Elliott Hughes05493712014-04-17 17:30:03 -0700807
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700808 free(convbuf);
809 convbuf = NULL;
810 if ((wcp = GETARG(wchar_t*)) == NULL) {
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700811 cp = const_cast<char*>("(null)");
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700812 } else {
813 convbuf = __wcsconv(wcp, prec);
814 if (convbuf == NULL) {
815 ret = -1;
816 goto error;
817 }
818 cp = convbuf;
819 }
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700820 } else if ((cp = GETARG(char*)) == NULL) {
821 cp = const_cast<char*>("(null)");
822 }
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700823 if (prec >= 0) {
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700824 size = strnlen(cp, prec);
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700825 } else {
826 size_t len;
Elliott Hughes05493712014-04-17 17:30:03 -0700827
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700828 if ((len = strlen(cp)) > INT_MAX) goto overflow;
829 size = (int)len;
830 }
831 sign = '\0';
832 break;
833 case 'U':
834 flags |= LONGINT;
835 /*FALLTHROUGH*/
836 case 'u':
837 _umax = UARG();
838 base = DEC;
839 goto nosign;
840 case 'X':
841 xdigs = xdigs_upper;
842 goto hex;
843 case 'x':
844 xdigs = xdigs_lower;
845 hex:
846 _umax = UARG();
847 base = HEX;
848 /* leading 0x/X only if non-zero */
849 if (flags & ALT && _umax != 0) ox[1] = ch;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700851 /* unsigned conversions */
852 nosign:
853 sign = '\0';
854 /*
855 * ``... diouXx conversions ... if a precision is
856 * specified, the 0 flag will be ignored.''
857 * -- ANSI X3J11
858 */
859 number:
860 if ((dprec = prec) >= 0) flags &= ~ZEROPAD;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700862 /*
863 * ``The result of converting a zero value with an
864 * explicit precision of zero is no characters.''
865 * -- ANSI X3J11
866 */
867 cp = buf + BUF;
868 if (_umax != 0 || prec != 0) {
869 /*
870 * Unsigned mod is hard, and unsigned mod
871 * by a constant is easier than that by
872 * a variable; hence this switch.
873 */
874 switch (base) {
875 case OCT:
876 do {
877 *--cp = to_char(_umax & 7);
878 _umax >>= 3;
879 } while (_umax);
880 /* handle octal leading 0 */
881 if (flags & ALT && *cp != '0') *--cp = '0';
882 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800883
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700884 case DEC:
885 /* many numbers are 1 digit */
886 while (_umax >= 10) {
887 *--cp = to_char(_umax % 10);
888 _umax /= 10;
889 }
890 *--cp = to_char(_umax);
891 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800892
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700893 case HEX:
894 do {
895 *--cp = xdigs[_umax & 15];
896 _umax >>= 4;
897 } while (_umax);
898 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800899
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700900 default:
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700901 abort();
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700902 }
903 }
904 size = buf + BUF - cp;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -0700905 if (size > BUF) abort(); /* should never happen */
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700906 break;
907 default: /* "%?" prints ?, unless ? is NUL */
908 if (ch == '\0') goto done;
909 /* pretend it was %c with argument ch */
910 cp = buf;
911 *cp = ch;
912 size = 1;
913 sign = '\0';
914 break;
915 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800916
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700917 /*
918 * All reasonable formats wind up here. At this point, `cp'
919 * points to a string which (if not flags&LADJUST) should be
920 * padded out to `width' places. If flags&ZEROPAD, it should
921 * first be prefixed by any sign or other prefix; otherwise,
922 * it should be blank padded before the prefix is emitted.
923 * After any left-hand padding and prefixing, emit zeroes
924 * required by a decimal %[diouxX] precision, then print the
925 * string proper, then emit zeroes required by any leftover
926 * floating precision; finally, if LADJUST, pad with blanks.
927 *
928 * Compute actual size, so we know how much to pad.
929 * size excludes decimal prec; realsz includes it.
930 */
931 realsz = dprec > size ? dprec : size;
932 if (sign) realsz++;
933 if (ox[1]) realsz += 2;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800934
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700935 /* right-adjusting blank padding */
936 if ((flags & (LADJUST | ZEROPAD)) == 0) PAD(width - realsz, blanks);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800937
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700938 /* prefix */
939 if (sign) PRINT(&sign, 1);
940 if (ox[1]) { /* ox[1] is either x, X, or \0 */
941 ox[0] = '0';
942 PRINT(ox, 2);
943 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700945 /* right-adjusting zero padding */
946 if ((flags & (LADJUST | ZEROPAD)) == ZEROPAD) PAD(width - realsz, zeroes);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800947
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700948 /* leading zeroes from decimal precision */
949 PAD(dprec - size, zeroes);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800950
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700951 /* the string or number proper */
952 if ((flags & FPT) == 0) {
953 PRINT(cp, size);
954 } else { /* glue together f_p fragments */
955 if (decimal_point == NULL) decimal_point = nl_langinfo(RADIXCHAR);
956 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
957 if (expt <= 0) {
958 PRINT(zeroes, 1);
959 if (prec || flags & ALT) PRINT(decimal_point, 1);
960 PAD(-expt, zeroes);
961 /* already handled initial 0's */
962 prec += expt;
963 } else {
964 PRINTANDPAD(cp, dtoaend, lead, zeroes);
965 cp += lead;
966 if (prec || flags & ALT) PRINT(decimal_point, 1);
967 }
968 PRINTANDPAD(cp, dtoaend, prec, zeroes);
969 } else { /* %[eE] or sufficiently long %[gG] */
970 if (prec > 1 || flags & ALT) {
971 buf[0] = *cp++;
972 buf[1] = *decimal_point;
973 PRINT(buf, 2);
974 PRINT(cp, ndig - 1);
975 PAD(prec - ndig, zeroes);
976 } else { /* XeYYY */
977 PRINT(cp, 1);
978 }
979 PRINT(expstr, expsize);
980 }
981 }
982 /* left-adjusting padding (always blank) */
983 if (flags & LADJUST) PAD(width - realsz, blanks);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700985 /* finally, adjust ret */
986 if (width < realsz) width = realsz;
987 if (width > INT_MAX - ret) goto overflow;
988 ret += width;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800989
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700990 FLUSH(); /* copy out the I/O vectors */
991 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800992done:
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700993 FLUSH();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800994error:
Elliott Hughesc8f2c522017-10-31 13:07:51 -0700995 va_end(orgap);
996 if (__sferror(fp)) ret = -1;
997 goto finish;
Elliott Hughes05493712014-04-17 17:30:03 -0700998
999overflow:
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001000 errno = ENOMEM;
1001 ret = -1;
Elliott Hughes05493712014-04-17 17:30:03 -07001002
1003finish:
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001004 free(convbuf);
1005 if (dtoaresult) __freedtoa(dtoaresult);
1006 if (argtable != NULL && argtable != statargtable) {
1007 munmap(argtable, argtablesiz);
1008 argtable = NULL;
1009 }
1010 return (ret);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001011}
1012
1013/*
1014 * Type ids for argument type table.
1015 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001016#define T_UNUSED 0
1017#define T_SHORT 1
1018#define T_U_SHORT 2
1019#define TP_SHORT 3
1020#define T_INT 4
1021#define T_U_INT 5
1022#define TP_INT 6
1023#define T_LONG 7
1024#define T_U_LONG 8
1025#define TP_LONG 9
1026#define T_LLONG 10
1027#define T_U_LLONG 11
1028#define TP_LLONG 12
1029#define T_DOUBLE 13
1030#define T_LONG_DOUBLE 14
1031#define TP_CHAR 15
1032#define TP_VOID 16
1033#define T_PTRINT 17
1034#define TP_PTRINT 18
1035#define T_SIZEINT 19
1036#define T_SSIZEINT 20
1037#define TP_SSIZEINT 21
1038#define T_MAXINT 22
1039#define T_MAXUINT 23
1040#define TP_MAXINT 24
1041#define T_CHAR 25
1042#define T_U_CHAR 26
1043#define T_WINT 27
1044#define TP_WCHAR 28
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001045
1046/*
1047 * Find all arguments when a positional parameter is encountered. Returns a
1048 * table, indexed by argument number, of pointers to each arguments. The
1049 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1050 * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1051 * used since we are attempting to make snprintf thread safe, and alloca is
1052 * problematic since we have nested functions..)
1053 */
Elliott Hughes5305a4d2017-11-03 14:00:37 -07001054static int __find_arguments(const CHAR_TYPE* fmt0, va_list ap, union arg** argtable,
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001055 size_t* argtablesiz) {
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001056 int ch; /* character from fmt */
1057 int n, n2; /* handy integer (short term usage) */
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001058 int flags; /* flags as above */
1059 unsigned char* typetable; /* table of types */
1060 unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1061 int tablesize; /* current size of type table */
1062 int tablemax; /* largest used index in table */
1063 int nextarg; /* 1-based argument index */
1064 int ret = 0; /* return value */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001065
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001066 /*
1067 * Add an argument type to the table, expanding if necessary.
1068 */
1069#define ADDTYPE(type) \
1070 ((nextarg >= tablesize) ? __grow_type_table(&typetable, &tablesize) : 0, \
1071 (nextarg > tablemax) ? tablemax = nextarg : 0, typetable[nextarg++] = type)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001072
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001073#define ADDSARG() \
1074 ((flags & MAXINT) \
1075 ? ADDTYPE(T_MAXINT) \
1076 : ((flags & PTRINT) ? ADDTYPE(T_PTRINT) \
1077 : ((flags & SIZEINT) \
1078 ? ADDTYPE(T_SSIZEINT) \
1079 : ((flags & LLONGINT) \
1080 ? ADDTYPE(T_LLONG) \
1081 : ((flags & LONGINT) \
1082 ? ADDTYPE(T_LONG) \
1083 : ((flags & SHORTINT) \
1084 ? ADDTYPE(T_SHORT) \
1085 : ((flags & CHARINT) ? ADDTYPE(T_CHAR) \
1086 : ADDTYPE(T_INT))))))))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001087
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001088#define ADDUARG() \
1089 ((flags & MAXINT) \
1090 ? ADDTYPE(T_MAXUINT) \
1091 : ((flags & PTRINT) \
1092 ? ADDTYPE(T_PTRINT) \
1093 : ((flags & SIZEINT) \
1094 ? ADDTYPE(T_SIZEINT) \
1095 : ((flags & LLONGINT) \
1096 ? ADDTYPE(T_U_LLONG) \
1097 : ((flags & LONGINT) \
1098 ? ADDTYPE(T_U_LONG) \
1099 : ((flags & SHORTINT) \
1100 ? ADDTYPE(T_U_SHORT) \
1101 : ((flags & CHARINT) ? ADDTYPE(T_U_CHAR) \
1102 : ADDTYPE(T_U_INT))))))))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001104 /*
1105 * Add * arguments to the type array.
1106 */
1107#define ADDASTER() \
1108 n2 = 0; \
1109 cp = fmt; \
1110 while (is_digit(*cp)) { \
1111 APPEND_DIGIT(n2, *cp); \
1112 cp++; \
1113 } \
1114 if (*cp == '$') { \
1115 int hold = nextarg; \
1116 nextarg = n2; \
1117 ADDTYPE(T_INT); \
1118 nextarg = hold; \
1119 fmt = ++cp; \
1120 } else { \
1121 ADDTYPE(T_INT); \
1122 }
Elliott Hughes5305a4d2017-11-03 14:00:37 -07001123 CHAR_TYPE* fmt = const_cast<CHAR_TYPE*>(fmt0);
1124 CHAR_TYPE* cp;
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001125 typetable = stattypetable;
1126 tablesize = STATIC_ARG_TBL_SIZE;
1127 tablemax = 0;
1128 nextarg = 1;
1129 memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001130
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001131 /*
1132 * Scan the format for conversions (`%' character).
1133 */
1134 for (;;) {
Elliott Hughes5305a4d2017-11-03 14:00:37 -07001135 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) continue;
1136 if (ch == '\0') goto done;
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001137 fmt++; /* skip over '%' */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001138
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001139 flags = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001140
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001141 rflag:
1142 ch = *fmt++;
1143 reswitch:
1144 switch (ch) {
1145 case ' ':
1146 case '#':
1147 case '\'':
1148 goto rflag;
1149 case '*':
1150 ADDASTER();
1151 goto rflag;
1152 case '-':
1153 case '+':
1154 goto rflag;
1155 case '.':
1156 if ((ch = *fmt++) == '*') {
1157 ADDASTER();
1158 goto rflag;
1159 }
1160 while (is_digit(ch)) {
1161 ch = *fmt++;
1162 }
1163 goto reswitch;
1164 case '0':
1165 goto rflag;
1166 case '1':
1167 case '2':
1168 case '3':
1169 case '4':
1170 case '5':
1171 case '6':
1172 case '7':
1173 case '8':
1174 case '9':
1175 n = 0;
1176 do {
1177 APPEND_DIGIT(n, ch);
1178 ch = *fmt++;
1179 } while (is_digit(ch));
1180 if (ch == '$') {
1181 nextarg = n;
1182 goto rflag;
1183 }
1184 goto reswitch;
1185 case 'L':
1186 flags |= LONGDBL;
1187 goto rflag;
1188 case 'h':
1189 if (*fmt == 'h') {
1190 fmt++;
1191 flags |= CHARINT;
1192 } else {
1193 flags |= SHORTINT;
1194 }
1195 goto rflag;
1196 case 'j':
1197 flags |= MAXINT;
1198 goto rflag;
1199 case 'l':
1200 if (*fmt == 'l') {
1201 fmt++;
1202 flags |= LLONGINT;
1203 } else {
1204 flags |= LONGINT;
1205 }
1206 goto rflag;
1207 case 'q':
1208 flags |= LLONGINT;
1209 goto rflag;
1210 case 't':
1211 flags |= PTRINT;
1212 goto rflag;
1213 case 'z':
1214 flags |= SIZEINT;
1215 goto rflag;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001216 case 'C':
1217 flags |= LONGINT;
1218 /*FALLTHROUGH*/
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001219 case 'c':
1220 if (flags & LONGINT)
1221 ADDTYPE(T_WINT);
1222 else
1223 ADDTYPE(T_INT);
1224 break;
1225 case 'D':
1226 flags |= LONGINT;
1227 /*FALLTHROUGH*/
1228 case 'd':
1229 case 'i':
1230 ADDSARG();
1231 break;
1232 case 'a':
1233 case 'A':
1234 case 'e':
1235 case 'E':
1236 case 'f':
1237 case 'F':
1238 case 'g':
1239 case 'G':
1240 if (flags & LONGDBL)
1241 ADDTYPE(T_LONG_DOUBLE);
1242 else
1243 ADDTYPE(T_DOUBLE);
1244 break;
Elliott Hughese2341d02014-05-02 18:16:32 -07001245#ifndef NO_PRINTF_PERCENT_N
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001246 case 'n':
1247 if (flags & LLONGINT)
1248 ADDTYPE(TP_LLONG);
1249 else if (flags & LONGINT)
1250 ADDTYPE(TP_LONG);
1251 else if (flags & SHORTINT)
1252 ADDTYPE(TP_SHORT);
1253 else if (flags & PTRINT)
1254 ADDTYPE(TP_PTRINT);
1255 else if (flags & SIZEINT)
1256 ADDTYPE(TP_SSIZEINT);
1257 else if (flags & MAXINT)
1258 ADDTYPE(TP_MAXINT);
1259 else
1260 ADDTYPE(TP_INT);
1261 continue; /* no output */
1262#endif /* NO_PRINTF_PERCENT_N */
1263 case 'O':
1264 flags |= LONGINT;
1265 /*FALLTHROUGH*/
1266 case 'o':
1267 ADDUARG();
1268 break;
1269 case 'p':
1270 ADDTYPE(TP_VOID);
1271 break;
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001272 case 'S':
1273 flags |= LONGINT;
1274 /*FALLTHROUGH*/
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001275 case 's':
Elliott Hughes93a1f8b2017-11-07 22:52:29 -08001276 ADDTYPE((flags & LONGINT) ? TP_WCHAR : TP_CHAR);
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001277 break;
1278 case 'U':
1279 flags |= LONGINT;
1280 /*FALLTHROUGH*/
1281 case 'u':
1282 case 'X':
1283 case 'x':
1284 ADDUARG();
1285 break;
1286 default: /* "%?" prints ?, unless ? is NUL */
1287 if (ch == '\0') goto done;
1288 break;
1289 }
1290 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001291done:
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001292 /*
1293 * Build the argument table.
1294 */
1295 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1296 *argtablesiz = sizeof(union arg) * (tablemax + 1);
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001297 *argtable = static_cast<arg*>(mmap(NULL, *argtablesiz,
1298 PROT_WRITE | PROT_READ,
1299 MAP_ANON | MAP_PRIVATE, -1, 0));
1300 if (*argtable == MAP_FAILED) return -1;
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001301 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001302
1303#if 0
1304 /* XXX is this required? */
Alexander Ivchenkoedd7c2e2014-04-01 17:01:39 +04001305 (*argtable)[0].intarg = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001306#endif
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001307 for (n = 1; n <= tablemax; n++) {
1308 switch (typetable[n]) {
1309 case T_UNUSED:
1310 case T_CHAR:
1311 case T_U_CHAR:
1312 case T_SHORT:
1313 case T_U_SHORT:
1314 case T_INT:
1315 (*argtable)[n].intarg = va_arg(ap, int);
1316 break;
1317 case TP_SHORT:
1318 (*argtable)[n].pshortarg = va_arg(ap, short*);
1319 break;
1320 case T_U_INT:
1321 (*argtable)[n].uintarg = va_arg(ap, unsigned int);
1322 break;
1323 case TP_INT:
1324 (*argtable)[n].pintarg = va_arg(ap, int*);
1325 break;
1326 case T_LONG:
1327 (*argtable)[n].longarg = va_arg(ap, long);
1328 break;
1329 case T_U_LONG:
1330 (*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1331 break;
1332 case TP_LONG:
1333 (*argtable)[n].plongarg = va_arg(ap, long*);
1334 break;
1335 case T_LLONG:
1336 (*argtable)[n].longlongarg = va_arg(ap, long long);
1337 break;
1338 case T_U_LLONG:
1339 (*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1340 break;
1341 case TP_LLONG:
1342 (*argtable)[n].plonglongarg = va_arg(ap, long long*);
1343 break;
1344 case T_DOUBLE:
1345 (*argtable)[n].doublearg = va_arg(ap, double);
1346 break;
1347 case T_LONG_DOUBLE:
1348 (*argtable)[n].longdoublearg = va_arg(ap, long double);
1349 break;
1350 case TP_CHAR:
1351 (*argtable)[n].pchararg = va_arg(ap, char*);
1352 break;
1353 case TP_VOID:
1354 (*argtable)[n].pvoidarg = va_arg(ap, void*);
1355 break;
1356 case T_PTRINT:
1357 (*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1358 break;
1359 case TP_PTRINT:
1360 (*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t*);
1361 break;
1362 case T_SIZEINT:
1363 (*argtable)[n].sizearg = va_arg(ap, size_t);
1364 break;
1365 case T_SSIZEINT:
1366 (*argtable)[n].ssizearg = va_arg(ap, ssize_t);
1367 break;
1368 case TP_SSIZEINT:
1369 (*argtable)[n].pssizearg = va_arg(ap, ssize_t*);
1370 break;
1371 case T_MAXINT:
1372 (*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1373 break;
1374 case T_MAXUINT:
1375 (*argtable)[n].uintmaxarg = va_arg(ap, uintmax_t);
1376 break;
1377 case TP_MAXINT:
1378 (*argtable)[n].pintmaxarg = va_arg(ap, intmax_t*);
1379 break;
1380 case T_WINT:
1381 (*argtable)[n].wintarg = va_arg(ap, wint_t);
1382 break;
1383 case TP_WCHAR:
1384 (*argtable)[n].pwchararg = va_arg(ap, wchar_t*);
1385 break;
1386 }
1387 }
1388 goto finish;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001389
Elliott Hughes05493712014-04-17 17:30:03 -07001390overflow:
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001391 errno = ENOMEM;
1392 ret = -1;
Elliott Hughes05493712014-04-17 17:30:03 -07001393
1394finish:
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001395 if (typetable != NULL && typetable != stattypetable) {
1396 munmap(typetable, *argtablesiz);
1397 typetable = NULL;
1398 }
1399 return (ret);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001400}
1401
1402/*
1403 * Increase the size of the type table.
1404 */
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001405static int __grow_type_table(unsigned char** typetable, int* tablesize) {
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001406 unsigned char* old_table = *typetable;
1407 int new_size = *tablesize * 2;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001408
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001409 if (new_size < getpagesize()) new_size = getpagesize();
Elliott Hughes05493712014-04-17 17:30:03 -07001410
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001411 if (*tablesize == STATIC_ARG_TBL_SIZE) {
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001412 *typetable = static_cast<unsigned char*>(mmap(NULL, new_size,
1413 PROT_WRITE | PROT_READ,
1414 MAP_ANON | MAP_PRIVATE, -1, 0));
1415 if (*typetable == MAP_FAILED) return -1;
1416 bcopy(old_table, *typetable, *tablesize);
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001417 } else {
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001418 unsigned char* new_table = static_cast<unsigned char*>(mmap(NULL, new_size,
1419 PROT_WRITE | PROT_READ,
1420 MAP_ANON | MAP_PRIVATE, -1, 0));
1421 if (new_table == MAP_FAILED) return -1;
1422 memmove(new_table, *typetable, *tablesize);
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001423 munmap(*typetable, *tablesize);
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001424 *typetable = new_table;
Elliott Hughesc8f2c522017-10-31 13:07:51 -07001425 }
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001426 memset(*typetable + *tablesize, T_UNUSED, (new_size - *tablesize));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001427
Elliott Hughes2f9c8ce2017-11-01 13:54:47 -07001428 *tablesize = new_size;
1429 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001430}