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