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