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