1 /* $NetBSD: vfwprintf.c,v 1.31 2013/04/19 15:22:25 joerg 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.31 2013/04/19 15:22:25 joerg 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 if (loc == NULL) 709 loc = _C_locale; 710 711 /* 712 * BEWARE, these `goto error' on error, PRINT uses `n2' and 713 * PAD uses `n'. 714 */ 715 #ifndef NARROW 716 #define PRINT(ptr, len) do { \ 717 for (n3 = 0; n3 < (len); n3++) \ 718 __xfputwc((ptr)[n3], fp, loc); \ 719 } while (/*CONSTCOND*/0) 720 #define FLUSH() 721 #else 722 #define PRINT(ptr, len) do { \ 723 iovp->iov_base = __UNCONST(ptr); \ 724 iovp->iov_len = (len); \ 725 uio.uio_resid += (len); \ 726 iovp++; \ 727 if (++uio.uio_iovcnt >= NIOV) { \ 728 if (__sprint(fp, &uio)) \ 729 goto error; \ 730 iovp = iov; \ 731 } \ 732 } while (/*CONSTCOND*/0) 733 #define FLUSH() do { \ 734 if (uio.uio_resid && __sprint(fp, &uio)) \ 735 goto error; \ 736 uio.uio_iovcnt = 0; \ 737 iovp = iov; \ 738 } while (/*CONSTCOND*/0) 739 #endif /* NARROW */ 740 741 #define PAD(howmany, with) do { \ 742 if ((n = (howmany)) > 0) { \ 743 while (n > PADSIZE) { \ 744 PRINT(with, PADSIZE); \ 745 n -= PADSIZE; \ 746 } \ 747 PRINT(with, n); \ 748 } \ 749 } while (/*CONSTCOND*/0) 750 #define PRINTANDPAD(p, ep, len, with) do { \ 751 ptrdiff_t td = (ep) - (p); \ 752 _DIAGASSERT(__type_fit(int, td)); \ 753 n2 = (int)td; \ 754 if (n2 > (len)) \ 755 n2 = (len); \ 756 if (n2 > 0) \ 757 PRINT((p), n2); \ 758 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \ 759 } while(/*CONSTCOND*/0) 760 761 /* 762 * Get the argument indexed by nextarg. If the argument table is 763 * built, use it to get the argument. If its not, get the next 764 * argument (and arguments must be gotten sequentially). 765 */ 766 #define GETARG(type) \ 767 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \ 768 (nextarg++, va_arg(ap, type))) 769 770 /* 771 * To extend shorts properly, we need both signed and unsigned 772 * argument extraction methods. 773 */ 774 #define SARG() \ 775 (flags&LONGINT ? GETARG(long) : \ 776 flags&SHORTINT ? (long)(short)GETARG(int) : \ 777 flags&CHARINT ? (long)(signed char)GETARG(int) : \ 778 (long)GETARG(int)) 779 #define UARG() \ 780 (flags&LONGINT ? GETARG(u_long) : \ 781 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \ 782 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \ 783 (u_long)GETARG(u_int)) 784 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT) 785 #define SJARG() \ 786 (flags&INTMAXT ? GETARG(intmax_t) : \ 787 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \ 788 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \ 789 (intmax_t)GETARG(long long)) 790 #define UJARG() \ 791 (flags&INTMAXT ? GETARG(uintmax_t) : \ 792 flags&SIZET ? (uintmax_t)GETARG(size_t) : \ 793 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \ 794 (uintmax_t)GETARG(unsigned long long)) 795 796 /* 797 * Get * arguments, including the form *nn$. Preserve the nextarg 798 * that the argument can be gotten once the type is determined. 799 */ 800 #define GETASTER(val) \ 801 n2 = 0; \ 802 cp = fmt; \ 803 while (is_digit(*cp)) { \ 804 n2 = 10 * n2 + to_digit(*cp); \ 805 cp++; \ 806 } \ 807 if (*cp == '$') { \ 808 int hold = nextarg; \ 809 if (argtable == NULL) { \ 810 argtable = statargtable; \ 811 if (__find_arguments(fmt0, orgap, &argtable) == -1) \ 812 goto oomem; \ 813 } \ 814 nextarg = n2; \ 815 val = GETARG (int); \ 816 nextarg = hold; \ 817 fmt = ++cp; \ 818 } else { \ 819 val = GETARG (int); \ 820 } 821 822 _DIAGASSERT(fp != NULL); 823 _DIAGASSERT(fmt0 != NULL); 824 825 _SET_ORIENTATION(fp, -1); 826 827 ndig = -1; /* XXX gcc */ 828 829 thousands_sep = '\0'; 830 grouping = NULL; 831 #ifndef NO_FLOATING_POINT 832 decimal_point = localeconv_l(loc)->decimal_point; 833 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */ 834 #endif 835 convbuf = NULL; 836 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */ 837 if (cantwrite(fp)) { 838 errno = EBADF; 839 return END_OF_FILE; 840 } 841 842 /* optimise fprintf(stderr) (and other unbuffered Unix files) */ 843 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) && 844 __sfileno(fp) != -1) 845 return __sbprintf(fp, loc, fmt0, ap); 846 847 fmt = (CHAR_T *)__UNCONST(fmt0); 848 argtable = NULL; 849 nextarg = 1; 850 va_copy(orgap, ap); 851 #ifdef NARROW 852 uio.uio_iov = iovp = iov; 853 uio.uio_resid = 0; 854 uio.uio_iovcnt = 0; 855 #endif 856 ret = 0; 857 858 /* 859 * Scan the format for conversions (`%' character). 860 */ 861 for (;;) { 862 const CHAR_T *result; 863 864 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 865 continue; 866 _DIAGASSERT(__type_fit(int, fmt - cp)); 867 if ((n = (int)(fmt - cp)) != 0) { 868 if ((unsigned)ret + n > INT_MAX) { 869 ret = END_OF_FILE; 870 goto error; 871 } 872 PRINT(cp, n); 873 ret += n; 874 } 875 if (ch == '\0') 876 goto done; 877 fmt++; /* skip over '%' */ 878 879 flags = 0; 880 dprec = 0; 881 width = 0; 882 prec = -1; 883 sign = '\0'; 884 ox[1] = '\0'; 885 expchar = '\0'; 886 lead = 0; 887 nseps = nrepeats = 0; 888 ulval = 0; 889 ujval = 0; 890 xdigs = NULL; 891 892 rflag: ch = *fmt++; 893 reswitch: switch (ch) { 894 case ' ': 895 /*- 896 * ``If the space and + flags both appear, the space 897 * flag will be ignored.'' 898 * -- ANSI X3J11 899 */ 900 if (!sign) 901 sign = ' '; 902 goto rflag; 903 case '#': 904 flags |= ALT; 905 goto rflag; 906 case '*': 907 /*- 908 * ``A negative field width argument is taken as a 909 * - flag followed by a positive field width.'' 910 * -- ANSI X3J11 911 * They don't exclude field widths read from args. 912 */ 913 GETASTER (width); 914 if (width >= 0) 915 goto rflag; 916 width = -width; 917 /* FALLTHROUGH */ 918 case '-': 919 flags |= LADJUST; 920 goto rflag; 921 case '+': 922 sign = '+'; 923 goto rflag; 924 case '\'': 925 flags |= GROUPING; 926 thousands_sep = *(localeconv_l(loc)->thousands_sep); 927 grouping = localeconv_l(loc)->grouping; 928 /* If the locale doesn't define the above, use sane 929 * defaults - otherwise silly things happen! */ 930 if (thousands_sep == 0) 931 thousands_sep = ','; 932 if (!grouping || !*grouping) 933 grouping = "\3"; 934 goto rflag; 935 case '.': 936 if ((ch = *fmt++) == '*') { 937 GETASTER (prec); 938 goto rflag; 939 } 940 prec = 0; 941 while (is_digit(ch)) { 942 prec = 10 * prec + to_digit(ch); 943 ch = *fmt++; 944 } 945 goto reswitch; 946 case '0': 947 /*- 948 * ``Note that 0 is taken as a flag, not as the 949 * beginning of a field width.'' 950 * -- ANSI X3J11 951 */ 952 flags |= ZEROPAD; 953 goto rflag; 954 case '1': case '2': case '3': case '4': 955 case '5': case '6': case '7': case '8': case '9': 956 n = 0; 957 do { 958 n = 10 * n + to_digit(ch); 959 ch = *fmt++; 960 } while (is_digit(ch)); 961 if (ch == '$') { 962 nextarg = n; 963 if (argtable == NULL) { 964 argtable = statargtable; 965 if (__find_arguments(fmt0, orgap, 966 &argtable) == -1) 967 goto oomem; 968 } 969 goto rflag; 970 } 971 width = n; 972 goto reswitch; 973 #ifndef NO_FLOATING_POINT 974 case 'L': 975 flags |= LONGDBL; 976 goto rflag; 977 #endif 978 case 'h': 979 if (flags & SHORTINT) { 980 flags &= ~SHORTINT; 981 flags |= CHARINT; 982 } else 983 flags |= SHORTINT; 984 goto rflag; 985 case 'j': 986 flags |= INTMAXT; 987 goto rflag; 988 case 'l': 989 if (flags & LONGINT) { 990 flags &= ~LONGINT; 991 flags |= LLONGINT; 992 } else 993 flags |= LONGINT; 994 goto rflag; 995 case 'q': 996 flags |= LLONGINT; /* not necessarily */ 997 goto rflag; 998 case 't': 999 flags |= PTRDIFFT; 1000 goto rflag; 1001 case 'z': 1002 flags |= SIZET; 1003 goto rflag; 1004 case 'C': 1005 flags |= LONGINT; 1006 /*FALLTHROUGH*/ 1007 case 'c': 1008 #ifdef NARROW 1009 if (flags & LONGINT) { 1010 static const mbstate_t initial; 1011 mbstate_t mbs; 1012 size_t mbseqlen; 1013 1014 mbs = initial; 1015 mbseqlen = wcrtomb_l(buf, 1016 (wchar_t)GETARG(wint_t), &mbs, loc); 1017 if (mbseqlen == (size_t)-1) { 1018 fp->_flags |= __SERR; 1019 goto error; 1020 } 1021 size = (int)mbseqlen; 1022 } else { 1023 *buf = GETARG(int); 1024 size = 1; 1025 } 1026 #else 1027 if (flags & LONGINT) 1028 *buf = (wchar_t)GETARG(wint_t); 1029 else 1030 *buf = (wchar_t)btowc_l(GETARG(int), loc); 1031 size = 1; 1032 #endif 1033 result = buf; 1034 sign = '\0'; 1035 break; 1036 case 'D': 1037 flags |= LONGINT; 1038 /*FALLTHROUGH*/ 1039 case 'd': 1040 case 'i': 1041 if (flags & INTMAX_SIZE) { 1042 ujval = SJARG(); 1043 if ((intmax_t)ujval < 0) { 1044 ujval = -ujval; 1045 sign = '-'; 1046 } 1047 } else { 1048 ulval = SARG(); 1049 if ((long)ulval < 0) { 1050 ulval = -ulval; 1051 sign = '-'; 1052 } 1053 } 1054 base = 10; 1055 goto number; 1056 #ifndef NO_FLOATING_POINT 1057 #ifdef WIDE_DOUBLE 1058 case 'a': 1059 case 'A': 1060 if (ch == 'a') { 1061 ox[1] = 'x'; 1062 xdigs = xdigs_lower; 1063 expchar = 'p'; 1064 } else { 1065 ox[1] = 'X'; 1066 xdigs = xdigs_upper; 1067 expchar = 'P'; 1068 } 1069 if (prec >= 0) 1070 prec++; 1071 if (flags & LONGDBL) { 1072 fparg.ldbl = GETARG(long double); 1073 dtoaresult = 1074 __hldtoa(fparg.ldbl, xdigs, prec, 1075 &expt, &signflag, &dtoaend); 1076 } else { 1077 fparg.dbl = GETARG(double); 1078 dtoaresult = 1079 __hdtoa(fparg.dbl, xdigs, prec, 1080 &expt, &signflag, &dtoaend); 1081 } 1082 if (dtoaresult == NULL) 1083 goto oomem; 1084 1085 if (prec < 0) { 1086 _DIAGASSERT(__type_fit(int, 1087 dtoaend - dtoaresult)); 1088 prec = (int)(dtoaend - dtoaresult); 1089 } 1090 if (expt == INT_MAX) 1091 ox[1] = '\0'; 1092 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1093 ndig = (int)(dtoaend - dtoaresult); 1094 if (convbuf != NULL) 1095 free(convbuf); 1096 #ifndef NARROW 1097 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1098 #else 1099 /*XXX inefficient*/ 1100 result = convbuf = strdup(dtoaresult); 1101 #endif 1102 if (result == NULL) 1103 goto oomem; 1104 __freedtoa(dtoaresult); 1105 goto fp_common; 1106 case 'e': 1107 case 'E': 1108 expchar = ch; 1109 if (prec < 0) /* account for digit before decpt */ 1110 prec = DEFPREC + 1; 1111 else 1112 prec++; 1113 goto fp_begin; 1114 case 'f': 1115 case 'F': 1116 expchar = '\0'; 1117 goto fp_begin; 1118 case 'g': 1119 case 'G': 1120 expchar = ch - ('g' - 'e'); 1121 if (prec == 0) 1122 prec = 1; 1123 fp_begin: 1124 if (prec < 0) 1125 prec = DEFPREC; 1126 if (flags & LONGDBL) { 1127 fparg.ldbl = GETARG(long double); 1128 dtoaresult = 1129 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 1130 &expt, &signflag, &dtoaend); 1131 } else { 1132 fparg.dbl = GETARG(double); 1133 dtoaresult = 1134 __dtoa(fparg.dbl, expchar ? 2 : 3, prec, 1135 &expt, &signflag, &dtoaend); 1136 if (expt == 9999) 1137 expt = INT_MAX; 1138 } 1139 if (dtoaresult == NULL) 1140 goto oomem; 1141 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1142 ndig = (int)(dtoaend - dtoaresult); 1143 if (convbuf != NULL) 1144 free(convbuf); 1145 #ifndef NARROW 1146 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1147 #else 1148 /*XXX inefficient*/ 1149 result = convbuf = strdup(dtoaresult); 1150 #endif 1151 if (result == NULL) 1152 goto oomem; 1153 __freedtoa(dtoaresult); 1154 fp_common: 1155 if (signflag) 1156 sign = '-'; 1157 if (expt == INT_MAX) { /* inf or nan */ 1158 if (*result == 'N') { 1159 result = (ch >= 'a') ? STRCONST("nan") : 1160 STRCONST("NAN"); 1161 sign = '\0'; 1162 } else 1163 result = (ch >= 'a') ? STRCONST("inf") : 1164 STRCONST("INF"); 1165 size = 3; 1166 flags &= ~ZEROPAD; 1167 break; 1168 } 1169 #else 1170 case 'e': 1171 case 'E': 1172 case 'f': 1173 case 'F': 1174 case 'g': 1175 case 'G': 1176 if (prec == -1) { 1177 prec = DEFPREC; 1178 } else if ((ch == 'g' || ch == 'G') && prec == 0) { 1179 prec = 1; 1180 } 1181 1182 if (flags & LONGDBL) { 1183 _double = (double) GETARG(long double); 1184 } else { 1185 _double = GETARG(double); 1186 } 1187 1188 /* do this before tricky precision changes */ 1189 if (isinf(_double)) { 1190 if (_double < 0) 1191 sign = '-'; 1192 if (ch == 'E' || ch == 'F' || ch == 'G') 1193 result = STRCONST("INF"); 1194 else 1195 result = STRCONST("inf"); 1196 size = 3; 1197 flags &= ~ZEROPAD; 1198 break; 1199 } 1200 if (isnan(_double)) { 1201 if (ch == 'E' || ch == 'F' || ch == 'G') 1202 result = STRCONST("NAN"); 1203 else 1204 result = STRCONST("nan"); 1205 size = 3; 1206 flags &= ~ZEROPAD; 1207 break; 1208 } 1209 1210 flags |= FPT; 1211 dtoaresult = cvt(_double, prec, flags, &softsign, 1212 &expt, ch, &ndig); 1213 if (dtoaresult == NULL) 1214 goto oomem; 1215 if (convbuf != NULL) 1216 free(convbuf); 1217 #ifndef NARROW 1218 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1219 #else 1220 /*XXX inefficient*/ 1221 result = convbuf = strdup(dtoaresult); 1222 #endif 1223 if (result == NULL) 1224 goto oomem; 1225 __freedtoa(dtoaresult); 1226 if (softsign) 1227 sign = '-'; 1228 #endif 1229 flags |= FPT; 1230 if (ch == 'g' || ch == 'G') { 1231 if (expt > -4 && expt <= prec) { 1232 /* Make %[gG] smell like %[fF] */ 1233 expchar = '\0'; 1234 if (flags & ALT) 1235 prec -= expt; 1236 else 1237 prec = ndig - expt; 1238 if (prec < 0) 1239 prec = 0; 1240 } else { 1241 /* 1242 * Make %[gG] smell like %[eE], but 1243 * trim trailing zeroes if no # flag. 1244 */ 1245 if (!(flags & ALT)) 1246 prec = ndig; 1247 } 1248 } 1249 if (expchar) { 1250 expsize = exponent(expstr, expt - 1, expchar); 1251 size = expsize + prec; 1252 if (prec > 1 || flags & ALT) 1253 ++size; 1254 } else { 1255 /* space for digits before decimal point */ 1256 if (expt > 0) 1257 size = expt; 1258 else /* "0" */ 1259 size = 1; 1260 /* space for decimal pt and following digits */ 1261 if (prec || flags & ALT) 1262 size += prec + 1; 1263 if (grouping && expt > 0) { 1264 /* space for thousands' grouping */ 1265 nseps = nrepeats = 0; 1266 lead = expt; 1267 while ((unsigned char)*grouping 1268 != (unsigned char)CHAR_MAX) { 1269 if (lead <= *grouping) 1270 break; 1271 lead -= *grouping; 1272 if (*(grouping+1)) { 1273 nseps++; 1274 grouping++; 1275 } else 1276 nrepeats++; 1277 } 1278 size += nseps + nrepeats; 1279 } else 1280 lead = expt; 1281 } 1282 break; 1283 #endif /* !NO_FLOATING_POINT */ 1284 case 'n': 1285 /* 1286 * Assignment-like behavior is specified if the 1287 * value overflows or is otherwise unrepresentable. 1288 * C99 says to use `signed char' for %hhn conversions. 1289 */ 1290 if (flags & LLONGINT) 1291 *GETARG(long long *) = ret; 1292 else if (flags & SIZET) 1293 *GETARG(ssize_t *) = (ssize_t)ret; 1294 else if (flags & PTRDIFFT) 1295 *GETARG(ptrdiff_t *) = ret; 1296 else if (flags & INTMAXT) 1297 *GETARG(intmax_t *) = ret; 1298 else if (flags & LONGINT) 1299 *GETARG(long *) = ret; 1300 else if (flags & SHORTINT) 1301 *GETARG(short *) = ret; 1302 else if (flags & CHARINT) 1303 *GETARG(signed char *) = ret; 1304 else 1305 *GETARG(int *) = ret; 1306 continue; /* no output */ 1307 case 'O': 1308 flags |= LONGINT; 1309 /*FALLTHROUGH*/ 1310 case 'o': 1311 if (flags & INTMAX_SIZE) 1312 ujval = UJARG(); 1313 else 1314 ulval = UARG(); 1315 base = 8; 1316 goto nosign; 1317 case 'p': 1318 /*- 1319 * ``The argument shall be a pointer to void. The 1320 * value of the pointer is converted to a sequence 1321 * of printable characters, in an implementation- 1322 * defined manner.'' 1323 * -- ANSI X3J11 1324 */ 1325 ujval = (uintmax_t)(uintptr_t)GETARG(void *); 1326 base = 16; 1327 xdigs = xdigs_lower; 1328 flags = flags | INTMAXT; 1329 ox[1] = 'x'; 1330 goto nosign; 1331 case 'S': 1332 flags |= LONGINT; 1333 /*FALLTHROUGH*/ 1334 case 's': 1335 if ((flags & LONGINT) != MULTI) { 1336 if ((result = GETARG(CHAR_T *)) == NULL) 1337 result = STRCONST("(null)"); 1338 } else { 1339 MCHAR_T *mc; 1340 1341 if (convbuf != NULL) 1342 free(convbuf); 1343 if ((mc = GETARG(MCHAR_T *)) == NULL) 1344 result = STRCONST("(null)"); 1345 else { 1346 convbuf = SCONV(mc, prec, loc); 1347 if (convbuf == NULL) { 1348 fp->_flags |= __SERR; 1349 goto error; 1350 } 1351 result = convbuf; 1352 } 1353 } 1354 1355 if (prec >= 0) { 1356 /* 1357 * can't use STRLEN; can only look for the 1358 * NUL in the first `prec' characters, and 1359 * STRLEN() will go further. 1360 */ 1361 CHAR_T *p = MEMCHR(result, 0, (size_t)prec); 1362 1363 if (p != NULL) { 1364 _DIAGASSERT(__type_fit(int, 1365 p - result)); 1366 size = (int)(p - result); 1367 if (size > prec) 1368 size = prec; 1369 } else 1370 size = prec; 1371 } else { 1372 size_t rlen = STRLEN(result); 1373 _DIAGASSERT(__type_fit(int, rlen)); 1374 size = (int)rlen; 1375 } 1376 sign = '\0'; 1377 break; 1378 case 'U': 1379 flags |= LONGINT; 1380 /*FALLTHROUGH*/ 1381 case 'u': 1382 if (flags & INTMAX_SIZE) 1383 ujval = UJARG(); 1384 else 1385 ulval = UARG(); 1386 base = 10; 1387 goto nosign; 1388 case 'X': 1389 xdigs = xdigs_upper; 1390 goto hex; 1391 case 'x': 1392 xdigs = xdigs_lower; 1393 hex: 1394 if (flags & INTMAX_SIZE) 1395 ujval = UJARG(); 1396 else 1397 ulval = UARG(); 1398 base = 16; 1399 /* leading 0x/X only if non-zero */ 1400 if (flags & ALT && 1401 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 1402 ox[1] = ch; 1403 1404 flags &= ~GROUPING; 1405 /* unsigned conversions */ 1406 nosign: sign = '\0'; 1407 /*- 1408 * ``... diouXx conversions ... if a precision is 1409 * specified, the 0 flag will be ignored.'' 1410 * -- ANSI X3J11 1411 */ 1412 number: if ((dprec = prec) >= 0) 1413 flags &= ~ZEROPAD; 1414 1415 /*- 1416 * ``The result of converting a zero value with an 1417 * explicit precision of zero is no characters.'' 1418 * -- ANSI X3J11 1419 * 1420 * ``The C Standard is clear enough as is. The call 1421 * printf("%#.0o", 0) should print 0.'' 1422 * -- Defect Report #151 1423 */ 1424 result = cp = buf + BUF; 1425 if (flags & INTMAX_SIZE) { 1426 if (ujval != 0 || prec != 0 || 1427 (flags & ALT && base == 8)) 1428 result = __ujtoa(ujval, cp, base, 1429 flags & ALT, xdigs, 1430 flags & GROUPING, thousands_sep, 1431 grouping); 1432 } else { 1433 if (ulval != 0 || prec != 0 || 1434 (flags & ALT && base == 8)) 1435 result = __ultoa(ulval, cp, base, 1436 flags & ALT, xdigs, 1437 flags & GROUPING, thousands_sep, 1438 grouping); 1439 } 1440 _DIAGASSERT(__type_fit(int, buf + BUF - result)); 1441 size = (int)(buf + BUF - result); 1442 if (size > BUF) /* should never happen */ 1443 abort(); 1444 break; 1445 default: /* "%?" prints ?, unless ? is NUL */ 1446 if (ch == '\0') 1447 goto done; 1448 /* pretend it was %c with argument ch */ 1449 *buf = ch; 1450 result = buf; 1451 size = 1; 1452 sign = '\0'; 1453 break; 1454 } 1455 1456 /* 1457 * All reasonable formats wind up here. At this point, `result' 1458 * points to a string which (if not flags&LADJUST) should be 1459 * padded out to `width' places. If flags&ZEROPAD, it should 1460 * first be prefixed by any sign or other prefix; otherwise, 1461 * it should be blank padded before the prefix is emitted. 1462 * After any left-hand padding and prefixing, emit zeroes 1463 * required by a decimal [diouxX] precision, then print the 1464 * string proper, then emit zeroes required by any leftover 1465 * floating precision; finally, if LADJUST, pad with blanks. 1466 * 1467 * Compute actual size, so we know how much to pad. 1468 * size excludes decimal prec; realsz includes it. 1469 */ 1470 realsz = dprec > size ? dprec : size; 1471 if (sign) 1472 realsz++; 1473 if (ox[1]) 1474 realsz += 2; 1475 1476 prsize = width > realsz ? width : realsz; 1477 if ((unsigned)ret + prsize > INT_MAX) { 1478 ret = END_OF_FILE; 1479 goto error; 1480 } 1481 1482 /* right-adjusting blank padding */ 1483 if ((flags & (LADJUST|ZEROPAD)) == 0) 1484 PAD(width - realsz, blanks); 1485 1486 /* prefix */ 1487 if (sign) 1488 PRINT(&sign, 1); 1489 1490 if (ox[1]) { /* ox[1] is either x, X, or \0 */ 1491 ox[0] = '0'; 1492 PRINT(ox, 2); 1493 } 1494 1495 /* right-adjusting zero padding */ 1496 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) 1497 PAD(width - realsz, zeroes); 1498 1499 /* leading zeroes from decimal precision */ 1500 PAD(dprec - size, zeroes); 1501 1502 /* the string or number proper */ 1503 #ifndef NO_FLOATING_POINT 1504 if ((flags & FPT) == 0) { 1505 PRINT(result, size); 1506 } else { /* glue together f_p fragments */ 1507 if (!expchar) { /* %[fF] or sufficiently short %[gG] */ 1508 if (expt <= 0) { 1509 PRINT(zeroes, 1); 1510 if (prec || flags & ALT) 1511 PRINT(decimal_point, 1); 1512 PAD(-expt, zeroes); 1513 /* already handled initial 0's */ 1514 prec += expt; 1515 } else { 1516 PRINTANDPAD(result, convbuf + ndig, 1517 lead, zeroes); 1518 result += lead; 1519 if (grouping) { 1520 while (nseps>0 || nrepeats>0) { 1521 if (nrepeats > 0) 1522 nrepeats--; 1523 else { 1524 grouping--; 1525 nseps--; 1526 } 1527 PRINT(&thousands_sep, 1528 1); 1529 PRINTANDPAD(result, 1530 convbuf + ndig, 1531 *grouping, zeroes); 1532 result += *grouping; 1533 } 1534 if (result > convbuf + ndig) 1535 result = convbuf + ndig; 1536 } 1537 if (prec || flags & ALT) { 1538 buf[0] = *decimal_point; 1539 PRINT(buf, 1); 1540 } 1541 } 1542 PRINTANDPAD(result, convbuf + ndig, prec, 1543 zeroes); 1544 } else { /* %[eE] or sufficiently long %[gG] */ 1545 if (prec > 1 || flags & ALT) { 1546 buf[0] = *result++; 1547 buf[1] = *decimal_point; 1548 PRINT(buf, 2); 1549 PRINT(result, ndig-1); 1550 PAD(prec - ndig, zeroes); 1551 } else /* XeYYY */ 1552 PRINT(result, 1); 1553 PRINT(expstr, expsize); 1554 } 1555 } 1556 #else 1557 PRINT(result, size); 1558 #endif 1559 /* left-adjusting padding (always blank) */ 1560 if (flags & LADJUST) 1561 PAD(width - realsz, blanks); 1562 1563 /* finally, adjust ret */ 1564 ret += prsize; 1565 FLUSH(); 1566 } 1567 done: 1568 FLUSH(); 1569 error: 1570 va_end(orgap); 1571 if (convbuf != NULL) 1572 free(convbuf); 1573 if (__sferror(fp)) 1574 ret = END_OF_FILE; 1575 if ((argtable != NULL) && (argtable != statargtable)) 1576 free (argtable); 1577 return ret; 1578 /* NOTREACHED */ 1579 oomem: 1580 errno = ENOMEM; 1581 ret = END_OF_FILE; 1582 goto error; 1583 } 1584 1585 /* 1586 * Find all arguments when a positional parameter is encountered. Returns a 1587 * table, indexed by argument number, of pointers to each arguments. The 1588 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries. 1589 * It will be replaces with a malloc-ed one if it overflows. 1590 */ 1591 static int 1592 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable) 1593 { 1594 CHAR_T *fmt; /* format string */ 1595 int ch; /* character from fmt */ 1596 size_t n, n2; /* handy index (short term usage) */ 1597 CHAR_T *cp; /* handy char pointer (short term usage) */ 1598 int flags; /* flags as above */ 1599 enum typeid *typetable; /* table of types */ 1600 enum typeid stattypetable [STATIC_ARG_TBL_SIZE]; 1601 size_t tablesize; /* current size of type table */ 1602 size_t tablemax; /* largest used index in table */ 1603 size_t nextarg; /* 1-based argument index */ 1604 size_t nitems; /* number of items we picked from the stack */ 1605 1606 /* 1607 * Add an argument type to the table, expanding if necessary. 1608 * Check for overflow. 1609 */ 1610 #define ADDTYPE(type) \ 1611 do { \ 1612 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \ 1613 if (typetable != stattypetable) \ 1614 free(typetable); \ 1615 return -1; \ 1616 } \ 1617 if (nextarg >= tablesize) \ 1618 if (__grow_type_table(nextarg, &typetable, \ 1619 &tablesize) == -1) \ 1620 return -1; \ 1621 if (nextarg > tablemax) \ 1622 tablemax = nextarg; \ 1623 typetable[nextarg++] = type; \ 1624 nitems++; \ 1625 } while (/*CONSTCOND*/0) 1626 1627 #define ADDSARG() \ 1628 do { \ 1629 if (flags & INTMAXT) \ 1630 ADDTYPE(T_INTMAXT); \ 1631 else if (flags & SIZET) \ 1632 ADDTYPE(T_SSIZET); \ 1633 else if (flags & PTRDIFFT) \ 1634 ADDTYPE(T_PTRDIFFT); \ 1635 else if (flags & LLONGINT) \ 1636 ADDTYPE(T_LLONG); \ 1637 else if (flags & LONGINT) \ 1638 ADDTYPE(T_LONG); \ 1639 else \ 1640 ADDTYPE(T_INT); \ 1641 } while (/*CONSTCOND*/0) 1642 1643 #define ADDUARG() \ 1644 do { \ 1645 if (flags & INTMAXT) \ 1646 ADDTYPE(T_UINTMAXT); \ 1647 else if (flags & SIZET) \ 1648 ADDTYPE(T_SIZET); \ 1649 else if (flags & PTRDIFFT) \ 1650 ADDTYPE(T_PTRDIFFT); \ 1651 else if (flags & LLONGINT) \ 1652 ADDTYPE(T_U_LLONG); \ 1653 else if (flags & LONGINT) \ 1654 ADDTYPE(T_U_LONG); \ 1655 else \ 1656 ADDTYPE(T_U_INT); \ 1657 } while (/*CONSTCOND*/0) 1658 /* 1659 * Add * arguments to the type array. 1660 */ 1661 #define ADDASTER() \ 1662 n2 = 0; \ 1663 cp = fmt; \ 1664 while (is_digit(*cp)) { \ 1665 n2 = 10 * n2 + to_digit(*cp); \ 1666 cp++; \ 1667 } \ 1668 if (*cp == '$') { \ 1669 size_t hold = nextarg; \ 1670 nextarg = n2; \ 1671 ADDTYPE(T_INT); \ 1672 nextarg = hold; \ 1673 fmt = ++cp; \ 1674 } else { \ 1675 ADDTYPE(T_INT); \ 1676 } 1677 fmt = (CHAR_T *)__UNCONST(fmt0); 1678 memset(stattypetable, 0, sizeof(stattypetable)); 1679 typetable = stattypetable; 1680 tablesize = STATIC_ARG_TBL_SIZE; 1681 tablemax = 0; 1682 nextarg = 1; 1683 nitems = 1; 1684 1685 /* 1686 * Scan the format for conversions (`%' character). 1687 */ 1688 for (;;) { 1689 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 1690 /* void */; 1691 if (ch == '\0') 1692 goto done; 1693 fmt++; /* skip over '%' */ 1694 1695 flags = 0; 1696 1697 rflag: ch = *fmt++; 1698 reswitch: switch (ch) { 1699 case ' ': 1700 case '#': 1701 goto rflag; 1702 case '*': 1703 ADDASTER (); 1704 goto rflag; 1705 case '-': 1706 case '+': 1707 case '\'': 1708 goto rflag; 1709 case '.': 1710 if ((ch = *fmt++) == '*') { 1711 ADDASTER (); 1712 goto rflag; 1713 } 1714 while (is_digit(ch)) { 1715 ch = *fmt++; 1716 } 1717 goto reswitch; 1718 case '0': 1719 goto rflag; 1720 case '1': case '2': case '3': case '4': 1721 case '5': case '6': case '7': case '8': case '9': 1722 n = 0; 1723 do { 1724 n = 10 * n + to_digit(ch); 1725 ch = *fmt++; 1726 } while (is_digit(ch)); 1727 if (ch == '$') { 1728 nextarg = n; 1729 goto rflag; 1730 } 1731 goto reswitch; 1732 #ifndef NO_FLOATING_POINT 1733 case 'L': 1734 flags |= LONGDBL; 1735 goto rflag; 1736 #endif 1737 case 'h': 1738 if (flags & SHORTINT) { 1739 flags &= ~SHORTINT; 1740 flags |= CHARINT; 1741 } else 1742 flags |= SHORTINT; 1743 goto rflag; 1744 case 'j': 1745 flags |= INTMAXT; 1746 goto rflag; 1747 case 'l': 1748 if (flags & LONGINT) { 1749 flags &= ~LONGINT; 1750 flags |= LLONGINT; 1751 } else 1752 flags |= LONGINT; 1753 goto rflag; 1754 case 'q': 1755 flags |= LLONGINT; /* not necessarily */ 1756 goto rflag; 1757 case 't': 1758 flags |= PTRDIFFT; 1759 goto rflag; 1760 case 'z': 1761 flags |= SIZET; 1762 goto rflag; 1763 case 'C': 1764 flags |= LONGINT; 1765 /*FALLTHROUGH*/ 1766 case 'c': 1767 if (flags & LONGINT) 1768 ADDTYPE(T_WINT); 1769 else 1770 ADDTYPE(T_INT); 1771 break; 1772 case 'D': 1773 flags |= LONGINT; 1774 /*FALLTHROUGH*/ 1775 case 'd': 1776 case 'i': 1777 ADDSARG(); 1778 break; 1779 #ifndef NO_FLOATING_POINT 1780 case 'a': 1781 case 'A': 1782 case 'e': 1783 case 'E': 1784 case 'f': 1785 case 'g': 1786 case 'G': 1787 if (flags & LONGDBL) 1788 ADDTYPE(T_LONG_DOUBLE); 1789 else 1790 ADDTYPE(T_DOUBLE); 1791 break; 1792 #endif /* !NO_FLOATING_POINT */ 1793 case 'n': 1794 if (flags & INTMAXT) 1795 ADDTYPE(TP_INTMAXT); 1796 else if (flags & PTRDIFFT) 1797 ADDTYPE(TP_PTRDIFFT); 1798 else if (flags & SIZET) 1799 ADDTYPE(TP_SIZET); 1800 else if (flags & LLONGINT) 1801 ADDTYPE(TP_LLONG); 1802 else if (flags & LONGINT) 1803 ADDTYPE(TP_LONG); 1804 else if (flags & SHORTINT) 1805 ADDTYPE(TP_SHORT); 1806 else if (flags & CHARINT) 1807 ADDTYPE(TP_SCHAR); 1808 else 1809 ADDTYPE(TP_INT); 1810 continue; /* no output */ 1811 case 'O': 1812 flags |= LONGINT; 1813 /*FALLTHROUGH*/ 1814 case 'o': 1815 ADDUARG(); 1816 break; 1817 case 'p': 1818 ADDTYPE(TP_VOID); 1819 break; 1820 case 'S': 1821 flags |= LONGINT; 1822 /*FALLTHROUGH*/ 1823 case 's': 1824 if (flags & LONGINT) 1825 ADDTYPE(TP_WCHAR); 1826 else 1827 ADDTYPE(TP_CHAR); 1828 break; 1829 case 'U': 1830 flags |= LONGINT; 1831 /*FALLTHROUGH*/ 1832 case 'u': 1833 case 'X': 1834 case 'x': 1835 ADDUARG(); 1836 break; 1837 default: /* "%?" prints ?, unless ? is NUL */ 1838 if (ch == '\0') 1839 goto done; 1840 break; 1841 } 1842 } 1843 done: 1844 /* 1845 * nitems contains the number of arguments we picked from the stack. 1846 * If tablemax is larger, this means that some positional argument, 1847 * tried to pick an argument the number of arguments possibly supplied. 1848 * Since positional arguments are typically used to swap the order of 1849 * the printf arguments and not to pick random arguments from strange 1850 * positions in the stack, we assume that if the positional argument 1851 * is trying to pick beyond the end of arguments, then this is wrong. 1852 * Alternatively we could find a way to figure out when va_arg() runs 1853 * out, but how to do that? 1854 */ 1855 if (nitems < tablemax) { 1856 if (typetable != stattypetable) 1857 free(typetable); 1858 return -1; 1859 } 1860 /* 1861 * Build the argument table. 1862 */ 1863 if (tablemax >= STATIC_ARG_TBL_SIZE) { 1864 *argtable = malloc(sizeof(**argtable) * (tablemax + 1)); 1865 if (*argtable == NULL) { 1866 free(typetable); 1867 return -1; 1868 } 1869 } 1870 1871 (*argtable) [0].intarg = 0; 1872 for (n = 1; n <= tablemax; n++) { 1873 switch (typetable [n]) { 1874 case T_UNUSED: /* whoops! */ 1875 (*argtable) [n].intarg = va_arg (ap, int); 1876 break; 1877 case TP_SCHAR: 1878 (*argtable) [n].pschararg = va_arg (ap, signed char *); 1879 break; 1880 case TP_SHORT: 1881 (*argtable) [n].pshortarg = va_arg (ap, short *); 1882 break; 1883 case T_INT: 1884 (*argtable) [n].intarg = va_arg (ap, int); 1885 break; 1886 case T_U_INT: 1887 (*argtable) [n].uintarg = va_arg (ap, unsigned int); 1888 break; 1889 case TP_INT: 1890 (*argtable) [n].pintarg = va_arg (ap, int *); 1891 break; 1892 case T_LONG: 1893 (*argtable) [n].longarg = va_arg (ap, long); 1894 break; 1895 case T_U_LONG: 1896 (*argtable) [n].ulongarg = va_arg (ap, unsigned long); 1897 break; 1898 case TP_LONG: 1899 (*argtable) [n].plongarg = va_arg (ap, long *); 1900 break; 1901 case T_LLONG: 1902 (*argtable) [n].longlongarg = va_arg (ap, long long); 1903 break; 1904 case T_U_LLONG: 1905 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long); 1906 break; 1907 case TP_LLONG: 1908 (*argtable) [n].plonglongarg = va_arg (ap, long long *); 1909 break; 1910 case T_PTRDIFFT: 1911 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t); 1912 break; 1913 case TP_PTRDIFFT: 1914 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *); 1915 break; 1916 case T_SSIZET: 1917 (*argtable) [n].ssizearg = va_arg (ap, ssize_t); 1918 break; 1919 case T_SIZET: 1920 (*argtable) [n].sizearg = va_arg (ap, size_t); 1921 break; 1922 case TP_SIZET: 1923 (*argtable) [n].psizearg = va_arg (ap, size_t *); 1924 break; 1925 case T_INTMAXT: 1926 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t); 1927 break; 1928 case T_UINTMAXT: 1929 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t); 1930 break; 1931 case TP_INTMAXT: 1932 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *); 1933 break; 1934 case T_DOUBLE: 1935 #ifndef NO_FLOATING_POINT 1936 (*argtable) [n].doublearg = va_arg (ap, double); 1937 #endif 1938 break; 1939 case T_LONG_DOUBLE: 1940 #ifndef NO_FLOATING_POINT 1941 (*argtable) [n].longdoublearg = va_arg (ap, long double); 1942 #endif 1943 break; 1944 case TP_CHAR: 1945 (*argtable) [n].pchararg = va_arg (ap, char *); 1946 break; 1947 case TP_VOID: 1948 (*argtable) [n].pvoidarg = va_arg (ap, void *); 1949 break; 1950 case T_WINT: 1951 (*argtable) [n].wintarg = va_arg (ap, wint_t); 1952 break; 1953 case TP_WCHAR: 1954 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *); 1955 break; 1956 } 1957 } 1958 1959 if (typetable != stattypetable) 1960 free (typetable); 1961 return 0; 1962 } 1963 1964 /* 1965 * Increase the size of the type table. 1966 */ 1967 static int 1968 __grow_type_table (size_t nextarg, enum typeid **typetable, size_t *tablesize) 1969 { 1970 enum typeid *const oldtable = *typetable; 1971 const size_t oldsize = *tablesize; 1972 enum typeid *newtable; 1973 size_t newsize = oldsize * 2; 1974 1975 if (newsize < nextarg + 1) 1976 newsize = nextarg + 1; 1977 if (oldsize == STATIC_ARG_TBL_SIZE) { 1978 if ((newtable = malloc(newsize * sizeof(*newtable))) == NULL) 1979 return -1; 1980 memcpy(newtable, oldtable, oldsize * sizeof(*newtable)); 1981 } else { 1982 newtable = realloc(oldtable, newsize * sizeof(*newtable)); 1983 if (newtable == NULL) { 1984 free(oldtable); 1985 return -1; 1986 } 1987 } 1988 memset(&newtable[oldsize], 0, (newsize - oldsize) * sizeof(*newtable)); 1989 1990 *typetable = newtable; 1991 *tablesize = newsize; 1992 return 0; 1993 } 1994 1995 1996 #ifndef NO_FLOATING_POINT 1997 #ifndef WIDE_DOUBLE 1998 static char * 1999 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch, 2000 int *length) 2001 { 2002 int mode, dsgn; 2003 char *digits, *bp, *rve; 2004 2005 _DIAGASSERT(decpt != NULL); 2006 _DIAGASSERT(length != NULL); 2007 _DIAGASSERT(sign != NULL); 2008 2009 if (ch == 'f') { 2010 mode = 3; /* ndigits after the decimal point */ 2011 } else { 2012 /* To obtain ndigits after the decimal point for the 'e' 2013 * and 'E' formats, round to ndigits + 1 significant 2014 * figures. 2015 */ 2016 if (ch == 'e' || ch == 'E') { 2017 ndigits++; 2018 } 2019 mode = 2; /* ndigits significant digits */ 2020 } 2021 2022 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve); 2023 if (digits == NULL) 2024 return NULL; 2025 if (dsgn) { 2026 value = -value; 2027 *sign = '-'; 2028 } else 2029 *sign = '\000'; 2030 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */ 2031 bp = digits + ndigits; 2032 if (ch == 'f') { 2033 if (*digits == '0' && value) 2034 *decpt = -ndigits + 1; 2035 bp += *decpt; 2036 } 2037 if (value == 0) /* kludge for __dtoa irregularity */ 2038 rve = bp; 2039 while (rve < bp) 2040 *rve++ = '0'; 2041 } 2042 *length = rve - digits; 2043 return digits; 2044 } 2045 #endif 2046 2047 static int 2048 exponent(CHAR_T *p0, int expo, int fmtch) 2049 { 2050 CHAR_T *p, *t; 2051 CHAR_T expbuf[MAXEXPDIG]; 2052 2053 p = p0; 2054 *p++ = fmtch; 2055 if (expo < 0) { 2056 expo = -expo; 2057 *p++ = '-'; 2058 } 2059 else 2060 *p++ = '+'; 2061 t = expbuf + MAXEXPDIG; 2062 if (expo > 9) { 2063 do { 2064 *--t = to_char(expo % 10); 2065 } while ((expo /= 10) > 9); 2066 *--t = to_char(expo); 2067 for (; t < expbuf + MAXEXPDIG; *p++ = *t++); 2068 } 2069 else { 2070 /* 2071 * Exponents for decimal floating point conversions 2072 * (%[eEgG]) must be at least two characters long, 2073 * whereas exponents for hexadecimal conversions can 2074 * be only one character long. 2075 */ 2076 if (fmtch == 'e' || fmtch == 'E') 2077 *p++ = '0'; 2078 *p++ = to_char(expo); 2079 } 2080 _DIAGASSERT(__type_fit(int, p - p0)); 2081 return (int)(p - p0); 2082 } 2083 #endif /* !NO_FLOATING_POINT */ 2084