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