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