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