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