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 int error; 319 char errnomsg[NL_TEXTMAX]; 320 char sign; /* sign prefix (' ', '+', '-', or \0) */ 321 struct grouping_state gs; /* thousands' grouping info */ 322 323 #ifndef NO_FLOATING_POINT 324 /* 325 * We can decompose the printed representation of floating 326 * point numbers into several parts, some of which may be empty: 327 * 328 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ 329 * A B ---C--- D E F 330 * 331 * A: 'sign' holds this value if present; '\0' otherwise 332 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal 333 * C: cp points to the string MMMNNN. Leading and trailing 334 * zeros are not in the string and must be added. 335 * D: expchar holds this character; '\0' if no exponent, e.g. %f 336 * F: at least two digits for decimal, at least one digit for hex 337 */ 338 char *decimal_point; /* locale specific decimal point */ 339 int decpt_len; /* length of decimal_point */ 340 int signflag; /* true if float is negative */ 341 union { /* floating point arguments %[aAeEfFgG] */ 342 double dbl; 343 long double ldbl; 344 } fparg; 345 int expt; /* integer value of exponent */ 346 char expchar; /* exponent character: [eEpP\0] */ 347 char *dtoaend; /* pointer to end of converted digits */ 348 int expsize; /* character count for expstr */ 349 int ndig; /* actual number of digits returned by dtoa */ 350 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */ 351 char *dtoaresult; /* buffer allocated by dtoa */ 352 #endif 353 u_long ulval; /* integer arguments %[diouxX] */ 354 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */ 355 int base; /* base for [diouxX] conversion */ 356 int dprec; /* a copy of prec if [diouxX], 0 otherwise */ 357 int realsz; /* field size expanded by dprec, sign, etc */ 358 int size; /* size of converted field or string */ 359 int prsize; /* max size of printed field */ 360 const char *xdigs; /* digits for %[xX] conversion */ 361 struct io_state io; /* I/O buffering state */ 362 char buf[BUF]; /* buffer with space for digits of uintmax_t */ 363 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */ 364 union arg *argtable; /* args, built due to positional arg */ 365 union arg statargtable [STATIC_ARG_TBL_SIZE]; 366 int nextarg; /* 1-based argument index */ 367 va_list orgap; /* original argument pointer */ 368 char *convbuf; /* wide to multibyte conversion result */ 369 int savserr; 370 371 static const char xdigs_lower[16] = "0123456789abcdef"; 372 static const char xdigs_upper[16] = "0123456789ABCDEF"; 373 374 /* BEWARE, these `goto error' on error. */ 375 #define PRINT(ptr, len) { \ 376 if (io_print(&io, (ptr), (len), locale)) \ 377 goto error; \ 378 } 379 #define PAD(howmany, with) { \ 380 if (io_pad(&io, (howmany), (with), locale)) \ 381 goto error; \ 382 } 383 #define PRINTANDPAD(p, ep, len, with) { \ 384 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \ 385 goto error; \ 386 } 387 #define FLUSH() { \ 388 if (io_flush(&io, locale)) \ 389 goto error; \ 390 } 391 392 /* 393 * Get the argument indexed by nextarg. If the argument table is 394 * built, use it to get the argument. If its not, get the next 395 * argument (and arguments must be gotten sequentially). 396 */ 397 #define GETARG(type) \ 398 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \ 399 (nextarg++, va_arg(ap, type))) 400 401 /* 402 * To extend shorts properly, we need both signed and unsigned 403 * argument extraction methods. 404 */ 405 #define SARG() \ 406 (flags&LONGINT ? GETARG(long) : \ 407 flags&SHORTINT ? (long)(short)GETARG(int) : \ 408 flags&CHARINT ? (long)(signed char)GETARG(int) : \ 409 (long)GETARG(int)) 410 #define UARG() \ 411 (flags&LONGINT ? GETARG(u_long) : \ 412 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \ 413 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \ 414 (u_long)GETARG(u_int)) 415 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT) 416 #define SJARG() \ 417 (flags&INTMAXT ? GETARG(intmax_t) : \ 418 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \ 419 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \ 420 (intmax_t)GETARG(long long)) 421 #define UJARG() \ 422 (flags&INTMAXT ? GETARG(uintmax_t) : \ 423 flags&SIZET ? (uintmax_t)GETARG(size_t) : \ 424 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \ 425 (uintmax_t)GETARG(unsigned long long)) 426 427 /* 428 * Get * arguments, including the form *nn$. Preserve the nextarg 429 * that the argument can be gotten once the type is determined. 430 */ 431 #define GETASTER(val) \ 432 n2 = 0; \ 433 cp = fmt; \ 434 while (is_digit(*cp)) { \ 435 n2 = 10 * n2 + to_digit(*cp); \ 436 cp++; \ 437 } \ 438 if (*cp == '$') { \ 439 int hold = nextarg; \ 440 if (argtable == NULL) { \ 441 argtable = statargtable; \ 442 if (__find_arguments (fmt0, orgap, &argtable)) { \ 443 ret = EOF; \ 444 goto error; \ 445 } \ 446 } \ 447 nextarg = n2; \ 448 val = GETARG (int); \ 449 nextarg = hold; \ 450 fmt = ++cp; \ 451 } else { \ 452 val = GETARG (int); \ 453 } 454 455 if (__use_xprintf == 0 && getenv("USE_XPRINTF")) 456 __use_xprintf = 1; 457 if (__use_xprintf > 0) 458 return (__xvprintf(fp, fmt0, ap)); 459 460 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */ 461 if (prepwrite(fp) != 0) { 462 errno = EBADF; 463 return (EOF); 464 } 465 466 savserr = fp->_flags & __SERR; 467 fp->_flags &= ~__SERR; 468 469 saved_errno = errno; 470 convbuf = NULL; 471 fmt = (char *)fmt0; 472 argtable = NULL; 473 nextarg = 1; 474 va_copy(orgap, ap); 475 io_init(&io, fp); 476 ret = 0; 477 #ifndef NO_FLOATING_POINT 478 dtoaresult = NULL; 479 decimal_point = localeconv_l(locale)->decimal_point; 480 /* The overwhelmingly common case is decpt_len == 1. */ 481 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point)); 482 #endif 483 484 /* 485 * Scan the format for conversions (`%' character). 486 */ 487 for (;;) { 488 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 489 /* void */; 490 if ((n = fmt - cp) != 0) { 491 if ((unsigned)ret + n > INT_MAX) { 492 ret = EOF; 493 errno = EOVERFLOW; 494 goto error; 495 } 496 PRINT(cp, n); 497 ret += n; 498 } 499 if (ch == '\0') 500 goto done; 501 fmt++; /* skip over '%' */ 502 503 flags = 0; 504 dprec = 0; 505 width = 0; 506 prec = -1; 507 gs.grouping = NULL; 508 sign = '\0'; 509 ox[1] = '\0'; 510 511 rflag: ch = *fmt++; 512 reswitch: switch (ch) { 513 case ' ': 514 /*- 515 * ``If the space and + flags both appear, the space 516 * flag will be ignored.'' 517 * -- ANSI X3J11 518 */ 519 if (!sign) 520 sign = ' '; 521 goto rflag; 522 case '#': 523 flags |= ALT; 524 goto rflag; 525 case '*': 526 /*- 527 * ``A negative field width argument is taken as a 528 * - flag followed by a positive field width.'' 529 * -- ANSI X3J11 530 * They don't exclude field widths read from args. 531 */ 532 GETASTER (width); 533 if (width >= 0) 534 goto rflag; 535 width = -width; 536 /* FALLTHROUGH */ 537 case '-': 538 flags |= LADJUST; 539 goto rflag; 540 case '+': 541 sign = '+'; 542 goto rflag; 543 case '\'': 544 flags |= GROUPING; 545 goto rflag; 546 case '.': 547 if ((ch = *fmt++) == '*') { 548 GETASTER (prec); 549 goto rflag; 550 } 551 prec = 0; 552 while (is_digit(ch)) { 553 prec = 10 * prec + to_digit(ch); 554 ch = *fmt++; 555 } 556 goto reswitch; 557 case '0': 558 /*- 559 * ``Note that 0 is taken as a flag, not as the 560 * beginning of a field width.'' 561 * -- ANSI X3J11 562 */ 563 flags |= ZEROPAD; 564 goto rflag; 565 case '1': case '2': case '3': case '4': 566 case '5': case '6': case '7': case '8': case '9': 567 n = 0; 568 do { 569 n = 10 * n + to_digit(ch); 570 ch = *fmt++; 571 } while (is_digit(ch)); 572 if (ch == '$') { 573 nextarg = n; 574 if (argtable == NULL) { 575 argtable = statargtable; 576 if (__find_arguments (fmt0, orgap, 577 &argtable)) { 578 ret = EOF; 579 goto error; 580 } 581 } 582 goto rflag; 583 } 584 width = n; 585 goto reswitch; 586 #ifndef NO_FLOATING_POINT 587 case 'L': 588 flags |= LONGDBL; 589 goto rflag; 590 #endif 591 case 'h': 592 if (flags & SHORTINT) { 593 flags &= ~SHORTINT; 594 flags |= CHARINT; 595 } else 596 flags |= SHORTINT; 597 goto rflag; 598 case 'j': 599 flags |= INTMAXT; 600 goto rflag; 601 case 'l': 602 if (flags & LONGINT) { 603 flags &= ~LONGINT; 604 flags |= LLONGINT; 605 } else 606 flags |= LONGINT; 607 goto rflag; 608 case 'q': 609 flags |= LLONGINT; /* not necessarily */ 610 goto rflag; 611 case 't': 612 flags |= PTRDIFFT; 613 goto rflag; 614 case 'w': 615 /* 616 * Fixed-width integer types. On all platforms we 617 * support, int8_t is equivalent to char, int16_t 618 * is equivalent to short, int32_t is equivalent 619 * to int, int64_t is equivalent to long long int. 620 * Furthermore, int_fast8_t, int_fast16_t and 621 * int_fast32_t are equivalent to int, and 622 * int_fast64_t is equivalent to long long int. 623 */ 624 flags &= ~(CHARINT|SHORTINT|LONGINT|LLONGINT|INTMAXT); 625 if (fmt[0] == 'f') { 626 flags |= FASTINT; 627 fmt++; 628 } else { 629 flags &= ~FASTINT; 630 } 631 if (fmt[0] == '8') { 632 if (!(flags & FASTINT)) 633 flags |= CHARINT; 634 else 635 /* no flag set = 32 */ ; 636 fmt += 1; 637 } else if (fmt[0] == '1' && fmt[1] == '6') { 638 if (!(flags & FASTINT)) 639 flags |= SHORTINT; 640 else 641 /* no flag set = 32 */ ; 642 fmt += 2; 643 } else if (fmt[0] == '3' && fmt[1] == '2') { 644 /* no flag set = 32 */ ; 645 fmt += 2; 646 } else if (fmt[0] == '6' && fmt[1] == '4') { 647 flags |= LLONGINT; 648 fmt += 2; 649 } else { 650 if (flags & FASTINT) { 651 flags &= ~FASTINT; 652 fmt--; 653 } 654 goto invalid; 655 } 656 goto rflag; 657 case 'z': 658 flags |= SIZET; 659 goto rflag; 660 case 'B': 661 case 'b': 662 if (flags & INTMAX_SIZE) 663 ujval = UJARG(); 664 else 665 ulval = UARG(); 666 base = 2; 667 /* leading 0b/B only if non-zero */ 668 if (flags & ALT && 669 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 670 ox[1] = ch; 671 goto nosign; 672 break; 673 case 'C': 674 flags |= LONGINT; 675 /*FALLTHROUGH*/ 676 case 'c': 677 if (flags & LONGINT) { 678 static const mbstate_t initial; 679 mbstate_t mbs; 680 size_t mbseqlen; 681 682 mbs = initial; 683 mbseqlen = wcrtomb(cp = buf, 684 (wchar_t)GETARG(wint_t), &mbs); 685 if (mbseqlen == (size_t)-1) { 686 fp->_flags |= __SERR; 687 goto error; 688 } 689 size = (int)mbseqlen; 690 } else { 691 *(cp = buf) = GETARG(int); 692 size = 1; 693 } 694 sign = '\0'; 695 break; 696 case 'D': 697 flags |= LONGINT; 698 /*FALLTHROUGH*/ 699 case 'd': 700 case 'i': 701 if (flags & INTMAX_SIZE) { 702 ujval = SJARG(); 703 if ((intmax_t)ujval < 0) { 704 ujval = -ujval; 705 sign = '-'; 706 } 707 } else { 708 ulval = SARG(); 709 if ((long)ulval < 0) { 710 ulval = -ulval; 711 sign = '-'; 712 } 713 } 714 base = 10; 715 goto number; 716 #ifndef NO_FLOATING_POINT 717 case 'a': 718 case 'A': 719 if (ch == 'a') { 720 ox[1] = 'x'; 721 xdigs = xdigs_lower; 722 expchar = 'p'; 723 } else { 724 ox[1] = 'X'; 725 xdigs = xdigs_upper; 726 expchar = 'P'; 727 } 728 if (prec >= 0) 729 prec++; 730 if (dtoaresult != NULL) 731 freedtoa(dtoaresult); 732 if (flags & LONGDBL) { 733 fparg.ldbl = GETARG(long double); 734 dtoaresult = cp = 735 __hldtoa(fparg.ldbl, xdigs, prec, 736 &expt, &signflag, &dtoaend); 737 } else { 738 fparg.dbl = GETARG(double); 739 dtoaresult = cp = 740 __hdtoa(fparg.dbl, xdigs, prec, 741 &expt, &signflag, &dtoaend); 742 } 743 if (prec < 0) 744 prec = dtoaend - cp; 745 if (expt == INT_MAX) 746 ox[1] = '\0'; 747 goto fp_common; 748 case 'e': 749 case 'E': 750 expchar = ch; 751 if (prec < 0) /* account for digit before decpt */ 752 prec = DEFPREC + 1; 753 else 754 prec++; 755 goto fp_begin; 756 case 'f': 757 case 'F': 758 expchar = '\0'; 759 goto fp_begin; 760 case 'g': 761 case 'G': 762 expchar = ch - ('g' - 'e'); 763 if (prec == 0) 764 prec = 1; 765 fp_begin: 766 if (prec < 0) 767 prec = DEFPREC; 768 if (dtoaresult != NULL) 769 freedtoa(dtoaresult); 770 if (flags & LONGDBL) { 771 fparg.ldbl = GETARG(long double); 772 dtoaresult = cp = 773 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 774 &expt, &signflag, &dtoaend); 775 } else { 776 fparg.dbl = GETARG(double); 777 dtoaresult = cp = 778 dtoa(fparg.dbl, expchar ? 2 : 3, prec, 779 &expt, &signflag, &dtoaend); 780 if (expt == 9999) 781 expt = INT_MAX; 782 } 783 fp_common: 784 if (signflag) 785 sign = '-'; 786 if (expt == INT_MAX) { /* inf or nan */ 787 if (*cp == 'N') { 788 cp = (ch >= 'a') ? "nan" : "NAN"; 789 sign = '\0'; 790 } else 791 cp = (ch >= 'a') ? "inf" : "INF"; 792 size = 3; 793 flags &= ~ZEROPAD; 794 break; 795 } 796 flags |= FPT; 797 ndig = dtoaend - cp; 798 if (ch == 'g' || ch == 'G') { 799 if (expt > -4 && expt <= prec) { 800 /* Make %[gG] smell like %[fF] */ 801 expchar = '\0'; 802 if (flags & ALT) 803 prec -= expt; 804 else 805 prec = ndig - expt; 806 if (prec < 0) 807 prec = 0; 808 } else { 809 /* 810 * Make %[gG] smell like %[eE], but 811 * trim trailing zeroes if no # flag. 812 */ 813 if (!(flags & ALT)) 814 prec = ndig; 815 } 816 } 817 if (expchar) { 818 expsize = exponent(expstr, expt - 1, expchar); 819 size = expsize + prec; 820 if (prec > 1 || flags & ALT) 821 size += decpt_len; 822 } else { 823 /* space for digits before decimal point */ 824 if (expt > 0) 825 size = expt; 826 else /* "0" */ 827 size = 1; 828 /* space for decimal pt and following digits */ 829 if (prec || flags & ALT) 830 size += prec + decpt_len; 831 if ((flags & GROUPING) && expt > 0) 832 size += grouping_init(&gs, expt, locale); 833 } 834 break; 835 #endif /* !NO_FLOATING_POINT */ 836 case 'm': 837 error = __strerror_rl(saved_errno, errnomsg, 838 sizeof(errnomsg), locale); 839 cp = error == 0 ? errnomsg : "<strerror failure>"; 840 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp); 841 sign = '\0'; 842 break; 843 case 'n': 844 /* 845 * Assignment-like behavior is specified if the 846 * value overflows or is otherwise unrepresentable. 847 * C99 says to use `signed char' for %hhn conversions. 848 */ 849 if (flags & LLONGINT) 850 *GETARG(long long *) = ret; 851 else if (flags & SIZET) 852 *GETARG(ssize_t *) = (ssize_t)ret; 853 else if (flags & PTRDIFFT) 854 *GETARG(ptrdiff_t *) = ret; 855 else if (flags & INTMAXT) 856 *GETARG(intmax_t *) = ret; 857 else if (flags & LONGINT) 858 *GETARG(long *) = ret; 859 else if (flags & SHORTINT) 860 *GETARG(short *) = ret; 861 else if (flags & CHARINT) 862 *GETARG(signed char *) = ret; 863 else 864 *GETARG(int *) = ret; 865 continue; /* no output */ 866 case 'O': 867 flags |= LONGINT; 868 /*FALLTHROUGH*/ 869 case 'o': 870 if (flags & INTMAX_SIZE) 871 ujval = UJARG(); 872 else 873 ulval = UARG(); 874 base = 8; 875 goto nosign; 876 case 'p': 877 /*- 878 * ``The argument shall be a pointer to void. The 879 * value of the pointer is converted to a sequence 880 * of printable characters, in an implementation- 881 * defined manner.'' 882 * -- ANSI X3J11 883 */ 884 ujval = (uintmax_t)(uintptr_t)GETARG(void *); 885 base = 16; 886 xdigs = xdigs_lower; 887 flags = flags | INTMAXT; 888 ox[1] = 'x'; 889 goto nosign; 890 case 'S': 891 flags |= LONGINT; 892 /*FALLTHROUGH*/ 893 case 's': 894 if (flags & LONGINT) { 895 wchar_t *wcp; 896 897 if (convbuf != NULL) 898 free(convbuf); 899 if ((wcp = GETARG(wchar_t *)) == NULL) 900 cp = "(null)"; 901 else { 902 convbuf = __wcsconv(wcp, prec); 903 if (convbuf == NULL) { 904 fp->_flags |= __SERR; 905 goto error; 906 } 907 cp = convbuf; 908 } 909 } else if ((cp = GETARG(char *)) == NULL) 910 cp = "(null)"; 911 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp); 912 sign = '\0'; 913 break; 914 case 'U': 915 flags |= LONGINT; 916 /*FALLTHROUGH*/ 917 case 'u': 918 if (flags & INTMAX_SIZE) 919 ujval = UJARG(); 920 else 921 ulval = UARG(); 922 base = 10; 923 goto nosign; 924 case 'X': 925 xdigs = xdigs_upper; 926 goto hex; 927 case 'x': 928 xdigs = xdigs_lower; 929 hex: 930 if (flags & INTMAX_SIZE) 931 ujval = UJARG(); 932 else 933 ulval = UARG(); 934 base = 16; 935 /* leading 0x/X only if non-zero */ 936 if (flags & ALT && 937 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 938 ox[1] = ch; 939 940 flags &= ~GROUPING; 941 /* unsigned conversions */ 942 nosign: sign = '\0'; 943 /*- 944 * ``... diouXx conversions ... if a precision is 945 * specified, the 0 flag will be ignored.'' 946 * -- ANSI X3J11 947 */ 948 number: if ((dprec = prec) >= 0) 949 flags &= ~ZEROPAD; 950 951 /*- 952 * ``The result of converting a zero value with an 953 * explicit precision of zero is no characters.'' 954 * -- ANSI X3J11 955 * 956 * ``The C Standard is clear enough as is. The call 957 * printf("%#.0o", 0) should print 0.'' 958 * -- Defect Report #151 959 */ 960 cp = buf + BUF; 961 if (flags & INTMAX_SIZE) { 962 if (ujval != 0 || prec != 0 || 963 (flags & ALT && base == 8)) 964 cp = __ujtoa(ujval, cp, base, 965 flags & ALT, xdigs); 966 } else { 967 if (ulval != 0 || prec != 0 || 968 (flags & ALT && base == 8)) 969 cp = __ultoa(ulval, cp, base, 970 flags & ALT, xdigs); 971 } 972 size = buf + BUF - cp; 973 if (size > BUF) /* should never happen */ 974 abort(); 975 if ((flags & GROUPING) && size != 0) 976 size += grouping_init(&gs, size, locale); 977 break; 978 default: /* "%?" prints ?, unless ? is NUL */ 979 if (ch == '\0') 980 goto done; 981 invalid: 982 /* pretend it was %c with argument ch */ 983 cp = buf; 984 *cp = ch; 985 size = 1; 986 sign = '\0'; 987 break; 988 } 989 990 /* 991 * All reasonable formats wind up here. At this point, `cp' 992 * points to a string which (if not flags&LADJUST) should be 993 * padded out to `width' places. If flags&ZEROPAD, it should 994 * first be prefixed by any sign or other prefix; otherwise, 995 * it should be blank padded before the prefix is emitted. 996 * After any left-hand padding and prefixing, emit zeroes 997 * required by a decimal [diouxX] precision, then print the 998 * string proper, then emit zeroes required by any leftover 999 * floating precision; finally, if LADJUST, pad with blanks. 1000 * 1001 * Compute actual size, so we know how much to pad. 1002 * size excludes decimal prec; realsz includes it. 1003 */ 1004 realsz = dprec > size ? dprec : size; 1005 if (sign) 1006 realsz++; 1007 if (ox[1]) 1008 realsz += 2; 1009 1010 prsize = width > realsz ? width : realsz; 1011 if ((unsigned)ret + prsize > INT_MAX) { 1012 ret = EOF; 1013 errno = EOVERFLOW; 1014 goto error; 1015 } 1016 1017 /* right-adjusting blank padding */ 1018 if ((flags & (LADJUST|ZEROPAD)) == 0) 1019 PAD(width - realsz, blanks); 1020 1021 /* prefix */ 1022 if (sign) 1023 PRINT(&sign, 1); 1024 1025 if (ox[1]) { /* ox[1] is either x, X, or \0 */ 1026 ox[0] = '0'; 1027 PRINT(ox, 2); 1028 } 1029 1030 /* right-adjusting zero padding */ 1031 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) 1032 PAD(width - realsz, zeroes); 1033 1034 /* the string or number proper */ 1035 #ifndef NO_FLOATING_POINT 1036 if ((flags & FPT) == 0) { 1037 #endif 1038 /* leading zeroes from decimal precision */ 1039 PAD(dprec - size, zeroes); 1040 if (gs.grouping) { 1041 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0) 1042 goto error; 1043 } else { 1044 PRINT(cp, size); 1045 } 1046 #ifndef NO_FLOATING_POINT 1047 } else { /* glue together f_p fragments */ 1048 if (!expchar) { /* %[fF] or sufficiently short %[gG] */ 1049 if (expt <= 0) { 1050 PRINT(zeroes, 1); 1051 if (prec || flags & ALT) 1052 PRINT(decimal_point,decpt_len); 1053 PAD(-expt, zeroes); 1054 /* already handled initial 0's */ 1055 prec += expt; 1056 } else { 1057 if (gs.grouping) { 1058 n = grouping_print(&gs, &io, 1059 cp, dtoaend, locale); 1060 if (n < 0) 1061 goto error; 1062 cp += n; 1063 } else { 1064 PRINTANDPAD(cp, dtoaend, 1065 expt, zeroes); 1066 cp += expt; 1067 } 1068 if (prec || flags & ALT) 1069 PRINT(decimal_point,decpt_len); 1070 } 1071 PRINTANDPAD(cp, dtoaend, prec, zeroes); 1072 } else { /* %[eE] or sufficiently long %[gG] */ 1073 if (prec > 1 || flags & ALT) { 1074 PRINT(cp++, 1); 1075 PRINT(decimal_point, decpt_len); 1076 PRINT(cp, ndig-1); 1077 PAD(prec - ndig, zeroes); 1078 } else /* XeYYY */ 1079 PRINT(cp, 1); 1080 PRINT(expstr, expsize); 1081 } 1082 } 1083 #endif 1084 /* left-adjusting padding (always blank) */ 1085 if (flags & LADJUST) 1086 PAD(width - realsz, blanks); 1087 1088 /* finally, adjust ret */ 1089 ret += prsize; 1090 1091 FLUSH(); /* copy out the I/O vectors */ 1092 } 1093 done: 1094 FLUSH(); 1095 error: 1096 va_end(orgap); 1097 #ifndef NO_FLOATING_POINT 1098 if (dtoaresult != NULL) 1099 freedtoa(dtoaresult); 1100 #endif 1101 if (convbuf != NULL) 1102 free(convbuf); 1103 if (__sferror(fp)) 1104 ret = EOF; 1105 else 1106 fp->_flags |= savserr; 1107 if ((argtable != NULL) && (argtable != statargtable)) 1108 free (argtable); 1109 return (ret); 1110 /* NOTREACHED */ 1111 } 1112 1113