1 /*- 2 * Copyright (c) 1990, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Chris Torek. 7 * 8 * Copyright (c) 2011 The FreeBSD Foundation 9 * All rights reserved. 10 * Portions of this software were developed by David Chisnall 11 * under sponsorship from the FreeBSD Foundation. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. Neither the name of the University nor the names of its contributors 22 * may be used to endorse or promote products derived from this software 23 * without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 */ 37 38 #if defined(LIBC_SCCS) && !defined(lint) 39 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93"; 40 #endif /* LIBC_SCCS and not lint */ 41 #include <sys/cdefs.h> 42 __FBSDID("$FreeBSD$"); 43 44 /* 45 * Actual printf innards. 46 * 47 * This code is large and complicated... 48 */ 49 50 #include "namespace.h" 51 #include <sys/types.h> 52 53 #include <ctype.h> 54 #include <errno.h> 55 #include <limits.h> 56 #include <locale.h> 57 #include <stddef.h> 58 #include <stdint.h> 59 #include <stdio.h> 60 #include <stdlib.h> 61 #include <string.h> 62 #include <wchar.h> 63 #include <printf.h> 64 65 #include <stdarg.h> 66 #include "xlocale_private.h" 67 #include "un-namespace.h" 68 69 #include "libc_private.h" 70 #include "local.h" 71 #include "fvwrite.h" 72 #include "printflocal.h" 73 74 static int __sprint(FILE *, struct __suio *, locale_t); 75 static int __sbprintf(FILE *, locale_t, const char *, va_list) __printflike(3, 0) 76 __noinline; 77 static char *__wcsconv(wchar_t *, int); 78 79 #define CHAR char 80 #include "printfcommon.h" 81 82 struct grouping_state { 83 char *thousands_sep; /* locale-specific thousands separator */ 84 int thousep_len; /* length of thousands_sep */ 85 const char *grouping; /* locale-specific numeric grouping rules */ 86 int lead; /* sig figs before decimal or group sep */ 87 int nseps; /* number of group separators with ' */ 88 int nrepeats; /* number of repeats of the last group */ 89 }; 90 91 /* 92 * Initialize the thousands' grouping state in preparation to print a 93 * number with ndigits digits. This routine returns the total number 94 * of bytes that will be needed. 95 */ 96 static int 97 grouping_init(struct grouping_state *gs, int ndigits, locale_t loc) 98 { 99 struct lconv *locale; 100 101 locale = localeconv_l(loc); 102 gs->grouping = locale->grouping; 103 gs->thousands_sep = locale->thousands_sep; 104 gs->thousep_len = strlen(gs->thousands_sep); 105 106 gs->nseps = gs->nrepeats = 0; 107 gs->lead = ndigits; 108 while (*gs->grouping != CHAR_MAX) { 109 if (gs->lead <= *gs->grouping) 110 break; 111 gs->lead -= *gs->grouping; 112 if (*(gs->grouping+1)) { 113 gs->nseps++; 114 gs->grouping++; 115 } else 116 gs->nrepeats++; 117 } 118 return ((gs->nseps + gs->nrepeats) * gs->thousep_len); 119 } 120 121 /* 122 * Print a number with thousands' separators. 123 */ 124 static int 125 grouping_print(struct grouping_state *gs, struct io_state *iop, 126 const CHAR *cp, const CHAR *ep, locale_t locale) 127 { 128 const CHAR *cp0 = cp; 129 130 if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale)) 131 return (-1); 132 cp += gs->lead; 133 while (gs->nseps > 0 || gs->nrepeats > 0) { 134 if (gs->nrepeats > 0) 135 gs->nrepeats--; 136 else { 137 gs->grouping--; 138 gs->nseps--; 139 } 140 if (io_print(iop, gs->thousands_sep, gs->thousep_len, locale)) 141 return (-1); 142 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale)) 143 return (-1); 144 cp += *gs->grouping; 145 } 146 if (cp > ep) 147 cp = ep; 148 return (cp - cp0); 149 } 150 151 /* 152 * Flush out all the vectors defined by the given uio, 153 * then reset it so that it can be reused. 154 */ 155 static int 156 __sprint(FILE *fp, struct __suio *uio, locale_t locale) 157 { 158 int err; 159 160 if (uio->uio_resid == 0) { 161 uio->uio_iovcnt = 0; 162 return (0); 163 } 164 err = __sfvwrite(fp, uio); 165 uio->uio_resid = 0; 166 uio->uio_iovcnt = 0; 167 return (err); 168 } 169 170 /* 171 * Helper function for `fprintf to unbuffered unix file': creates a 172 * temporary buffer. We only work on write-only files; this avoids 173 * worries about ungetc buffers and so forth. 174 */ 175 static int 176 __sbprintf(FILE *fp, locale_t locale, const char *fmt, va_list ap) 177 { 178 int ret; 179 FILE fake = FAKE_FILE; 180 unsigned char buf[BUFSIZ]; 181 182 /* XXX This is probably not needed. */ 183 if (prepwrite(fp) != 0) 184 return (EOF); 185 186 /* copy the important variables */ 187 fake._flags = fp->_flags & ~__SNBF; 188 fake._file = fp->_file; 189 fake._cookie = fp->_cookie; 190 fake._write = fp->_write; 191 fake._orientation = fp->_orientation; 192 fake._mbstate = fp->_mbstate; 193 194 /* set up the buffer */ 195 fake._bf._base = fake._p = buf; 196 fake._bf._size = fake._w = sizeof(buf); 197 fake._lbfsize = 0; /* not actually used, but Just In Case */ 198 199 /* do the work, then copy any error status */ 200 ret = __vfprintf(&fake, locale, fmt, ap); 201 if (ret >= 0 && __fflush(&fake)) 202 ret = EOF; 203 if (fake._flags & __SERR) 204 fp->_flags |= __SERR; 205 return (ret); 206 } 207 208 /* 209 * Convert a wide character string argument for the %ls format to a multibyte 210 * string representation. If not -1, prec specifies the maximum number of 211 * bytes to output, and also means that we can't assume that the wide char. 212 * string ends is null-terminated. 213 */ 214 static char * 215 __wcsconv(wchar_t *wcsarg, int prec) 216 { 217 static const mbstate_t initial; 218 mbstate_t mbs; 219 char buf[MB_LEN_MAX]; 220 wchar_t *p; 221 char *convbuf; 222 size_t clen, nbytes; 223 224 /* Allocate space for the maximum number of bytes we could output. */ 225 if (prec < 0) { 226 p = wcsarg; 227 mbs = initial; 228 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs); 229 if (nbytes == (size_t)-1) 230 return (NULL); 231 } else { 232 /* 233 * Optimisation: if the output precision is small enough, 234 * just allocate enough memory for the maximum instead of 235 * scanning the string. 236 */ 237 if (prec < 128) 238 nbytes = prec; 239 else { 240 nbytes = 0; 241 p = wcsarg; 242 mbs = initial; 243 for (;;) { 244 clen = wcrtomb(buf, *p++, &mbs); 245 if (clen == 0 || clen == (size_t)-1 || 246 nbytes + clen > prec) 247 break; 248 nbytes += clen; 249 } 250 } 251 } 252 if ((convbuf = malloc(nbytes + 1)) == NULL) 253 return (NULL); 254 255 /* Fill the output buffer. */ 256 p = wcsarg; 257 mbs = initial; 258 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p, 259 nbytes, &mbs)) == (size_t)-1) { 260 free(convbuf); 261 return (NULL); 262 } 263 convbuf[nbytes] = '\0'; 264 return (convbuf); 265 } 266 267 /* 268 * MT-safe version 269 */ 270 int 271 vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0, 272 va_list ap) 273 { 274 int ret; 275 FIX_LOCALE(locale); 276 277 FLOCKFILE(fp); 278 /* optimise fprintf(stderr) (and other unbuffered Unix files) */ 279 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) && 280 fp->_file >= 0) 281 ret = __sbprintf(fp, locale, fmt0, ap); 282 else 283 ret = __vfprintf(fp, locale, fmt0, ap); 284 FUNLOCKFILE(fp); 285 return (ret); 286 } 287 int 288 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap) 289 { 290 return vfprintf_l(fp, __get_locale(), fmt0, ap); 291 } 292 293 /* 294 * The size of the buffer we use as scratch space for integer 295 * conversions, among other things. We need enough space to 296 * write a uintmax_t in octal (plus one byte). 297 */ 298 #if UINTMAX_MAX <= UINT64_MAX 299 #define BUF 32 300 #else 301 #error "BUF must be large enough to format a uintmax_t" 302 #endif 303 304 /* 305 * Non-MT-safe version 306 */ 307 int 308 __vfprintf(FILE *fp, locale_t locale, const char *fmt0, va_list ap) 309 { 310 char *fmt; /* format string */ 311 int ch; /* character from fmt */ 312 int n, n2; /* handy integer (short term usage) */ 313 char *cp; /* handy char pointer (short term usage) */ 314 int flags; /* flags as above */ 315 int ret; /* return value accumulator */ 316 int width; /* width from format (%8d), or 0 */ 317 int prec; /* precision from format; <0 for N/A */ 318 char sign; /* sign prefix (' ', '+', '-', or \0) */ 319 struct grouping_state gs; /* thousands' grouping info */ 320 321 #ifndef NO_FLOATING_POINT 322 /* 323 * We can decompose the printed representation of floating 324 * point numbers into several parts, some of which may be empty: 325 * 326 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ 327 * A B ---C--- D E F 328 * 329 * A: 'sign' holds this value if present; '\0' otherwise 330 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal 331 * C: cp points to the string MMMNNN. Leading and trailing 332 * zeros are not in the string and must be added. 333 * D: expchar holds this character; '\0' if no exponent, e.g. %f 334 * F: at least two digits for decimal, at least one digit for hex 335 */ 336 char *decimal_point; /* locale specific decimal point */ 337 int decpt_len; /* length of decimal_point */ 338 int signflag; /* true if float is negative */ 339 union { /* floating point arguments %[aAeEfFgG] */ 340 double dbl; 341 long double ldbl; 342 } fparg; 343 int expt; /* integer value of exponent */ 344 char expchar; /* exponent character: [eEpP\0] */ 345 char *dtoaend; /* pointer to end of converted digits */ 346 int expsize; /* character count for expstr */ 347 int ndig; /* actual number of digits returned by dtoa */ 348 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */ 349 char *dtoaresult; /* buffer allocated by dtoa */ 350 #endif 351 u_long ulval; /* integer arguments %[diouxX] */ 352 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */ 353 int base; /* base for [diouxX] conversion */ 354 int dprec; /* a copy of prec if [diouxX], 0 otherwise */ 355 int realsz; /* field size expanded by dprec, sign, etc */ 356 int size; /* size of converted field or string */ 357 int prsize; /* max size of printed field */ 358 const char *xdigs; /* digits for %[xX] conversion */ 359 struct io_state io; /* I/O buffering state */ 360 char buf[BUF]; /* buffer with space for digits of uintmax_t */ 361 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */ 362 union arg *argtable; /* args, built due to positional arg */ 363 union arg statargtable [STATIC_ARG_TBL_SIZE]; 364 int nextarg; /* 1-based argument index */ 365 va_list orgap; /* original argument pointer */ 366 char *convbuf; /* wide to multibyte conversion result */ 367 int savserr; 368 369 static const char xdigs_lower[16] = "0123456789abcdef"; 370 static const char xdigs_upper[16] = "0123456789ABCDEF"; 371 372 /* BEWARE, these `goto error' on error. */ 373 #define PRINT(ptr, len) { \ 374 if (io_print(&io, (ptr), (len), locale)) \ 375 goto error; \ 376 } 377 #define PAD(howmany, with) { \ 378 if (io_pad(&io, (howmany), (with), locale)) \ 379 goto error; \ 380 } 381 #define PRINTANDPAD(p, ep, len, with) { \ 382 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \ 383 goto error; \ 384 } 385 #define FLUSH() { \ 386 if (io_flush(&io, locale)) \ 387 goto error; \ 388 } 389 390 /* 391 * Get the argument indexed by nextarg. If the argument table is 392 * built, use it to get the argument. If its not, get the next 393 * argument (and arguments must be gotten sequentially). 394 */ 395 #define GETARG(type) \ 396 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \ 397 (nextarg++, va_arg(ap, type))) 398 399 /* 400 * To extend shorts properly, we need both signed and unsigned 401 * argument extraction methods. 402 */ 403 #define SARG() \ 404 (flags&LONGINT ? GETARG(long) : \ 405 flags&SHORTINT ? (long)(short)GETARG(int) : \ 406 flags&CHARINT ? (long)(signed char)GETARG(int) : \ 407 (long)GETARG(int)) 408 #define UARG() \ 409 (flags&LONGINT ? GETARG(u_long) : \ 410 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \ 411 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \ 412 (u_long)GETARG(u_int)) 413 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT) 414 #define SJARG() \ 415 (flags&INTMAXT ? GETARG(intmax_t) : \ 416 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \ 417 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \ 418 (intmax_t)GETARG(long long)) 419 #define UJARG() \ 420 (flags&INTMAXT ? GETARG(uintmax_t) : \ 421 flags&SIZET ? (uintmax_t)GETARG(size_t) : \ 422 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \ 423 (uintmax_t)GETARG(unsigned long long)) 424 425 /* 426 * Get * arguments, including the form *nn$. Preserve the nextarg 427 * that the argument can be gotten once the type is determined. 428 */ 429 #define GETASTER(val) \ 430 n2 = 0; \ 431 cp = fmt; \ 432 while (is_digit(*cp)) { \ 433 n2 = 10 * n2 + to_digit(*cp); \ 434 cp++; \ 435 } \ 436 if (*cp == '$') { \ 437 int hold = nextarg; \ 438 if (argtable == NULL) { \ 439 argtable = statargtable; \ 440 if (__find_arguments (fmt0, orgap, &argtable)) { \ 441 ret = EOF; \ 442 goto error; \ 443 } \ 444 } \ 445 nextarg = n2; \ 446 val = GETARG (int); \ 447 nextarg = hold; \ 448 fmt = ++cp; \ 449 } else { \ 450 val = GETARG (int); \ 451 } 452 453 if (__use_xprintf == 0 && getenv("USE_XPRINTF")) 454 __use_xprintf = 1; 455 if (__use_xprintf > 0) 456 return (__xvprintf(fp, fmt0, ap)); 457 458 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */ 459 if (prepwrite(fp) != 0) { 460 errno = EBADF; 461 return (EOF); 462 } 463 464 savserr = fp->_flags & __SERR; 465 fp->_flags &= ~__SERR; 466 467 convbuf = NULL; 468 fmt = (char *)fmt0; 469 argtable = NULL; 470 nextarg = 1; 471 va_copy(orgap, ap); 472 io_init(&io, fp); 473 ret = 0; 474 #ifndef NO_FLOATING_POINT 475 dtoaresult = NULL; 476 decimal_point = localeconv_l(locale)->decimal_point; 477 /* The overwhelmingly common case is decpt_len == 1. */ 478 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point)); 479 #endif 480 481 /* 482 * Scan the format for conversions (`%' character). 483 */ 484 for (;;) { 485 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 486 /* void */; 487 if ((n = fmt - cp) != 0) { 488 if ((unsigned)ret + n > INT_MAX) { 489 ret = EOF; 490 errno = EOVERFLOW; 491 goto error; 492 } 493 PRINT(cp, n); 494 ret += n; 495 } 496 if (ch == '\0') 497 goto done; 498 fmt++; /* skip over '%' */ 499 500 flags = 0; 501 dprec = 0; 502 width = 0; 503 prec = -1; 504 gs.grouping = NULL; 505 sign = '\0'; 506 ox[1] = '\0'; 507 508 rflag: ch = *fmt++; 509 reswitch: switch (ch) { 510 case ' ': 511 /*- 512 * ``If the space and + flags both appear, the space 513 * flag will be ignored.'' 514 * -- ANSI X3J11 515 */ 516 if (!sign) 517 sign = ' '; 518 goto rflag; 519 case '#': 520 flags |= ALT; 521 goto rflag; 522 case '*': 523 /*- 524 * ``A negative field width argument is taken as a 525 * - flag followed by a positive field width.'' 526 * -- ANSI X3J11 527 * They don't exclude field widths read from args. 528 */ 529 GETASTER (width); 530 if (width >= 0) 531 goto rflag; 532 width = -width; 533 /* FALLTHROUGH */ 534 case '-': 535 flags |= LADJUST; 536 goto rflag; 537 case '+': 538 sign = '+'; 539 goto rflag; 540 case '\'': 541 flags |= GROUPING; 542 goto rflag; 543 case '.': 544 if ((ch = *fmt++) == '*') { 545 GETASTER (prec); 546 goto rflag; 547 } 548 prec = 0; 549 while (is_digit(ch)) { 550 prec = 10 * prec + to_digit(ch); 551 ch = *fmt++; 552 } 553 goto reswitch; 554 case '0': 555 /*- 556 * ``Note that 0 is taken as a flag, not as the 557 * beginning of a field width.'' 558 * -- ANSI X3J11 559 */ 560 flags |= ZEROPAD; 561 goto rflag; 562 case '1': case '2': case '3': case '4': 563 case '5': case '6': case '7': case '8': case '9': 564 n = 0; 565 do { 566 n = 10 * n + to_digit(ch); 567 ch = *fmt++; 568 } while (is_digit(ch)); 569 if (ch == '$') { 570 nextarg = n; 571 if (argtable == NULL) { 572 argtable = statargtable; 573 if (__find_arguments (fmt0, orgap, 574 &argtable)) { 575 ret = EOF; 576 goto error; 577 } 578 } 579 goto rflag; 580 } 581 width = n; 582 goto reswitch; 583 #ifndef NO_FLOATING_POINT 584 case 'L': 585 flags |= LONGDBL; 586 goto rflag; 587 #endif 588 case 'h': 589 if (flags & SHORTINT) { 590 flags &= ~SHORTINT; 591 flags |= CHARINT; 592 } else 593 flags |= SHORTINT; 594 goto rflag; 595 case 'j': 596 flags |= INTMAXT; 597 goto rflag; 598 case 'l': 599 if (flags & LONGINT) { 600 flags &= ~LONGINT; 601 flags |= LLONGINT; 602 } else 603 flags |= LONGINT; 604 goto rflag; 605 case 'q': 606 flags |= LLONGINT; /* not necessarily */ 607 goto rflag; 608 case 't': 609 flags |= PTRDIFFT; 610 goto rflag; 611 case 'z': 612 flags |= SIZET; 613 goto rflag; 614 case 'b': 615 { 616 const char *q; 617 int anybitset, bit; 618 619 ulval = (u_int)GETARG(int); 620 cp = GETARG(char *); 621 622 q = __ultoa(ulval, buf + BUF, *cp++, 0, xdigs_lower); 623 PRINT(q, buf + BUF - q); 624 625 if (ulval == 0) 626 break; 627 628 for (anybitset = 0; *cp;) { 629 bit = *cp++; 630 if (ulval & (1 << (bit - 1))) { 631 PRINT(anybitset ? "," : "<", 1); 632 q = cp; 633 for (; (bit = *cp) > ' '; ++cp) 634 continue; 635 PRINT(q, cp - q); 636 anybitset = 1; 637 } else 638 for (; *cp > ' '; ++cp) 639 continue; 640 } 641 if (anybitset) 642 PRINT(">", 1); 643 } 644 continue; 645 case 'C': 646 flags |= LONGINT; 647 /*FALLTHROUGH*/ 648 case 'c': 649 if (flags & LONGINT) { 650 static const mbstate_t initial; 651 mbstate_t mbs; 652 size_t mbseqlen; 653 654 mbs = initial; 655 mbseqlen = wcrtomb(cp = buf, 656 (wchar_t)GETARG(wint_t), &mbs); 657 if (mbseqlen == (size_t)-1) { 658 fp->_flags |= __SERR; 659 goto error; 660 } 661 size = (int)mbseqlen; 662 } else { 663 *(cp = buf) = GETARG(int); 664 size = 1; 665 } 666 sign = '\0'; 667 break; 668 case 'D': 669 flags |= LONGINT; 670 /*FALLTHROUGH*/ 671 case 'd': 672 case 'i': 673 if (flags & INTMAX_SIZE) { 674 ujval = SJARG(); 675 if ((intmax_t)ujval < 0) { 676 ujval = -ujval; 677 sign = '-'; 678 } 679 } else { 680 ulval = SARG(); 681 if ((long)ulval < 0) { 682 ulval = -ulval; 683 sign = '-'; 684 } 685 } 686 base = 10; 687 goto number; 688 #ifndef NO_FLOATING_POINT 689 case 'a': 690 case 'A': 691 if (ch == 'a') { 692 ox[1] = 'x'; 693 xdigs = xdigs_lower; 694 expchar = 'p'; 695 } else { 696 ox[1] = 'X'; 697 xdigs = xdigs_upper; 698 expchar = 'P'; 699 } 700 if (prec >= 0) 701 prec++; 702 if (dtoaresult != NULL) 703 freedtoa(dtoaresult); 704 if (flags & LONGDBL) { 705 fparg.ldbl = GETARG(long double); 706 dtoaresult = cp = 707 __hldtoa(fparg.ldbl, xdigs, prec, 708 &expt, &signflag, &dtoaend); 709 } else { 710 fparg.dbl = GETARG(double); 711 dtoaresult = cp = 712 __hdtoa(fparg.dbl, xdigs, prec, 713 &expt, &signflag, &dtoaend); 714 } 715 if (prec < 0) 716 prec = dtoaend - cp; 717 if (expt == INT_MAX) 718 ox[1] = '\0'; 719 goto fp_common; 720 case 'e': 721 case 'E': 722 expchar = ch; 723 if (prec < 0) /* account for digit before decpt */ 724 prec = DEFPREC + 1; 725 else 726 prec++; 727 goto fp_begin; 728 case 'f': 729 case 'F': 730 expchar = '\0'; 731 goto fp_begin; 732 case 'g': 733 case 'G': 734 expchar = ch - ('g' - 'e'); 735 if (prec == 0) 736 prec = 1; 737 fp_begin: 738 if (prec < 0) 739 prec = DEFPREC; 740 if (dtoaresult != NULL) 741 freedtoa(dtoaresult); 742 if (flags & LONGDBL) { 743 fparg.ldbl = GETARG(long double); 744 dtoaresult = cp = 745 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 746 &expt, &signflag, &dtoaend); 747 } else { 748 fparg.dbl = GETARG(double); 749 dtoaresult = cp = 750 dtoa(fparg.dbl, expchar ? 2 : 3, prec, 751 &expt, &signflag, &dtoaend); 752 if (expt == 9999) 753 expt = INT_MAX; 754 } 755 fp_common: 756 if (signflag) 757 sign = '-'; 758 if (expt == INT_MAX) { /* inf or nan */ 759 if (*cp == 'N') { 760 cp = (ch >= 'a') ? "nan" : "NAN"; 761 sign = '\0'; 762 } else 763 cp = (ch >= 'a') ? "inf" : "INF"; 764 size = 3; 765 flags &= ~ZEROPAD; 766 break; 767 } 768 flags |= FPT; 769 ndig = dtoaend - cp; 770 if (ch == 'g' || ch == 'G') { 771 if (expt > -4 && expt <= prec) { 772 /* Make %[gG] smell like %[fF] */ 773 expchar = '\0'; 774 if (flags & ALT) 775 prec -= expt; 776 else 777 prec = ndig - expt; 778 if (prec < 0) 779 prec = 0; 780 } else { 781 /* 782 * Make %[gG] smell like %[eE], but 783 * trim trailing zeroes if no # flag. 784 */ 785 if (!(flags & ALT)) 786 prec = ndig; 787 } 788 } 789 if (expchar) { 790 expsize = exponent(expstr, expt - 1, expchar); 791 size = expsize + prec; 792 if (prec > 1 || flags & ALT) 793 size += decpt_len; 794 } else { 795 /* space for digits before decimal point */ 796 if (expt > 0) 797 size = expt; 798 else /* "0" */ 799 size = 1; 800 /* space for decimal pt and following digits */ 801 if (prec || flags & ALT) 802 size += prec + decpt_len; 803 if ((flags & GROUPING) && expt > 0) 804 size += grouping_init(&gs, expt, locale); 805 } 806 break; 807 #endif /* !NO_FLOATING_POINT */ 808 case 'n': 809 /* 810 * Assignment-like behavior is specified if the 811 * value overflows or is otherwise unrepresentable. 812 * C99 says to use `signed char' for %hhn conversions. 813 */ 814 if (flags & LLONGINT) 815 *GETARG(long long *) = ret; 816 else if (flags & SIZET) 817 *GETARG(ssize_t *) = (ssize_t)ret; 818 else if (flags & PTRDIFFT) 819 *GETARG(ptrdiff_t *) = ret; 820 else if (flags & INTMAXT) 821 *GETARG(intmax_t *) = ret; 822 else if (flags & LONGINT) 823 *GETARG(long *) = ret; 824 else if (flags & SHORTINT) 825 *GETARG(short *) = ret; 826 else if (flags & CHARINT) 827 *GETARG(signed char *) = ret; 828 else 829 *GETARG(int *) = ret; 830 continue; /* no output */ 831 case 'O': 832 flags |= LONGINT; 833 /*FALLTHROUGH*/ 834 case 'o': 835 if (flags & INTMAX_SIZE) 836 ujval = UJARG(); 837 else 838 ulval = UARG(); 839 base = 8; 840 goto nosign; 841 case 'p': 842 /*- 843 * ``The argument shall be a pointer to void. The 844 * value of the pointer is converted to a sequence 845 * of printable characters, in an implementation- 846 * defined manner.'' 847 * -- ANSI X3J11 848 */ 849 ujval = (uintmax_t)(uintptr_t)GETARG(void *); 850 base = 16; 851 xdigs = xdigs_lower; 852 flags = flags | INTMAXT; 853 ox[1] = 'x'; 854 goto nosign; 855 case 'S': 856 flags |= LONGINT; 857 /*FALLTHROUGH*/ 858 case 's': 859 if (flags & LONGINT) { 860 wchar_t *wcp; 861 862 if (convbuf != NULL) 863 free(convbuf); 864 if ((wcp = GETARG(wchar_t *)) == NULL) 865 cp = "(null)"; 866 else { 867 convbuf = __wcsconv(wcp, prec); 868 if (convbuf == NULL) { 869 fp->_flags |= __SERR; 870 goto error; 871 } 872 cp = convbuf; 873 } 874 } else if ((cp = GETARG(char *)) == NULL) 875 cp = "(null)"; 876 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp); 877 sign = '\0'; 878 break; 879 case 'U': 880 flags |= LONGINT; 881 /*FALLTHROUGH*/ 882 case 'u': 883 if (flags & INTMAX_SIZE) 884 ujval = UJARG(); 885 else 886 ulval = UARG(); 887 base = 10; 888 goto nosign; 889 case 'X': 890 xdigs = xdigs_upper; 891 goto hex; 892 case 'x': 893 xdigs = xdigs_lower; 894 hex: 895 if (flags & INTMAX_SIZE) 896 ujval = UJARG(); 897 else 898 ulval = UARG(); 899 base = 16; 900 /* leading 0x/X only if non-zero */ 901 if (flags & ALT && 902 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 903 ox[1] = ch; 904 905 flags &= ~GROUPING; 906 /* unsigned conversions */ 907 nosign: sign = '\0'; 908 /*- 909 * ``... diouXx conversions ... if a precision is 910 * specified, the 0 flag will be ignored.'' 911 * -- ANSI X3J11 912 */ 913 number: if ((dprec = prec) >= 0) 914 flags &= ~ZEROPAD; 915 916 /*- 917 * ``The result of converting a zero value with an 918 * explicit precision of zero is no characters.'' 919 * -- ANSI X3J11 920 * 921 * ``The C Standard is clear enough as is. The call 922 * printf("%#.0o", 0) should print 0.'' 923 * -- Defect Report #151 924 */ 925 cp = buf + BUF; 926 if (flags & INTMAX_SIZE) { 927 if (ujval != 0 || prec != 0 || 928 (flags & ALT && base == 8)) 929 cp = __ujtoa(ujval, cp, base, 930 flags & ALT, xdigs); 931 } else { 932 if (ulval != 0 || prec != 0 || 933 (flags & ALT && base == 8)) 934 cp = __ultoa(ulval, cp, base, 935 flags & ALT, xdigs); 936 } 937 size = buf + BUF - cp; 938 if (size > BUF) /* should never happen */ 939 abort(); 940 if ((flags & GROUPING) && size != 0) 941 size += grouping_init(&gs, size, locale); 942 break; 943 default: /* "%?" prints ?, unless ? is NUL */ 944 if (ch == '\0') 945 goto done; 946 /* pretend it was %c with argument ch */ 947 cp = buf; 948 *cp = ch; 949 size = 1; 950 sign = '\0'; 951 break; 952 } 953 954 /* 955 * All reasonable formats wind up here. At this point, `cp' 956 * points to a string which (if not flags&LADJUST) should be 957 * padded out to `width' places. If flags&ZEROPAD, it should 958 * first be prefixed by any sign or other prefix; otherwise, 959 * it should be blank padded before the prefix is emitted. 960 * After any left-hand padding and prefixing, emit zeroes 961 * required by a decimal [diouxX] precision, then print the 962 * string proper, then emit zeroes required by any leftover 963 * floating precision; finally, if LADJUST, pad with blanks. 964 * 965 * Compute actual size, so we know how much to pad. 966 * size excludes decimal prec; realsz includes it. 967 */ 968 realsz = dprec > size ? dprec : size; 969 if (sign) 970 realsz++; 971 if (ox[1]) 972 realsz += 2; 973 974 prsize = width > realsz ? width : realsz; 975 if ((unsigned)ret + prsize > INT_MAX) { 976 ret = EOF; 977 errno = EOVERFLOW; 978 goto error; 979 } 980 981 /* right-adjusting blank padding */ 982 if ((flags & (LADJUST|ZEROPAD)) == 0) 983 PAD(width - realsz, blanks); 984 985 /* prefix */ 986 if (sign) 987 PRINT(&sign, 1); 988 989 if (ox[1]) { /* ox[1] is either x, X, or \0 */ 990 ox[0] = '0'; 991 PRINT(ox, 2); 992 } 993 994 /* right-adjusting zero padding */ 995 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) 996 PAD(width - realsz, zeroes); 997 998 /* the string or number proper */ 999 #ifndef NO_FLOATING_POINT 1000 if ((flags & FPT) == 0) { 1001 #endif 1002 /* leading zeroes from decimal precision */ 1003 PAD(dprec - size, zeroes); 1004 if (gs.grouping) { 1005 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0) 1006 goto error; 1007 } else { 1008 PRINT(cp, size); 1009 } 1010 #ifndef NO_FLOATING_POINT 1011 } else { /* glue together f_p fragments */ 1012 if (!expchar) { /* %[fF] or sufficiently short %[gG] */ 1013 if (expt <= 0) { 1014 PRINT(zeroes, 1); 1015 if (prec || flags & ALT) 1016 PRINT(decimal_point,decpt_len); 1017 PAD(-expt, zeroes); 1018 /* already handled initial 0's */ 1019 prec += expt; 1020 } else { 1021 if (gs.grouping) { 1022 n = grouping_print(&gs, &io, 1023 cp, dtoaend, locale); 1024 if (n < 0) 1025 goto error; 1026 cp += n; 1027 } else { 1028 PRINTANDPAD(cp, dtoaend, 1029 expt, zeroes); 1030 cp += expt; 1031 } 1032 if (prec || flags & ALT) 1033 PRINT(decimal_point,decpt_len); 1034 } 1035 PRINTANDPAD(cp, dtoaend, prec, zeroes); 1036 } else { /* %[eE] or sufficiently long %[gG] */ 1037 if (prec > 1 || flags & ALT) { 1038 PRINT(cp++, 1); 1039 PRINT(decimal_point, decpt_len); 1040 PRINT(cp, ndig-1); 1041 PAD(prec - ndig, zeroes); 1042 } else /* XeYYY */ 1043 PRINT(cp, 1); 1044 PRINT(expstr, expsize); 1045 } 1046 } 1047 #endif 1048 /* left-adjusting padding (always blank) */ 1049 if (flags & LADJUST) 1050 PAD(width - realsz, blanks); 1051 1052 /* finally, adjust ret */ 1053 ret += prsize; 1054 1055 FLUSH(); /* copy out the I/O vectors */ 1056 } 1057 done: 1058 FLUSH(); 1059 error: 1060 va_end(orgap); 1061 #ifndef NO_FLOATING_POINT 1062 if (dtoaresult != NULL) 1063 freedtoa(dtoaresult); 1064 #endif 1065 if (convbuf != NULL) 1066 free(convbuf); 1067 if (__sferror(fp)) 1068 ret = EOF; 1069 else 1070 fp->_flags |= savserr; 1071 if ((argtable != NULL) && (argtable != statargtable)) 1072 free (argtable); 1073 return (ret); 1074 /* NOTREACHED */ 1075 } 1076 1077