1 /* $OpenBSD: vfprintf.c,v 1.53 2008/10/21 17:51:17 martynas 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 } else { 580 fparg.dbl = GETARG(double); 581 dtoaresult = cp = 582 __hdtoa(fparg.dbl, xdigs, prec, 583 &expt, &signflag, &dtoaend); 584 } 585 if (prec < 0) 586 prec = dtoaend - cp; 587 if (expt == INT_MAX) 588 ox[1] = '\0'; 589 goto fp_common; 590 case 'e': 591 case 'E': 592 expchar = ch; 593 if (prec < 0) /* account for digit before decpt */ 594 prec = DEFPREC + 1; 595 else 596 prec++; 597 goto fp_begin; 598 case 'f': 599 case 'F': 600 expchar = '\0'; 601 goto fp_begin; 602 case 'g': 603 case 'G': 604 expchar = ch - ('g' - 'e'); 605 if (prec == 0) 606 prec = 1; 607 fp_begin: 608 if (prec < 0) 609 prec = DEFPREC; 610 if (dtoaresult) 611 __freedtoa(dtoaresult); 612 if (flags & LONGDBL) { 613 fparg.ldbl = GETARG(long double); 614 dtoaresult = cp = 615 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 616 &expt, &signflag, &dtoaend); 617 } else { 618 fparg.dbl = GETARG(double); 619 dtoaresult = cp = 620 __dtoa(fparg.dbl, expchar ? 2 : 3, prec, 621 &expt, &signflag, &dtoaend); 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 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 va_end(orgap); 918 if (__sferror(fp)) 919 ret = -1; 920 goto finish; 921 922 overflow: 923 errno = ENOMEM; 924 ret = -1; 925 926 finish: 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 = 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 goto rflag; 1072 case '*': 1073 ADDASTER(); 1074 goto rflag; 1075 case '-': 1076 case '+': 1077 goto rflag; 1078 case '.': 1079 if ((ch = *fmt++) == '*') { 1080 ADDASTER(); 1081 goto rflag; 1082 } 1083 while (is_digit(ch)) { 1084 ch = *fmt++; 1085 } 1086 goto reswitch; 1087 case '0': 1088 goto rflag; 1089 case '1': case '2': case '3': case '4': 1090 case '5': case '6': case '7': case '8': case '9': 1091 n = 0; 1092 do { 1093 APPEND_DIGIT(n ,ch); 1094 ch = *fmt++; 1095 } while (is_digit(ch)); 1096 if (ch == '$') { 1097 nextarg = n; 1098 goto rflag; 1099 } 1100 goto reswitch; 1101 #ifdef FLOATING_POINT 1102 case 'L': 1103 flags |= LONGDBL; 1104 goto rflag; 1105 #endif 1106 case 'h': 1107 if (*fmt == 'h') { 1108 fmt++; 1109 flags |= CHARINT; 1110 } else { 1111 flags |= SHORTINT; 1112 } 1113 goto rflag; 1114 case 'l': 1115 if (*fmt == 'l') { 1116 fmt++; 1117 flags |= LLONGINT; 1118 } else { 1119 flags |= LONGINT; 1120 } 1121 goto rflag; 1122 case 'q': 1123 flags |= LLONGINT; 1124 goto rflag; 1125 case 't': 1126 flags |= PTRINT; 1127 goto rflag; 1128 case 'z': 1129 flags |= SIZEINT; 1130 goto rflag; 1131 case 'c': 1132 ADDTYPE(T_INT); 1133 break; 1134 case 'D': 1135 flags |= LONGINT; 1136 /*FALLTHROUGH*/ 1137 case 'd': 1138 case 'i': 1139 ADDSARG(); 1140 break; 1141 #ifdef FLOATING_POINT 1142 case 'a': 1143 case 'A': 1144 case 'e': 1145 case 'E': 1146 case 'f': 1147 case 'F': 1148 case 'g': 1149 case 'G': 1150 if (flags & LONGDBL) 1151 ADDTYPE(T_LONG_DOUBLE); 1152 else 1153 ADDTYPE(T_DOUBLE); 1154 break; 1155 #endif /* FLOATING_POINT */ 1156 case 'n': 1157 if (flags & LLONGINT) 1158 ADDTYPE(TP_LLONG); 1159 else if (flags & LONGINT) 1160 ADDTYPE(TP_LONG); 1161 else if (flags & SHORTINT) 1162 ADDTYPE(TP_SHORT); 1163 else if (flags & PTRINT) 1164 ADDTYPE(TP_PTRINT); 1165 else if (flags & SIZEINT) 1166 ADDTYPE(TP_SSIZEINT); 1167 else if (flags & MAXINT) 1168 ADDTYPE(TP_MAXINT); 1169 else 1170 ADDTYPE(TP_INT); 1171 continue; /* no output */ 1172 case 'O': 1173 flags |= LONGINT; 1174 /*FALLTHROUGH*/ 1175 case 'o': 1176 ADDUARG(); 1177 break; 1178 case 'p': 1179 ADDTYPE(TP_VOID); 1180 break; 1181 case 's': 1182 ADDTYPE(TP_CHAR); 1183 break; 1184 case 'U': 1185 flags |= LONGINT; 1186 /*FALLTHROUGH*/ 1187 case 'u': 1188 case 'X': 1189 case 'x': 1190 ADDUARG(); 1191 break; 1192 default: /* "%?" prints ?, unless ? is NUL */ 1193 if (ch == '\0') 1194 goto done; 1195 break; 1196 } 1197 } 1198 done: 1199 /* 1200 * Build the argument table. 1201 */ 1202 if (tablemax >= STATIC_ARG_TBL_SIZE) { 1203 *argtablesiz = sizeof(union arg) * (tablemax + 1); 1204 *argtable = mmap(NULL, *argtablesiz, 1205 PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0); 1206 if (*argtable == MAP_FAILED) 1207 return (-1); 1208 } 1209 1210 #if 0 1211 /* XXX is this required? */ 1212 (*argtable)[0].intarg = 0; 1213 #endif 1214 for (n = 1; n <= tablemax; n++) { 1215 switch (typetable[n]) { 1216 case T_UNUSED: 1217 case T_CHAR: 1218 case T_U_CHAR: 1219 case T_SHORT: 1220 case T_U_SHORT: 1221 case T_INT: 1222 (*argtable)[n].intarg = va_arg(ap, int); 1223 break; 1224 case TP_SHORT: 1225 (*argtable)[n].pshortarg = va_arg(ap, short *); 1226 break; 1227 case T_U_INT: 1228 (*argtable)[n].uintarg = va_arg(ap, unsigned int); 1229 break; 1230 case TP_INT: 1231 (*argtable)[n].pintarg = va_arg(ap, int *); 1232 break; 1233 case T_LONG: 1234 (*argtable)[n].longarg = va_arg(ap, long); 1235 break; 1236 case T_U_LONG: 1237 (*argtable)[n].ulongarg = va_arg(ap, unsigned long); 1238 break; 1239 case TP_LONG: 1240 (*argtable)[n].plongarg = va_arg(ap, long *); 1241 break; 1242 case T_LLONG: 1243 (*argtable)[n].longlongarg = va_arg(ap, long long); 1244 break; 1245 case T_U_LLONG: 1246 (*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long); 1247 break; 1248 case TP_LLONG: 1249 (*argtable)[n].plonglongarg = va_arg(ap, long long *); 1250 break; 1251 #ifdef FLOATING_POINT 1252 case T_DOUBLE: 1253 (*argtable)[n].doublearg = va_arg(ap, double); 1254 break; 1255 case T_LONG_DOUBLE: 1256 (*argtable)[n].longdoublearg = va_arg(ap, long double); 1257 break; 1258 #endif 1259 case TP_CHAR: 1260 (*argtable)[n].pchararg = va_arg(ap, char *); 1261 break; 1262 case TP_VOID: 1263 (*argtable)[n].pvoidarg = va_arg(ap, void *); 1264 break; 1265 case T_PTRINT: 1266 (*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t); 1267 break; 1268 case TP_PTRINT: 1269 (*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *); 1270 break; 1271 case T_SIZEINT: 1272 (*argtable)[n].sizearg = va_arg(ap, size_t); 1273 break; 1274 case T_SSIZEINT: 1275 (*argtable)[n].ssizearg = va_arg(ap, ssize_t); 1276 break; 1277 case TP_SSIZEINT: 1278 (*argtable)[n].pssizearg = va_arg(ap, ssize_t *); 1279 break; 1280 case TP_MAXINT: 1281 (*argtable)[n].intmaxarg = va_arg(ap, intmax_t); 1282 break; 1283 } 1284 } 1285 goto finish; 1286 1287 overflow: 1288 errno = ENOMEM; 1289 ret = -1; 1290 1291 finish: 1292 if (typetable != NULL && typetable != stattypetable) { 1293 munmap(typetable, *argtablesiz); 1294 typetable = NULL; 1295 } 1296 return (ret); 1297 } 1298 1299 /* 1300 * Increase the size of the type table. 1301 */ 1302 static int 1303 __grow_type_table(unsigned char **typetable, int *tablesize) 1304 { 1305 unsigned char *oldtable = *typetable; 1306 int newsize = *tablesize * 2; 1307 1308 if (newsize < getpagesize()) 1309 newsize = getpagesize(); 1310 1311 if (*tablesize == STATIC_ARG_TBL_SIZE) { 1312 *typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ, 1313 MAP_ANON|MAP_PRIVATE, -1, 0); 1314 if (*typetable == MAP_FAILED) 1315 return (-1); 1316 bcopy(oldtable, *typetable, *tablesize); 1317 } else { 1318 unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ, 1319 MAP_ANON|MAP_PRIVATE, -1, 0); 1320 if (new == MAP_FAILED) 1321 return (-1); 1322 memmove(new, *typetable, *tablesize); 1323 munmap(*typetable, *tablesize); 1324 *typetable = new; 1325 } 1326 memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize)); 1327 1328 *tablesize = newsize; 1329 return (0); 1330 } 1331 1332 1333 #ifdef FLOATING_POINT 1334 static int 1335 exponent(char *p0, int exp, int fmtch) 1336 { 1337 char *p, *t; 1338 char expbuf[MAXEXPDIG]; 1339 1340 p = p0; 1341 *p++ = fmtch; 1342 if (exp < 0) { 1343 exp = -exp; 1344 *p++ = '-'; 1345 } else 1346 *p++ = '+'; 1347 t = expbuf + MAXEXPDIG; 1348 if (exp > 9) { 1349 do { 1350 *--t = to_char(exp % 10); 1351 } while ((exp /= 10) > 9); 1352 *--t = to_char(exp); 1353 for (; t < expbuf + MAXEXPDIG; *p++ = *t++) 1354 /* nothing */; 1355 } else { 1356 /* 1357 * Exponents for decimal floating point conversions 1358 * (%[eEgG]) must be at least two characters long, 1359 * whereas exponents for hexadecimal conversions can 1360 * be only one character long. 1361 */ 1362 if (fmtch == 'e' || fmtch == 'E') 1363 *p++ = '0'; 1364 *p++ = to_char(exp); 1365 } 1366 return (p - p0); 1367 } 1368 #endif /* FLOATING_POINT */ 1369