1 /* $NetBSD: vfwprintf.c,v 1.33 2013/09/23 12:41:37 pooka Exp $ */ 2 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 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 #include <sys/cdefs.h> 36 #if defined(LIBC_SCCS) && !defined(lint) 37 #if 0 38 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93"; 39 __FBSDID("$FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.27 2007/01/09 00:28:08 imp Exp $"); 40 #else 41 __RCSID("$NetBSD: vfwprintf.c,v 1.33 2013/09/23 12:41:37 pooka Exp $"); 42 #endif 43 #endif /* LIBC_SCCS and not lint */ 44 45 /* 46 * Actual {w,}printf innards. 47 */ 48 49 #include "namespace.h" 50 #include <sys/types.h> 51 52 #include <assert.h> 53 #include <ctype.h> 54 #include <limits.h> 55 #include <locale.h> 56 #include <stdarg.h> 57 #include <stddef.h> 58 #include <stdint.h> 59 #include <stdio.h> 60 #include <stdlib.h> 61 #include <string.h> 62 #include <errno.h> 63 #include <wchar.h> 64 #include <wctype.h> 65 66 #include "reentrant.h" 67 #include "setlocale_local.h" 68 #include "local.h" 69 #include "extern.h" 70 #include "fvwrite.h" 71 72 #ifndef NARROW 73 #define MCHAR_T char 74 #define CHAR_T wchar_t 75 #define STRLEN(a) wcslen(a) 76 #define MEMCHR(a, b, c) wmemchr(a, b, c) 77 #define SCONV(a, b, loc) __mbsconv(a, b, loc) 78 #define STRCONST(a) L ## a 79 #define WDECL(a, b) a ## w ## b 80 #define END_OF_FILE WEOF 81 #define MULTI 0 82 #else 83 #define MCHAR_T wchar_t 84 #define CHAR_T char 85 #define STRLEN(a) strlen(a) 86 #define MEMCHR(a, b, c) memchr(a, b, c) 87 #define SCONV(a, b, loc) __wcsconv(a, b, loc) 88 #define STRCONST(a) a 89 #define WDECL(a, b) a ## b 90 #define END_OF_FILE EOF 91 #define MULTI LONGINT 92 #endif 93 94 union arg { 95 int intarg; 96 u_int uintarg; 97 long longarg; 98 u_long ulongarg; 99 long long longlongarg; 100 unsigned long long ulonglongarg; 101 ptrdiff_t ptrdiffarg; 102 ssize_t ssizearg; 103 size_t sizearg; 104 intmax_t intmaxarg; 105 uintmax_t uintmaxarg; 106 void *pvoidarg; 107 char *pchararg; 108 signed char *pschararg; 109 short *pshortarg; 110 int *pintarg; 111 long *plongarg; 112 long long *plonglongarg; 113 ptrdiff_t *pptrdiffarg; 114 size_t *psizearg; 115 intmax_t *pintmaxarg; 116 #ifndef NO_FLOATING_POINT 117 double doublearg; 118 long double longdoublearg; 119 #endif 120 wint_t wintarg; 121 wchar_t *pwchararg; 122 }; 123 124 /* 125 * Type ids for argument type table. 126 */ 127 enum typeid { 128 T_UNUSED = 0, TP_SHORT, T_INT, T_U_INT, TP_INT, 129 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG, 130 T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SIZET, 131 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR, 132 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR 133 }; 134 135 #ifdef NARROW 136 __printflike(3, 0) 137 #endif 138 static int __sbprintf(FILE *, locale_t, const CHAR_T *, va_list); 139 140 static CHAR_T *__ujtoa(uintmax_t, CHAR_T *, int, int, const char *, int, 141 char, const char *); 142 static CHAR_T *__ultoa(u_long, CHAR_T *, int, int, const char *, int, 143 char, const char *); 144 #ifndef NARROW 145 static CHAR_T *__mbsconv(char *, int, locale_t); 146 static wint_t __xfputwc(CHAR_T, FILE *, locale_t); 147 #else 148 static char *__wcsconv(wchar_t *, int, locale_t); 149 static int __sprint(FILE *, struct __suio *); 150 #endif 151 static int __find_arguments(const CHAR_T *, va_list, union arg **); 152 static int __grow_type_table(size_t, enum typeid **, size_t *); 153 154 /* 155 * Helper function for `fprintf to unbuffered unix file': creates a 156 * temporary buffer. We only work on write-only files; this avoids 157 * worries about ungetc buffers and so forth. 158 */ 159 static int 160 __sbprintf(FILE *fp, locale_t loc, const CHAR_T *fmt, va_list ap) 161 { 162 int ret; 163 FILE fake; 164 struct __sfileext fakeext; 165 unsigned char buf[BUFSIZ]; 166 167 _DIAGASSERT(fp != NULL); 168 _DIAGASSERT(fmt != NULL); 169 170 _FILEEXT_SETUP(&fake, &fakeext); 171 memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data)); 172 173 /* copy the important variables */ 174 fake._flags = fp->_flags & ~__SNBF; 175 fake._file = fp->_file; 176 fake._cookie = fp->_cookie; 177 fake._write = fp->_write; 178 fake._flush = fp->_flush; 179 180 /* set up the buffer */ 181 fake._bf._base = fake._p = buf; 182 fake._bf._size = fake._w = sizeof(buf); 183 fake._lbfsize = 0; /* not actually used, but Just In Case */ 184 185 /* do the work, then copy any error status */ 186 ret = WDECL(__vf,printf_unlocked_l)(&fake, loc, fmt, ap); 187 if (ret >= 0 && fflush(&fake)) 188 ret = END_OF_FILE; 189 if (fake._flags & __SERR) 190 fp->_flags |= __SERR; 191 return ret; 192 } 193 194 #ifndef NARROW 195 /* 196 * Like __fputwc, but handles fake string (__SSTR) files properly. 197 * File must already be locked. 198 */ 199 static wint_t 200 __xfputwc(wchar_t wc, FILE *fp, locale_t loc) 201 { 202 static const mbstate_t initial; 203 mbstate_t mbs; 204 char buf[MB_LEN_MAX]; 205 struct __suio uio; 206 struct __siov iov; 207 size_t len; 208 209 if ((fp->_flags & __SSTR) == 0) 210 return __fputwc_unlock(wc, fp); 211 212 mbs = initial; 213 if ((len = wcrtomb_l(buf, wc, &mbs, loc)) == (size_t)-1) { 214 fp->_flags |= __SERR; 215 return END_OF_FILE; 216 } 217 uio.uio_iov = &iov; 218 uio.uio_resid = len; 219 uio.uio_iovcnt = 1; 220 iov.iov_base = buf; 221 iov.iov_len = len; 222 return __sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE; 223 } 224 #else 225 /* 226 * Flush out all the vectors defined by the given uio, 227 * then reset it so that it can be reused. 228 */ 229 static int 230 __sprint(FILE *fp, struct __suio *uio) 231 { 232 int err; 233 234 _DIAGASSERT(fp != NULL); 235 _DIAGASSERT(uio != NULL); 236 237 if (uio->uio_resid == 0) { 238 uio->uio_iovcnt = 0; 239 return 0; 240 } 241 err = __sfvwrite(fp, uio); 242 uio->uio_resid = 0; 243 uio->uio_iovcnt = 0; 244 return err; 245 } 246 #endif 247 248 /* 249 * Macros for converting digits to letters and vice versa 250 */ 251 #define to_digit(c) ((c) - '0') 252 #define is_digit(c) ((unsigned)to_digit(c) <= 9) 253 #define to_char(n) (CHAR_T)((n) + '0') 254 255 /* 256 * Convert an unsigned long to ASCII for printf purposes, returning 257 * a pointer to the first character of the string representation. 258 * Octal numbers can be forced to have a leading zero; hex numbers 259 * use the given digits. 260 */ 261 static CHAR_T * 262 __ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs, 263 int needgrp, char thousep, const char *grp) 264 { 265 CHAR_T *cp = endp; 266 long sval; 267 int ndig; 268 269 /* 270 * Handle the three cases separately, in the hope of getting 271 * better/faster code. 272 */ 273 switch (base) { 274 case 10: 275 if (val < 10) { /* many numbers are 1 digit */ 276 *--cp = to_char(val); 277 return cp; 278 } 279 ndig = 0; 280 /* 281 * On many machines, unsigned arithmetic is harder than 282 * signed arithmetic, so we do at most one unsigned mod and 283 * divide; this is sufficient to reduce the range of 284 * the incoming value to where signed arithmetic works. 285 */ 286 if (val > LONG_MAX) { 287 *--cp = to_char(val % 10); 288 ndig++; 289 sval = val / 10; 290 } else 291 sval = val; 292 do { 293 *--cp = to_char(sval % 10); 294 ndig++; 295 /* 296 * If (*grp == CHAR_MAX) then no more grouping 297 * should be performed. 298 */ 299 if (needgrp && ndig == *grp 300 && (unsigned char)*grp != (unsigned char)CHAR_MAX 301 && sval > 9) { 302 *--cp = thousep; 303 ndig = 0; 304 /* 305 * If (*(grp+1) == '\0') then we have to 306 * use *grp character (last grouping rule) 307 * for all next cases 308 */ 309 if (*(grp+1) != '\0') 310 grp++; 311 } 312 sval /= 10; 313 } while (sval != 0); 314 break; 315 316 case 8: 317 do { 318 *--cp = to_char(val & 7); 319 val >>= 3; 320 } while (val); 321 if (octzero && *cp != '0') 322 *--cp = '0'; 323 break; 324 325 case 16: 326 do { 327 *--cp = xdigs[(size_t)val & 15]; 328 val >>= 4; 329 } while (val); 330 break; 331 332 default: /* oops */ 333 abort(); 334 } 335 return cp; 336 } 337 338 /* Identical to __ultoa, but for intmax_t. */ 339 static CHAR_T * 340 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero, 341 const char *xdigs, int needgrp, char thousep, const char *grp) 342 { 343 CHAR_T *cp = endp; 344 intmax_t sval; 345 int ndig; 346 347 /* quick test for small values; __ultoa is typically much faster */ 348 /* (perhaps instead we should run until small, then call __ultoa?) */ 349 if (val <= ULONG_MAX) 350 return __ultoa((u_long)val, endp, base, octzero, xdigs, 351 needgrp, thousep, grp); 352 switch (base) { 353 case 10: 354 if (val < 10) { 355 *--cp = to_char(val % 10); 356 return cp; 357 } 358 ndig = 0; 359 if (val > INTMAX_MAX) { 360 *--cp = to_char(val % 10); 361 ndig++; 362 sval = val / 10; 363 } else 364 sval = val; 365 do { 366 *--cp = to_char(sval % 10); 367 ndig++; 368 /* 369 * If (*grp == CHAR_MAX) then no more grouping 370 * should be performed. 371 */ 372 if (needgrp 373 && (unsigned char)*grp != (unsigned char)CHAR_MAX 374 && ndig == *grp 375 && sval > 9) { 376 *--cp = thousep; 377 ndig = 0; 378 /* 379 * If (*(grp+1) == '\0') then we have to 380 * use *grp character (last grouping rule) 381 * for all next cases 382 */ 383 if (*(grp+1) != '\0') 384 grp++; 385 } 386 sval /= 10; 387 } while (sval != 0); 388 break; 389 390 case 8: 391 do { 392 *--cp = to_char(val & 7); 393 val >>= 3; 394 } while (val); 395 if (octzero && *cp != '0') 396 *--cp = '0'; 397 break; 398 399 case 16: 400 do { 401 *--cp = xdigs[(size_t)val & 15]; 402 val >>= 4; 403 } while (val); 404 break; 405 406 default: 407 abort(); 408 } 409 return cp; 410 } 411 412 #ifndef NARROW 413 /* 414 * Convert a multibyte character string argument for the %s format to a wide 415 * string representation. ``prec'' specifies the maximum number of bytes 416 * to output. If ``prec'' is greater than or equal to zero, we can't assume 417 * that the multibyte char. string ends in a null character. 418 */ 419 static wchar_t * 420 __mbsconv(char *mbsarg, int prec, locale_t loc) 421 { 422 static const mbstate_t initial; 423 mbstate_t mbs; 424 wchar_t *convbuf, *wcp; 425 const char *p; 426 size_t insize, nchars, nconv; 427 428 if (mbsarg == NULL) 429 return NULL; 430 431 /* 432 * Supplied argument is a multibyte string; convert it to wide 433 * characters first. 434 */ 435 if (prec >= 0) { 436 /* 437 * String is not guaranteed to be NUL-terminated. Find the 438 * number of characters to print. 439 */ 440 p = mbsarg; 441 insize = nchars = nconv = 0; 442 mbs = initial; 443 while (nchars != (size_t)prec) { 444 nconv = mbrlen_l(p, MB_CUR_MAX_L(loc), &mbs, loc); 445 if (nconv == 0 || nconv == (size_t)-1 || 446 nconv == (size_t)-2) 447 break; 448 p += nconv; 449 nchars++; 450 insize += nconv; 451 } 452 if (nconv == (size_t)-1 || nconv == (size_t)-2) 453 return NULL; 454 } else 455 insize = strlen(mbsarg); 456 457 /* 458 * Allocate buffer for the result and perform the conversion, 459 * converting at most `size' bytes of the input multibyte string to 460 * wide characters for printing. 461 */ 462 convbuf = malloc((insize + 1) * sizeof(*convbuf)); 463 if (convbuf == NULL) 464 return NULL; 465 wcp = convbuf; 466 p = mbsarg; 467 mbs = initial; 468 nconv = 0; 469 while (insize != 0) { 470 nconv = mbrtowc_l(wcp, p, insize, &mbs, loc); 471 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2) 472 break; 473 wcp++; 474 p += nconv; 475 insize -= nconv; 476 } 477 if (nconv == (size_t)-1 || nconv == (size_t)-2) { 478 free(convbuf); 479 return NULL; 480 } 481 *wcp = L'\0'; 482 483 return convbuf; 484 } 485 #else 486 /* 487 * Convert a wide-character string argument for the %ls format to a multibyte 488 * string representation. If not -1, prec specifies the maximum number of 489 * bytes to output, and also means that we can't assume that the wide-char. 490 * string ends is null-terminated. 491 */ 492 static char * 493 __wcsconv(wchar_t *wcsarg, int prec, locale_t loc) 494 { 495 static const mbstate_t initial; 496 mbstate_t mbs; 497 char buf[MB_LEN_MAX]; 498 wchar_t *p; 499 char *convbuf; 500 size_t clen, nbytes; 501 502 /* Allocate space for the maximum number of bytes we could output. */ 503 if (prec < 0) { 504 p = wcsarg; 505 mbs = initial; 506 nbytes = wcsrtombs_l(NULL, (void *)&p, 0, &mbs, loc); 507 if (nbytes == (size_t)-1) 508 return NULL; 509 } else { 510 /* 511 * Optimisation: if the output precision is small enough, 512 * just allocate enough memory for the maximum instead of 513 * scanning the string. 514 */ 515 if (prec < 128) 516 nbytes = prec; 517 else { 518 nbytes = 0; 519 p = wcsarg; 520 mbs = initial; 521 for (;;) { 522 clen = wcrtomb_l(buf, *p++, &mbs, loc); 523 if (clen == 0 || clen == (size_t)-1 || 524 nbytes + clen > (size_t)prec) 525 break; 526 nbytes += clen; 527 } 528 } 529 } 530 if ((convbuf = malloc(nbytes + 1)) == NULL) 531 return NULL; 532 533 /* Fill the output buffer. */ 534 p = wcsarg; 535 mbs = initial; 536 if ((nbytes = wcsrtombs_l(convbuf, (void *)&p, 537 nbytes, &mbs, loc)) == (size_t)-1) { 538 free(convbuf); 539 return NULL; 540 } 541 convbuf[nbytes] = '\0'; 542 return convbuf; 543 } 544 #endif 545 546 /* 547 * MT-safe version 548 */ 549 int 550 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap) 551 { 552 int ret; 553 554 FLOCKFILE(fp); 555 ret = WDECL(__vf,printf_unlocked_l)(fp, _current_locale(), fmt0, ap); 556 FUNLOCKFILE(fp); 557 return ret; 558 } 559 560 int 561 WDECL(vf,printf_l)(FILE * __restrict fp, locale_t loc, const CHAR_T * __restrict fmt0, 562 va_list ap) 563 { 564 int ret; 565 566 FLOCKFILE(fp); 567 ret = WDECL(__vf,printf_unlocked_l)(fp, loc, fmt0, ap); 568 FUNLOCKFILE(fp); 569 return ret; 570 } 571 572 #ifndef NO_FLOATING_POINT 573 574 #include <float.h> 575 #include <math.h> 576 #include "floatio.h" 577 578 #define DEFPREC 6 579 580 static int exponent(CHAR_T *, int, int); 581 #ifndef WIDE_DOUBLE 582 static char *cvt(double, int, int, char *, int *, int, int *); 583 #endif 584 585 #endif /* !NO_FLOATING_POINT */ 586 587 /* 588 * The size of the buffer we use as scratch space for integer 589 * conversions, among other things. Technically, we would need the 590 * most space for base 10 conversions with thousands' grouping 591 * characters between each pair of digits. 100 bytes is a 592 * conservative overestimate even for a 128-bit uintmax_t. 593 */ 594 #define BUF 100 595 596 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */ 597 598 /* 599 * Flags used during conversion. 600 */ 601 #define ALT 0x001 /* alternate form */ 602 #define LADJUST 0x004 /* left adjustment */ 603 #define LONGDBL 0x008 /* long double */ 604 #define LONGINT 0x010 /* long integer */ 605 #define LLONGINT 0x020 /* long long integer */ 606 #define SHORTINT 0x040 /* short integer */ 607 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */ 608 #define FPT 0x100 /* Floating point number */ 609 #define GROUPING 0x200 /* use grouping ("'" flag) */ 610 /* C99 additional size modifiers: */ 611 #define SIZET 0x400 /* size_t */ 612 #define PTRDIFFT 0x800 /* ptrdiff_t */ 613 #define INTMAXT 0x1000 /* intmax_t */ 614 #define CHARINT 0x2000 /* print char using int format */ 615 616 /* 617 * Non-MT-safe version 618 */ 619 int 620 WDECL(__vf,printf_unlocked_l)(FILE *fp, locale_t loc, const CHAR_T *fmt0, va_list ap) 621 { 622 CHAR_T *fmt; /* format string */ 623 int ch; /* character from fmt */ 624 int n, n2; /* handy integer (short term usage) */ 625 CHAR_T *cp; /* handy char pointer (short term usage) */ 626 int flags; /* flags as above */ 627 int ret; /* return value accumulator */ 628 int width; /* width from format (%8d), or 0 */ 629 int prec; /* precision from format; <0 for N/A */ 630 CHAR_T sign; /* sign prefix (' ', '+', '-', or \0) */ 631 char thousands_sep; /* locale specific thousands separator */ 632 const char *grouping; /* locale specific numeric grouping rules */ 633 #ifndef NO_FLOATING_POINT 634 /* 635 * We can decompose the printed representation of floating 636 * point numbers into several parts, some of which may be empty: 637 * 638 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ 639 * A B ---C--- D E F 640 * 641 * A: 'sign' holds this value if present; '\0' otherwise 642 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal 643 * C: cp points to the string MMMNNN. Leading and trailing 644 * zeros are not in the string and must be added. 645 * D: expchar holds this character; '\0' if no exponent, e.g. %f 646 * F: at least two digits for decimal, at least one digit for hex 647 */ 648 char *decimal_point; /* locale specific decimal point */ 649 #ifdef WIDE_DOUBLE 650 int signflag; /* true if float is negative */ 651 union { /* floating point arguments %[aAeEfFgG] */ 652 double dbl; 653 long double ldbl; 654 } fparg; 655 char *dtoaend; /* pointer to end of converted digits */ 656 #else 657 double _double; /* double precision arguments %[eEfgG] */ 658 char softsign; /* temporary negative sign for floats */ 659 #endif 660 char *dtoaresult; /* buffer allocated by dtoa */ 661 int expt; /* integer value of exponent */ 662 char expchar; /* exponent character: [eEpP\0] */ 663 int expsize; /* character count for expstr */ 664 int lead; /* sig figs before decimal or group sep */ 665 int ndig; /* actual number of digits returned by dtoa */ 666 CHAR_T expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */ 667 int nseps; /* number of group separators with ' */ 668 int nrepeats; /* number of repeats of the last group */ 669 #endif 670 u_long ulval; /* integer arguments %[diouxX] */ 671 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */ 672 int base; /* base for [diouxX] conversion */ 673 int dprec; /* a copy of prec if [diouxX], 0 otherwise */ 674 int realsz; /* field size expanded by dprec, sign, etc */ 675 int size; /* size of converted field or string */ 676 int prsize; /* max size of printed field */ 677 const char *xdigs; /* digits for %[xX] conversion */ 678 #ifdef NARROW 679 #define NIOV 8 680 struct __siov *iovp; /* for PRINT macro */ 681 struct __suio uio; /* output information: summary */ 682 struct __siov iov[NIOV];/* ... and individual io vectors */ 683 #else 684 int n3; 685 #endif 686 CHAR_T buf[BUF]; /* buffer with space for digits of uintmax_t */ 687 CHAR_T ox[2]; /* space for 0x hex-prefix */ 688 union arg *argtable; /* args, built due to positional arg */ 689 union arg statargtable [STATIC_ARG_TBL_SIZE]; 690 int nextarg; /* 1-based argument index */ 691 va_list orgap; /* original argument pointer */ 692 CHAR_T *convbuf; /* multibyte to wide conversion result */ 693 694 /* 695 * Choose PADSIZE to trade efficiency vs. size. If larger printf 696 * fields occur frequently, increase PADSIZE and make the initialisers 697 * below longer. 698 */ 699 #define PADSIZE 16 /* pad chunk size */ 700 static CHAR_T blanks[PADSIZE] = 701 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; 702 static CHAR_T zeroes[PADSIZE] = 703 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'}; 704 705 static const char xdigs_lower[16] = "0123456789abcdef"; 706 static const char xdigs_upper[16] = "0123456789ABCDEF"; 707 708 /* 709 * BEWARE, these `goto error' on error, PRINT uses `n2' and 710 * PAD uses `n'. 711 */ 712 #ifndef NARROW 713 #define PRINT(ptr, len) do { \ 714 for (n3 = 0; n3 < (len); n3++) \ 715 __xfputwc((ptr)[n3], fp, loc); \ 716 } while (/*CONSTCOND*/0) 717 #define FLUSH() 718 #else 719 #define PRINT(ptr, len) do { \ 720 iovp->iov_base = __UNCONST(ptr); \ 721 iovp->iov_len = (len); \ 722 uio.uio_resid += (len); \ 723 iovp++; \ 724 if (++uio.uio_iovcnt >= NIOV) { \ 725 if (__sprint(fp, &uio)) \ 726 goto error; \ 727 iovp = iov; \ 728 } \ 729 } while (/*CONSTCOND*/0) 730 #define FLUSH() do { \ 731 if (uio.uio_resid && __sprint(fp, &uio)) \ 732 goto error; \ 733 uio.uio_iovcnt = 0; \ 734 iovp = iov; \ 735 } while (/*CONSTCOND*/0) 736 #endif /* NARROW */ 737 738 #define PAD(howmany, with) do { \ 739 if ((n = (howmany)) > 0) { \ 740 while (n > PADSIZE) { \ 741 PRINT(with, PADSIZE); \ 742 n -= PADSIZE; \ 743 } \ 744 PRINT(with, n); \ 745 } \ 746 } while (/*CONSTCOND*/0) 747 #define PRINTANDPAD(p, ep, len, with) do { \ 748 ptrdiff_t td = (ep) - (p); \ 749 _DIAGASSERT(__type_fit(int, td)); \ 750 n2 = (int)td; \ 751 if (n2 > (len)) \ 752 n2 = (len); \ 753 if (n2 > 0) \ 754 PRINT((p), n2); \ 755 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \ 756 } while(/*CONSTCOND*/0) 757 758 /* 759 * Get the argument indexed by nextarg. If the argument table is 760 * built, use it to get the argument. If its not, get the next 761 * argument (and arguments must be gotten sequentially). 762 */ 763 #define GETARG(type) \ 764 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \ 765 (nextarg++, va_arg(ap, type))) 766 767 /* 768 * To extend shorts properly, we need both signed and unsigned 769 * argument extraction methods. 770 */ 771 #define SARG() \ 772 (flags&LONGINT ? GETARG(long) : \ 773 flags&SHORTINT ? (long)(short)GETARG(int) : \ 774 flags&CHARINT ? (long)(signed char)GETARG(int) : \ 775 (long)GETARG(int)) 776 #define UARG() \ 777 (flags&LONGINT ? GETARG(u_long) : \ 778 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \ 779 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \ 780 (u_long)GETARG(u_int)) 781 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT) 782 #define SJARG() \ 783 (flags&INTMAXT ? GETARG(intmax_t) : \ 784 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \ 785 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \ 786 (intmax_t)GETARG(long long)) 787 #define UJARG() \ 788 (flags&INTMAXT ? GETARG(uintmax_t) : \ 789 flags&SIZET ? (uintmax_t)GETARG(size_t) : \ 790 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \ 791 (uintmax_t)GETARG(unsigned long long)) 792 793 /* 794 * Get * arguments, including the form *nn$. Preserve the nextarg 795 * that the argument can be gotten once the type is determined. 796 */ 797 #define GETASTER(val) \ 798 n2 = 0; \ 799 cp = fmt; \ 800 while (is_digit(*cp)) { \ 801 n2 = 10 * n2 + to_digit(*cp); \ 802 cp++; \ 803 } \ 804 if (*cp == '$') { \ 805 int hold = nextarg; \ 806 if (argtable == NULL) { \ 807 argtable = statargtable; \ 808 if (__find_arguments(fmt0, orgap, &argtable) == -1) \ 809 goto oomem; \ 810 } \ 811 nextarg = n2; \ 812 val = GETARG (int); \ 813 nextarg = hold; \ 814 fmt = ++cp; \ 815 } else { \ 816 val = GETARG (int); \ 817 } 818 819 _DIAGASSERT(fp != NULL); 820 _DIAGASSERT(fmt0 != NULL); 821 822 _SET_ORIENTATION(fp, -1); 823 824 thousands_sep = '\0'; 825 grouping = NULL; 826 #ifndef NO_FLOATING_POINT 827 decimal_point = localeconv_l(loc)->decimal_point; 828 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */ 829 ndig = -1; /* XXX gcc */ 830 #endif 831 convbuf = NULL; 832 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */ 833 if (cantwrite(fp)) { 834 errno = EBADF; 835 return END_OF_FILE; 836 } 837 838 /* optimise fprintf(stderr) (and other unbuffered Unix files) */ 839 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) && 840 __sfileno(fp) != -1) 841 return __sbprintf(fp, loc, fmt0, ap); 842 843 fmt = (CHAR_T *)__UNCONST(fmt0); 844 argtable = NULL; 845 nextarg = 1; 846 va_copy(orgap, ap); 847 #ifdef NARROW 848 uio.uio_iov = iovp = iov; 849 uio.uio_resid = 0; 850 uio.uio_iovcnt = 0; 851 #endif 852 ret = 0; 853 854 /* 855 * Scan the format for conversions (`%' character). 856 */ 857 for (;;) { 858 const CHAR_T *result; 859 860 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 861 continue; 862 _DIAGASSERT(__type_fit(int, fmt - cp)); 863 if ((n = (int)(fmt - cp)) != 0) { 864 if ((unsigned)ret + n > INT_MAX) { 865 ret = END_OF_FILE; 866 goto error; 867 } 868 PRINT(cp, n); 869 ret += n; 870 } 871 if (ch == '\0') 872 goto done; 873 fmt++; /* skip over '%' */ 874 875 flags = 0; 876 dprec = 0; 877 width = 0; 878 prec = -1; 879 sign = '\0'; 880 ox[1] = '\0'; 881 #ifndef NO_FLOATING_POINT 882 expchar = '\0'; 883 lead = 0; 884 nseps = nrepeats = 0; 885 #endif 886 ulval = 0; 887 ujval = 0; 888 xdigs = NULL; 889 890 rflag: ch = *fmt++; 891 reswitch: switch (ch) { 892 case ' ': 893 /*- 894 * ``If the space and + flags both appear, the space 895 * flag will be ignored.'' 896 * -- ANSI X3J11 897 */ 898 if (!sign) 899 sign = ' '; 900 goto rflag; 901 case '#': 902 flags |= ALT; 903 goto rflag; 904 case '*': 905 /*- 906 * ``A negative field width argument is taken as a 907 * - flag followed by a positive field width.'' 908 * -- ANSI X3J11 909 * They don't exclude field widths read from args. 910 */ 911 GETASTER (width); 912 if (width >= 0) 913 goto rflag; 914 width = -width; 915 /* FALLTHROUGH */ 916 case '-': 917 flags |= LADJUST; 918 goto rflag; 919 case '+': 920 sign = '+'; 921 goto rflag; 922 case '\'': 923 flags |= GROUPING; 924 thousands_sep = *(localeconv_l(loc)->thousands_sep); 925 grouping = localeconv_l(loc)->grouping; 926 /* If the locale doesn't define the above, use sane 927 * defaults - otherwise silly things happen! */ 928 if (thousands_sep == 0) 929 thousands_sep = ','; 930 if (!grouping || !*grouping) 931 grouping = "\3"; 932 goto rflag; 933 case '.': 934 if ((ch = *fmt++) == '*') { 935 GETASTER (prec); 936 goto rflag; 937 } 938 prec = 0; 939 while (is_digit(ch)) { 940 prec = 10 * prec + to_digit(ch); 941 ch = *fmt++; 942 } 943 goto reswitch; 944 case '0': 945 /*- 946 * ``Note that 0 is taken as a flag, not as the 947 * beginning of a field width.'' 948 * -- ANSI X3J11 949 */ 950 flags |= ZEROPAD; 951 goto rflag; 952 case '1': case '2': case '3': case '4': 953 case '5': case '6': case '7': case '8': case '9': 954 n = 0; 955 do { 956 n = 10 * n + to_digit(ch); 957 ch = *fmt++; 958 } while (is_digit(ch)); 959 if (ch == '$') { 960 nextarg = n; 961 if (argtable == NULL) { 962 argtable = statargtable; 963 if (__find_arguments(fmt0, orgap, 964 &argtable) == -1) 965 goto oomem; 966 } 967 goto rflag; 968 } 969 width = n; 970 goto reswitch; 971 #ifndef NO_FLOATING_POINT 972 case 'L': 973 flags |= LONGDBL; 974 goto rflag; 975 #endif 976 case 'h': 977 if (flags & SHORTINT) { 978 flags &= ~SHORTINT; 979 flags |= CHARINT; 980 } else 981 flags |= SHORTINT; 982 goto rflag; 983 case 'j': 984 flags |= INTMAXT; 985 goto rflag; 986 case 'l': 987 if (flags & LONGINT) { 988 flags &= ~LONGINT; 989 flags |= LLONGINT; 990 } else 991 flags |= LONGINT; 992 goto rflag; 993 case 'q': 994 flags |= LLONGINT; /* not necessarily */ 995 goto rflag; 996 case 't': 997 flags |= PTRDIFFT; 998 goto rflag; 999 case 'z': 1000 flags |= SIZET; 1001 goto rflag; 1002 case 'C': 1003 flags |= LONGINT; 1004 /*FALLTHROUGH*/ 1005 case 'c': 1006 #ifdef NARROW 1007 if (flags & LONGINT) { 1008 static const mbstate_t initial; 1009 mbstate_t mbs; 1010 size_t mbseqlen; 1011 1012 mbs = initial; 1013 mbseqlen = wcrtomb_l(buf, 1014 (wchar_t)GETARG(wint_t), &mbs, loc); 1015 if (mbseqlen == (size_t)-1) { 1016 fp->_flags |= __SERR; 1017 goto error; 1018 } 1019 size = (int)mbseqlen; 1020 } else { 1021 *buf = GETARG(int); 1022 size = 1; 1023 } 1024 #else 1025 if (flags & LONGINT) 1026 *buf = (wchar_t)GETARG(wint_t); 1027 else 1028 *buf = (wchar_t)btowc_l(GETARG(int), loc); 1029 size = 1; 1030 #endif 1031 result = buf; 1032 sign = '\0'; 1033 break; 1034 case 'D': 1035 flags |= LONGINT; 1036 /*FALLTHROUGH*/ 1037 case 'd': 1038 case 'i': 1039 if (flags & INTMAX_SIZE) { 1040 ujval = SJARG(); 1041 if ((intmax_t)ujval < 0) { 1042 ujval = -ujval; 1043 sign = '-'; 1044 } 1045 } else { 1046 ulval = SARG(); 1047 if ((long)ulval < 0) { 1048 ulval = -ulval; 1049 sign = '-'; 1050 } 1051 } 1052 base = 10; 1053 goto number; 1054 #ifndef NO_FLOATING_POINT 1055 #ifdef WIDE_DOUBLE 1056 case 'a': 1057 case 'A': 1058 if (ch == 'a') { 1059 ox[1] = 'x'; 1060 xdigs = xdigs_lower; 1061 expchar = 'p'; 1062 } else { 1063 ox[1] = 'X'; 1064 xdigs = xdigs_upper; 1065 expchar = 'P'; 1066 } 1067 if (prec >= 0) 1068 prec++; 1069 if (flags & LONGDBL) { 1070 fparg.ldbl = GETARG(long double); 1071 dtoaresult = 1072 __hldtoa(fparg.ldbl, xdigs, prec, 1073 &expt, &signflag, &dtoaend); 1074 } else { 1075 fparg.dbl = GETARG(double); 1076 dtoaresult = 1077 __hdtoa(fparg.dbl, xdigs, prec, 1078 &expt, &signflag, &dtoaend); 1079 } 1080 if (dtoaresult == NULL) 1081 goto oomem; 1082 1083 if (prec < 0) { 1084 _DIAGASSERT(__type_fit(int, 1085 dtoaend - dtoaresult)); 1086 prec = (int)(dtoaend - dtoaresult); 1087 } 1088 if (expt == INT_MAX) 1089 ox[1] = '\0'; 1090 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1091 ndig = (int)(dtoaend - dtoaresult); 1092 if (convbuf != NULL) 1093 free(convbuf); 1094 #ifndef NARROW 1095 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1096 #else 1097 /*XXX inefficient*/ 1098 result = convbuf = strdup(dtoaresult); 1099 #endif 1100 if (result == NULL) 1101 goto oomem; 1102 __freedtoa(dtoaresult); 1103 goto fp_common; 1104 case 'e': 1105 case 'E': 1106 expchar = ch; 1107 if (prec < 0) /* account for digit before decpt */ 1108 prec = DEFPREC + 1; 1109 else 1110 prec++; 1111 goto fp_begin; 1112 case 'f': 1113 case 'F': 1114 expchar = '\0'; 1115 goto fp_begin; 1116 case 'g': 1117 case 'G': 1118 expchar = ch - ('g' - 'e'); 1119 if (prec == 0) 1120 prec = 1; 1121 fp_begin: 1122 if (prec < 0) 1123 prec = DEFPREC; 1124 if (flags & LONGDBL) { 1125 fparg.ldbl = GETARG(long double); 1126 dtoaresult = 1127 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 1128 &expt, &signflag, &dtoaend); 1129 } else { 1130 fparg.dbl = GETARG(double); 1131 dtoaresult = 1132 __dtoa(fparg.dbl, expchar ? 2 : 3, prec, 1133 &expt, &signflag, &dtoaend); 1134 if (expt == 9999) 1135 expt = INT_MAX; 1136 } 1137 if (dtoaresult == NULL) 1138 goto oomem; 1139 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1140 ndig = (int)(dtoaend - dtoaresult); 1141 if (convbuf != NULL) 1142 free(convbuf); 1143 #ifndef NARROW 1144 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1145 #else 1146 /*XXX inefficient*/ 1147 result = convbuf = strdup(dtoaresult); 1148 #endif 1149 if (result == NULL) 1150 goto oomem; 1151 __freedtoa(dtoaresult); 1152 fp_common: 1153 if (signflag) 1154 sign = '-'; 1155 if (expt == INT_MAX) { /* inf or nan */ 1156 if (*result == 'N') { 1157 result = (ch >= 'a') ? STRCONST("nan") : 1158 STRCONST("NAN"); 1159 sign = '\0'; 1160 } else 1161 result = (ch >= 'a') ? STRCONST("inf") : 1162 STRCONST("INF"); 1163 size = 3; 1164 flags &= ~ZEROPAD; 1165 break; 1166 } 1167 #else 1168 case 'e': 1169 case 'E': 1170 case 'f': 1171 case 'F': 1172 case 'g': 1173 case 'G': 1174 if (prec == -1) { 1175 prec = DEFPREC; 1176 } else if ((ch == 'g' || ch == 'G') && prec == 0) { 1177 prec = 1; 1178 } 1179 1180 if (flags & LONGDBL) { 1181 _double = (double) GETARG(long double); 1182 } else { 1183 _double = GETARG(double); 1184 } 1185 1186 /* do this before tricky precision changes */ 1187 if (isinf(_double)) { 1188 if (_double < 0) 1189 sign = '-'; 1190 if (ch == 'E' || ch == 'F' || ch == 'G') 1191 result = STRCONST("INF"); 1192 else 1193 result = STRCONST("inf"); 1194 size = 3; 1195 flags &= ~ZEROPAD; 1196 break; 1197 } 1198 if (isnan(_double)) { 1199 if (ch == 'E' || ch == 'F' || ch == 'G') 1200 result = STRCONST("NAN"); 1201 else 1202 result = STRCONST("nan"); 1203 size = 3; 1204 flags &= ~ZEROPAD; 1205 break; 1206 } 1207 1208 flags |= FPT; 1209 dtoaresult = cvt(_double, prec, flags, &softsign, 1210 &expt, ch, &ndig); 1211 if (dtoaresult == NULL) 1212 goto oomem; 1213 if (convbuf != NULL) 1214 free(convbuf); 1215 #ifndef NARROW 1216 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1217 #else 1218 /*XXX inefficient*/ 1219 result = convbuf = strdup(dtoaresult); 1220 #endif 1221 if (result == NULL) 1222 goto oomem; 1223 __freedtoa(dtoaresult); 1224 if (softsign) 1225 sign = '-'; 1226 #endif 1227 flags |= FPT; 1228 if (ch == 'g' || ch == 'G') { 1229 if (expt > -4 && expt <= prec) { 1230 /* Make %[gG] smell like %[fF] */ 1231 expchar = '\0'; 1232 if (flags & ALT) 1233 prec -= expt; 1234 else 1235 prec = ndig - expt; 1236 if (prec < 0) 1237 prec = 0; 1238 } else { 1239 /* 1240 * Make %[gG] smell like %[eE], but 1241 * trim trailing zeroes if no # flag. 1242 */ 1243 if (!(flags & ALT)) 1244 prec = ndig; 1245 } 1246 } 1247 if (expchar) { 1248 expsize = exponent(expstr, expt - 1, expchar); 1249 size = expsize + prec; 1250 if (prec > 1 || flags & ALT) 1251 ++size; 1252 } else { 1253 /* space for digits before decimal point */ 1254 if (expt > 0) 1255 size = expt; 1256 else /* "0" */ 1257 size = 1; 1258 /* space for decimal pt and following digits */ 1259 if (prec || flags & ALT) 1260 size += prec + 1; 1261 if (grouping && expt > 0) { 1262 /* space for thousands' grouping */ 1263 nseps = nrepeats = 0; 1264 lead = expt; 1265 while ((unsigned char)*grouping 1266 != (unsigned char)CHAR_MAX) { 1267 if (lead <= *grouping) 1268 break; 1269 lead -= *grouping; 1270 if (*(grouping+1)) { 1271 nseps++; 1272 grouping++; 1273 } else 1274 nrepeats++; 1275 } 1276 size += nseps + nrepeats; 1277 } else 1278 lead = expt; 1279 } 1280 break; 1281 #endif /* !NO_FLOATING_POINT */ 1282 case 'n': 1283 /* 1284 * Assignment-like behavior is specified if the 1285 * value overflows or is otherwise unrepresentable. 1286 * C99 says to use `signed char' for %hhn conversions. 1287 */ 1288 if (flags & LLONGINT) 1289 *GETARG(long long *) = ret; 1290 else if (flags & SIZET) 1291 *GETARG(ssize_t *) = (ssize_t)ret; 1292 else if (flags & PTRDIFFT) 1293 *GETARG(ptrdiff_t *) = ret; 1294 else if (flags & INTMAXT) 1295 *GETARG(intmax_t *) = ret; 1296 else if (flags & LONGINT) 1297 *GETARG(long *) = ret; 1298 else if (flags & SHORTINT) 1299 *GETARG(short *) = ret; 1300 else if (flags & CHARINT) 1301 *GETARG(signed char *) = ret; 1302 else 1303 *GETARG(int *) = ret; 1304 continue; /* no output */ 1305 case 'O': 1306 flags |= LONGINT; 1307 /*FALLTHROUGH*/ 1308 case 'o': 1309 if (flags & INTMAX_SIZE) 1310 ujval = UJARG(); 1311 else 1312 ulval = UARG(); 1313 base = 8; 1314 goto nosign; 1315 case 'p': 1316 /*- 1317 * ``The argument shall be a pointer to void. The 1318 * value of the pointer is converted to a sequence 1319 * of printable characters, in an implementation- 1320 * defined manner.'' 1321 * -- ANSI X3J11 1322 */ 1323 ujval = (uintmax_t)(uintptr_t)GETARG(void *); 1324 base = 16; 1325 xdigs = xdigs_lower; 1326 flags = flags | INTMAXT; 1327 ox[1] = 'x'; 1328 goto nosign; 1329 case 'S': 1330 flags |= LONGINT; 1331 /*FALLTHROUGH*/ 1332 case 's': 1333 if ((flags & LONGINT) != MULTI) { 1334 if ((result = GETARG(CHAR_T *)) == NULL) 1335 result = STRCONST("(null)"); 1336 } else { 1337 MCHAR_T *mc; 1338 1339 if (convbuf != NULL) 1340 free(convbuf); 1341 if ((mc = GETARG(MCHAR_T *)) == NULL) 1342 result = STRCONST("(null)"); 1343 else { 1344 convbuf = SCONV(mc, prec, loc); 1345 if (convbuf == NULL) { 1346 fp->_flags |= __SERR; 1347 goto error; 1348 } 1349 result = convbuf; 1350 } 1351 } 1352 1353 if (prec >= 0) { 1354 /* 1355 * can't use STRLEN; can only look for the 1356 * NUL in the first `prec' characters, and 1357 * STRLEN() will go further. 1358 */ 1359 CHAR_T *p = MEMCHR(result, 0, (size_t)prec); 1360 1361 if (p != NULL) { 1362 _DIAGASSERT(__type_fit(int, 1363 p - result)); 1364 size = (int)(p - result); 1365 if (size > prec) 1366 size = prec; 1367 } else 1368 size = prec; 1369 } else { 1370 size_t rlen = STRLEN(result); 1371 _DIAGASSERT(__type_fit(int, rlen)); 1372 size = (int)rlen; 1373 } 1374 sign = '\0'; 1375 break; 1376 case 'U': 1377 flags |= LONGINT; 1378 /*FALLTHROUGH*/ 1379 case 'u': 1380 if (flags & INTMAX_SIZE) 1381 ujval = UJARG(); 1382 else 1383 ulval = UARG(); 1384 base = 10; 1385 goto nosign; 1386 case 'X': 1387 xdigs = xdigs_upper; 1388 goto hex; 1389 case 'x': 1390 xdigs = xdigs_lower; 1391 hex: 1392 if (flags & INTMAX_SIZE) 1393 ujval = UJARG(); 1394 else 1395 ulval = UARG(); 1396 base = 16; 1397 /* leading 0x/X only if non-zero */ 1398 if (flags & ALT && 1399 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 1400 ox[1] = ch; 1401 1402 flags &= ~GROUPING; 1403 /* unsigned conversions */ 1404 nosign: sign = '\0'; 1405 /*- 1406 * ``... diouXx conversions ... if a precision is 1407 * specified, the 0 flag will be ignored.'' 1408 * -- ANSI X3J11 1409 */ 1410 number: if ((dprec = prec) >= 0) 1411 flags &= ~ZEROPAD; 1412 1413 /*- 1414 * ``The result of converting a zero value with an 1415 * explicit precision of zero is no characters.'' 1416 * -- ANSI X3J11 1417 * 1418 * ``The C Standard is clear enough as is. The call 1419 * printf("%#.0o", 0) should print 0.'' 1420 * -- Defect Report #151 1421 */ 1422 result = cp = buf + BUF; 1423 if (flags & INTMAX_SIZE) { 1424 if (ujval != 0 || prec != 0 || 1425 (flags & ALT && base == 8)) 1426 result = __ujtoa(ujval, cp, base, 1427 flags & ALT, xdigs, 1428 flags & GROUPING, thousands_sep, 1429 grouping); 1430 } else { 1431 if (ulval != 0 || prec != 0 || 1432 (flags & ALT && base == 8)) 1433 result = __ultoa(ulval, cp, base, 1434 flags & ALT, xdigs, 1435 flags & GROUPING, thousands_sep, 1436 grouping); 1437 } 1438 _DIAGASSERT(__type_fit(int, buf + BUF - result)); 1439 size = (int)(buf + BUF - result); 1440 if (size > BUF) /* should never happen */ 1441 abort(); 1442 break; 1443 default: /* "%?" prints ?, unless ? is NUL */ 1444 if (ch == '\0') 1445 goto done; 1446 /* pretend it was %c with argument ch */ 1447 *buf = ch; 1448 result = buf; 1449 size = 1; 1450 sign = '\0'; 1451 break; 1452 } 1453 1454 /* 1455 * All reasonable formats wind up here. At this point, `result' 1456 * points to a string which (if not flags&LADJUST) should be 1457 * padded out to `width' places. If flags&ZEROPAD, it should 1458 * first be prefixed by any sign or other prefix; otherwise, 1459 * it should be blank padded before the prefix is emitted. 1460 * After any left-hand padding and prefixing, emit zeroes 1461 * required by a decimal [diouxX] precision, then print the 1462 * string proper, then emit zeroes required by any leftover 1463 * floating precision; finally, if LADJUST, pad with blanks. 1464 * 1465 * Compute actual size, so we know how much to pad. 1466 * size excludes decimal prec; realsz includes it. 1467 */ 1468 realsz = dprec > size ? dprec : size; 1469 if (sign) 1470 realsz++; 1471 if (ox[1]) 1472 realsz += 2; 1473 1474 prsize = width > realsz ? width : realsz; 1475 if ((unsigned)ret + prsize > INT_MAX) { 1476 ret = END_OF_FILE; 1477 goto error; 1478 } 1479 1480 /* right-adjusting blank padding */ 1481 if ((flags & (LADJUST|ZEROPAD)) == 0) 1482 PAD(width - realsz, blanks); 1483 1484 /* prefix */ 1485 if (sign) 1486 PRINT(&sign, 1); 1487 1488 if (ox[1]) { /* ox[1] is either x, X, or \0 */ 1489 ox[0] = '0'; 1490 PRINT(ox, 2); 1491 } 1492 1493 /* right-adjusting zero padding */ 1494 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) 1495 PAD(width - realsz, zeroes); 1496 1497 /* leading zeroes from decimal precision */ 1498 PAD(dprec - size, zeroes); 1499 1500 /* the string or number proper */ 1501 #ifndef NO_FLOATING_POINT 1502 if ((flags & FPT) == 0) { 1503 PRINT(result, size); 1504 } else { /* glue together f_p fragments */ 1505 if (!expchar) { /* %[fF] or sufficiently short %[gG] */ 1506 if (expt <= 0) { 1507 PRINT(zeroes, 1); 1508 if (prec || flags & ALT) 1509 PRINT(decimal_point, 1); 1510 PAD(-expt, zeroes); 1511 /* already handled initial 0's */ 1512 prec += expt; 1513 } else { 1514 PRINTANDPAD(result, convbuf + ndig, 1515 lead, zeroes); 1516 result += lead; 1517 if (grouping) { 1518 while (nseps>0 || nrepeats>0) { 1519 if (nrepeats > 0) 1520 nrepeats--; 1521 else { 1522 grouping--; 1523 nseps--; 1524 } 1525 PRINT(&thousands_sep, 1526 1); 1527 PRINTANDPAD(result, 1528 convbuf + ndig, 1529 *grouping, zeroes); 1530 result += *grouping; 1531 } 1532 if (result > convbuf + ndig) 1533 result = convbuf + ndig; 1534 } 1535 if (prec || flags & ALT) { 1536 buf[0] = *decimal_point; 1537 PRINT(buf, 1); 1538 } 1539 } 1540 PRINTANDPAD(result, convbuf + ndig, prec, 1541 zeroes); 1542 } else { /* %[eE] or sufficiently long %[gG] */ 1543 if (prec > 1 || flags & ALT) { 1544 buf[0] = *result++; 1545 buf[1] = *decimal_point; 1546 PRINT(buf, 2); 1547 PRINT(result, ndig-1); 1548 PAD(prec - ndig, zeroes); 1549 } else /* XeYYY */ 1550 PRINT(result, 1); 1551 PRINT(expstr, expsize); 1552 } 1553 } 1554 #else 1555 PRINT(result, size); 1556 #endif 1557 /* left-adjusting padding (always blank) */ 1558 if (flags & LADJUST) 1559 PAD(width - realsz, blanks); 1560 1561 /* finally, adjust ret */ 1562 ret += prsize; 1563 FLUSH(); 1564 } 1565 done: 1566 FLUSH(); 1567 error: 1568 va_end(orgap); 1569 if (convbuf != NULL) 1570 free(convbuf); 1571 if (__sferror(fp)) 1572 ret = END_OF_FILE; 1573 if ((argtable != NULL) && (argtable != statargtable)) 1574 free (argtable); 1575 return ret; 1576 /* NOTREACHED */ 1577 oomem: 1578 errno = ENOMEM; 1579 ret = END_OF_FILE; 1580 goto error; 1581 } 1582 1583 /* 1584 * Find all arguments when a positional parameter is encountered. Returns a 1585 * table, indexed by argument number, of pointers to each arguments. The 1586 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries. 1587 * It will be replaces with a malloc-ed one if it overflows. 1588 */ 1589 static int 1590 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable) 1591 { 1592 CHAR_T *fmt; /* format string */ 1593 int ch; /* character from fmt */ 1594 size_t n, n2; /* handy index (short term usage) */ 1595 CHAR_T *cp; /* handy char pointer (short term usage) */ 1596 int flags; /* flags as above */ 1597 enum typeid *typetable; /* table of types */ 1598 enum typeid stattypetable [STATIC_ARG_TBL_SIZE]; 1599 size_t tablesize; /* current size of type table */ 1600 size_t tablemax; /* largest used index in table */ 1601 size_t nextarg; /* 1-based argument index */ 1602 size_t nitems; /* number of items we picked from the stack */ 1603 1604 /* 1605 * Add an argument type to the table, expanding if necessary. 1606 * Check for overflow. 1607 */ 1608 #define ADDTYPE(type) \ 1609 do { \ 1610 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \ 1611 if (typetable != stattypetable) \ 1612 free(typetable); \ 1613 return -1; \ 1614 } \ 1615 if (nextarg >= tablesize) \ 1616 if (__grow_type_table(nextarg, &typetable, \ 1617 &tablesize) == -1) \ 1618 return -1; \ 1619 if (nextarg > tablemax) \ 1620 tablemax = nextarg; \ 1621 typetable[nextarg++] = type; \ 1622 nitems++; \ 1623 } while (/*CONSTCOND*/0) 1624 1625 #define ADDSARG() \ 1626 do { \ 1627 if (flags & INTMAXT) \ 1628 ADDTYPE(T_INTMAXT); \ 1629 else if (flags & SIZET) \ 1630 ADDTYPE(T_SSIZET); \ 1631 else if (flags & PTRDIFFT) \ 1632 ADDTYPE(T_PTRDIFFT); \ 1633 else if (flags & LLONGINT) \ 1634 ADDTYPE(T_LLONG); \ 1635 else if (flags & LONGINT) \ 1636 ADDTYPE(T_LONG); \ 1637 else \ 1638 ADDTYPE(T_INT); \ 1639 } while (/*CONSTCOND*/0) 1640 1641 #define ADDUARG() \ 1642 do { \ 1643 if (flags & INTMAXT) \ 1644 ADDTYPE(T_UINTMAXT); \ 1645 else if (flags & SIZET) \ 1646 ADDTYPE(T_SIZET); \ 1647 else if (flags & PTRDIFFT) \ 1648 ADDTYPE(T_PTRDIFFT); \ 1649 else if (flags & LLONGINT) \ 1650 ADDTYPE(T_U_LLONG); \ 1651 else if (flags & LONGINT) \ 1652 ADDTYPE(T_U_LONG); \ 1653 else \ 1654 ADDTYPE(T_U_INT); \ 1655 } while (/*CONSTCOND*/0) 1656 /* 1657 * Add * arguments to the type array. 1658 */ 1659 #define ADDASTER() \ 1660 n2 = 0; \ 1661 cp = fmt; \ 1662 while (is_digit(*cp)) { \ 1663 n2 = 10 * n2 + to_digit(*cp); \ 1664 cp++; \ 1665 } \ 1666 if (*cp == '$') { \ 1667 size_t hold = nextarg; \ 1668 nextarg = n2; \ 1669 ADDTYPE(T_INT); \ 1670 nextarg = hold; \ 1671 fmt = ++cp; \ 1672 } else { \ 1673 ADDTYPE(T_INT); \ 1674 } 1675 fmt = (CHAR_T *)__UNCONST(fmt0); 1676 memset(stattypetable, 0, sizeof(stattypetable)); 1677 typetable = stattypetable; 1678 tablesize = STATIC_ARG_TBL_SIZE; 1679 tablemax = 0; 1680 nextarg = 1; 1681 nitems = 1; 1682 1683 /* 1684 * Scan the format for conversions (`%' character). 1685 */ 1686 for (;;) { 1687 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 1688 /* void */; 1689 if (ch == '\0') 1690 goto done; 1691 fmt++; /* skip over '%' */ 1692 1693 flags = 0; 1694 1695 rflag: ch = *fmt++; 1696 reswitch: switch (ch) { 1697 case ' ': 1698 case '#': 1699 goto rflag; 1700 case '*': 1701 ADDASTER (); 1702 goto rflag; 1703 case '-': 1704 case '+': 1705 case '\'': 1706 goto rflag; 1707 case '.': 1708 if ((ch = *fmt++) == '*') { 1709 ADDASTER (); 1710 goto rflag; 1711 } 1712 while (is_digit(ch)) { 1713 ch = *fmt++; 1714 } 1715 goto reswitch; 1716 case '0': 1717 goto rflag; 1718 case '1': case '2': case '3': case '4': 1719 case '5': case '6': case '7': case '8': case '9': 1720 n = 0; 1721 do { 1722 n = 10 * n + to_digit(ch); 1723 ch = *fmt++; 1724 } while (is_digit(ch)); 1725 if (ch == '$') { 1726 nextarg = n; 1727 goto rflag; 1728 } 1729 goto reswitch; 1730 #ifndef NO_FLOATING_POINT 1731 case 'L': 1732 flags |= LONGDBL; 1733 goto rflag; 1734 #endif 1735 case 'h': 1736 if (flags & SHORTINT) { 1737 flags &= ~SHORTINT; 1738 flags |= CHARINT; 1739 } else 1740 flags |= SHORTINT; 1741 goto rflag; 1742 case 'j': 1743 flags |= INTMAXT; 1744 goto rflag; 1745 case 'l': 1746 if (flags & LONGINT) { 1747 flags &= ~LONGINT; 1748 flags |= LLONGINT; 1749 } else 1750 flags |= LONGINT; 1751 goto rflag; 1752 case 'q': 1753 flags |= LLONGINT; /* not necessarily */ 1754 goto rflag; 1755 case 't': 1756 flags |= PTRDIFFT; 1757 goto rflag; 1758 case 'z': 1759 flags |= SIZET; 1760 goto rflag; 1761 case 'C': 1762 flags |= LONGINT; 1763 /*FALLTHROUGH*/ 1764 case 'c': 1765 if (flags & LONGINT) 1766 ADDTYPE(T_WINT); 1767 else 1768 ADDTYPE(T_INT); 1769 break; 1770 case 'D': 1771 flags |= LONGINT; 1772 /*FALLTHROUGH*/ 1773 case 'd': 1774 case 'i': 1775 ADDSARG(); 1776 break; 1777 #ifndef NO_FLOATING_POINT 1778 case 'a': 1779 case 'A': 1780 case 'e': 1781 case 'E': 1782 case 'f': 1783 case 'g': 1784 case 'G': 1785 if (flags & LONGDBL) 1786 ADDTYPE(T_LONG_DOUBLE); 1787 else 1788 ADDTYPE(T_DOUBLE); 1789 break; 1790 #endif /* !NO_FLOATING_POINT */ 1791 case 'n': 1792 if (flags & INTMAXT) 1793 ADDTYPE(TP_INTMAXT); 1794 else if (flags & PTRDIFFT) 1795 ADDTYPE(TP_PTRDIFFT); 1796 else if (flags & SIZET) 1797 ADDTYPE(TP_SIZET); 1798 else if (flags & LLONGINT) 1799 ADDTYPE(TP_LLONG); 1800 else if (flags & LONGINT) 1801 ADDTYPE(TP_LONG); 1802 else if (flags & SHORTINT) 1803 ADDTYPE(TP_SHORT); 1804 else if (flags & CHARINT) 1805 ADDTYPE(TP_SCHAR); 1806 else 1807 ADDTYPE(TP_INT); 1808 continue; /* no output */ 1809 case 'O': 1810 flags |= LONGINT; 1811 /*FALLTHROUGH*/ 1812 case 'o': 1813 ADDUARG(); 1814 break; 1815 case 'p': 1816 ADDTYPE(TP_VOID); 1817 break; 1818 case 'S': 1819 flags |= LONGINT; 1820 /*FALLTHROUGH*/ 1821 case 's': 1822 if (flags & LONGINT) 1823 ADDTYPE(TP_WCHAR); 1824 else 1825 ADDTYPE(TP_CHAR); 1826 break; 1827 case 'U': 1828 flags |= LONGINT; 1829 /*FALLTHROUGH*/ 1830 case 'u': 1831 case 'X': 1832 case 'x': 1833 ADDUARG(); 1834 break; 1835 default: /* "%?" prints ?, unless ? is NUL */ 1836 if (ch == '\0') 1837 goto done; 1838 break; 1839 } 1840 } 1841 done: 1842 /* 1843 * nitems contains the number of arguments we picked from the stack. 1844 * If tablemax is larger, this means that some positional argument, 1845 * tried to pick an argument the number of arguments possibly supplied. 1846 * Since positional arguments are typically used to swap the order of 1847 * the printf arguments and not to pick random arguments from strange 1848 * positions in the stack, we assume that if the positional argument 1849 * is trying to pick beyond the end of arguments, then this is wrong. 1850 * Alternatively we could find a way to figure out when va_arg() runs 1851 * out, but how to do that? 1852 */ 1853 if (nitems < tablemax) { 1854 if (typetable != stattypetable) 1855 free(typetable); 1856 return -1; 1857 } 1858 /* 1859 * Build the argument table. 1860 */ 1861 if (tablemax >= STATIC_ARG_TBL_SIZE) { 1862 *argtable = malloc(sizeof(**argtable) * (tablemax + 1)); 1863 if (*argtable == NULL) { 1864 free(typetable); 1865 return -1; 1866 } 1867 } 1868 1869 (*argtable) [0].intarg = 0; 1870 for (n = 1; n <= tablemax; n++) { 1871 switch (typetable [n]) { 1872 case T_UNUSED: /* whoops! */ 1873 (*argtable) [n].intarg = va_arg (ap, int); 1874 break; 1875 case TP_SCHAR: 1876 (*argtable) [n].pschararg = va_arg (ap, signed char *); 1877 break; 1878 case TP_SHORT: 1879 (*argtable) [n].pshortarg = va_arg (ap, short *); 1880 break; 1881 case T_INT: 1882 (*argtable) [n].intarg = va_arg (ap, int); 1883 break; 1884 case T_U_INT: 1885 (*argtable) [n].uintarg = va_arg (ap, unsigned int); 1886 break; 1887 case TP_INT: 1888 (*argtable) [n].pintarg = va_arg (ap, int *); 1889 break; 1890 case T_LONG: 1891 (*argtable) [n].longarg = va_arg (ap, long); 1892 break; 1893 case T_U_LONG: 1894 (*argtable) [n].ulongarg = va_arg (ap, unsigned long); 1895 break; 1896 case TP_LONG: 1897 (*argtable) [n].plongarg = va_arg (ap, long *); 1898 break; 1899 case T_LLONG: 1900 (*argtable) [n].longlongarg = va_arg (ap, long long); 1901 break; 1902 case T_U_LLONG: 1903 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long); 1904 break; 1905 case TP_LLONG: 1906 (*argtable) [n].plonglongarg = va_arg (ap, long long *); 1907 break; 1908 case T_PTRDIFFT: 1909 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t); 1910 break; 1911 case TP_PTRDIFFT: 1912 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *); 1913 break; 1914 case T_SSIZET: 1915 (*argtable) [n].ssizearg = va_arg (ap, ssize_t); 1916 break; 1917 case T_SIZET: 1918 (*argtable) [n].sizearg = va_arg (ap, size_t); 1919 break; 1920 case TP_SIZET: 1921 (*argtable) [n].psizearg = va_arg (ap, size_t *); 1922 break; 1923 case T_INTMAXT: 1924 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t); 1925 break; 1926 case T_UINTMAXT: 1927 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t); 1928 break; 1929 case TP_INTMAXT: 1930 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *); 1931 break; 1932 case T_DOUBLE: 1933 #ifndef NO_FLOATING_POINT 1934 (*argtable) [n].doublearg = va_arg (ap, double); 1935 #endif 1936 break; 1937 case T_LONG_DOUBLE: 1938 #ifndef NO_FLOATING_POINT 1939 (*argtable) [n].longdoublearg = va_arg (ap, long double); 1940 #endif 1941 break; 1942 case TP_CHAR: 1943 (*argtable) [n].pchararg = va_arg (ap, char *); 1944 break; 1945 case TP_VOID: 1946 (*argtable) [n].pvoidarg = va_arg (ap, void *); 1947 break; 1948 case T_WINT: 1949 (*argtable) [n].wintarg = va_arg (ap, wint_t); 1950 break; 1951 case TP_WCHAR: 1952 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *); 1953 break; 1954 } 1955 } 1956 1957 if (typetable != stattypetable) 1958 free (typetable); 1959 return 0; 1960 } 1961 1962 /* 1963 * Increase the size of the type table. 1964 */ 1965 static int 1966 __grow_type_table (size_t nextarg, enum typeid **typetable, size_t *tablesize) 1967 { 1968 enum typeid *const oldtable = *typetable; 1969 const size_t oldsize = *tablesize; 1970 enum typeid *newtable; 1971 size_t newsize = oldsize * 2; 1972 1973 if (newsize < nextarg + 1) 1974 newsize = nextarg + 1; 1975 if (oldsize == STATIC_ARG_TBL_SIZE) { 1976 if ((newtable = malloc(newsize * sizeof(*newtable))) == NULL) 1977 return -1; 1978 memcpy(newtable, oldtable, oldsize * sizeof(*newtable)); 1979 } else { 1980 newtable = realloc(oldtable, newsize * sizeof(*newtable)); 1981 if (newtable == NULL) { 1982 free(oldtable); 1983 return -1; 1984 } 1985 } 1986 memset(&newtable[oldsize], 0, (newsize - oldsize) * sizeof(*newtable)); 1987 1988 *typetable = newtable; 1989 *tablesize = newsize; 1990 return 0; 1991 } 1992 1993 1994 #ifndef NO_FLOATING_POINT 1995 #ifndef WIDE_DOUBLE 1996 static char * 1997 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch, 1998 int *length) 1999 { 2000 int mode, dsgn; 2001 char *digits, *bp, *rve; 2002 2003 _DIAGASSERT(decpt != NULL); 2004 _DIAGASSERT(length != NULL); 2005 _DIAGASSERT(sign != NULL); 2006 2007 if (ch == 'f') { 2008 mode = 3; /* ndigits after the decimal point */ 2009 } else { 2010 /* To obtain ndigits after the decimal point for the 'e' 2011 * and 'E' formats, round to ndigits + 1 significant 2012 * figures. 2013 */ 2014 if (ch == 'e' || ch == 'E') { 2015 ndigits++; 2016 } 2017 mode = 2; /* ndigits significant digits */ 2018 } 2019 2020 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve); 2021 if (digits == NULL) 2022 return NULL; 2023 if (dsgn) { 2024 value = -value; 2025 *sign = '-'; 2026 } else 2027 *sign = '\000'; 2028 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */ 2029 bp = digits + ndigits; 2030 if (ch == 'f') { 2031 if (*digits == '0' && value) 2032 *decpt = -ndigits + 1; 2033 bp += *decpt; 2034 } 2035 if (value == 0) /* kludge for __dtoa irregularity */ 2036 rve = bp; 2037 while (rve < bp) 2038 *rve++ = '0'; 2039 } 2040 *length = rve - digits; 2041 return digits; 2042 } 2043 #endif 2044 2045 static int 2046 exponent(CHAR_T *p0, int expo, int fmtch) 2047 { 2048 CHAR_T *p, *t; 2049 CHAR_T expbuf[MAXEXPDIG]; 2050 2051 p = p0; 2052 *p++ = fmtch; 2053 if (expo < 0) { 2054 expo = -expo; 2055 *p++ = '-'; 2056 } 2057 else 2058 *p++ = '+'; 2059 t = expbuf + MAXEXPDIG; 2060 if (expo > 9) { 2061 do { 2062 *--t = to_char(expo % 10); 2063 } while ((expo /= 10) > 9); 2064 *--t = to_char(expo); 2065 for (; t < expbuf + MAXEXPDIG; *p++ = *t++); 2066 } 2067 else { 2068 /* 2069 * Exponents for decimal floating point conversions 2070 * (%[eEgG]) must be at least two characters long, 2071 * whereas exponents for hexadecimal conversions can 2072 * be only one character long. 2073 */ 2074 if (fmtch == 'e' || fmtch == 'E') 2075 *p++ = '0'; 2076 *p++ = to_char(expo); 2077 } 2078 _DIAGASSERT(__type_fit(int, p - p0)); 2079 return (int)(p - p0); 2080 } 2081 #endif /* !NO_FLOATING_POINT */ 2082