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