1 /* $NetBSD: vfwprintf.c,v 1.44 2026/10/29 05:47:37 kre 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.44 2026/10/29 05:47:37 kre 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; /* for inserting grouping separators */ 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 /* we enter here knowing that (initially) sval >= 10 */ 293 do { 294 /* 295 * If (*grp == CHAR_MAX) then no more grouping 296 * should be performed. 297 * Also: either needgrp == 0 || *grp != 0 298 */ 299 if (needgrp && ndig == *grp 300 && (unsigned char)*grp != (unsigned char)CHAR_MAX) { 301 cp -= needgrp; 302 memcpy(cp, thousep, needgrp); 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 313 ndig++; 314 *--cp = to_char(sval % 10); 315 sval /= 10; 316 } while (sval != 0); 317 break; 318 319 case 8: 320 do { 321 *--cp = to_char(val & 7); 322 val >>= 3; 323 } while (val); 324 if (octzero && *cp != '0') 325 *--cp = '0'; 326 break; 327 328 case 16: 329 do { 330 *--cp = xdigs[(size_t)val & 15]; 331 val >>= 4; 332 } while (val); 333 break; 334 335 default: /* oops */ 336 abort(); 337 } 338 return cp; 339 } 340 341 /* Identical to __ultoa, but for intmax_t. */ 342 static CHAR_T * 343 __ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero, 344 const char *xdigs, int needgrp, char *thousep, const char *grp) 345 { 346 CHAR_T *cp = endp; 347 intmax_t sval; 348 int ndig; 349 350 /* quick test for small values; __ultoa is typically much faster */ 351 /* (perhaps instead we should run until small, then call __ultoa?) */ 352 if (val <= ULONG_MAX) 353 return __ultoa((u_long)val, endp, base, octzero, xdigs, 354 needgrp, thousep, grp); 355 switch (base) { 356 case 10: 357 if (val < 10) { 358 *--cp = to_char(val % 10); 359 return cp; 360 } 361 ndig = 0; 362 if (val > INTMAX_MAX) { 363 ndig++; 364 *--cp = to_char(val % 10); 365 sval = val / 10; 366 } else 367 sval = val; 368 do { 369 /* 370 * If (*grp == CHAR_MAX) then no more grouping 371 * should be performed. 372 * note: if needgrp then *grp != 0 (always) 373 */ 374 if (needgrp && ndig == *grp 375 && (unsigned char)*grp != (unsigned char)CHAR_MAX) { 376 cp -= needgrp; 377 memcpy(cp, thousep, needgrp); 378 ndig = 0; 379 /* 380 * If (*(grp+1) == '\0') then we have to 381 * use *grp character (last grouping rule) 382 * for all next cases 383 */ 384 if (*(grp+1) != '\0') 385 grp++; 386 } 387 388 ndig++; 389 *--cp = to_char(sval % 10); 390 sval /= 10; 391 } while (sval != 0); 392 break; 393 394 case 8: 395 do { 396 *--cp = to_char(val & 7); 397 val >>= 3; 398 } while (val); 399 if (octzero && *cp != '0') 400 *--cp = '0'; 401 break; 402 403 case 16: 404 do { 405 *--cp = xdigs[(size_t)val & 15]; 406 val >>= 4; 407 } while (val); 408 break; 409 410 default: 411 abort(); 412 } 413 return cp; 414 } 415 416 #ifndef NARROW 417 /* 418 * Convert a multibyte character string argument for the %s format to a wide 419 * string representation. ``prec'' specifies the maximum number of bytes 420 * to output. If ``prec'' is greater than or equal to zero, we can't assume 421 * that the multibyte char. string ends in a null character. 422 */ 423 static wchar_t * 424 __mbsconv(char *mbsarg, int prec, locale_t loc) 425 { 426 static const mbstate_t initial; 427 mbstate_t mbs; 428 wchar_t *convbuf, *wcp; 429 const char *p; 430 size_t insize, nchars, nconv; 431 432 if (mbsarg == NULL) 433 return NULL; 434 435 /* 436 * Supplied argument is a multibyte string; convert it to wide 437 * characters first. 438 */ 439 if (prec >= 0) { 440 /* 441 * String is not guaranteed to be NUL-terminated. Find the 442 * number of characters to print. 443 */ 444 p = mbsarg; 445 insize = nchars = nconv = 0; 446 mbs = initial; 447 while (nchars != (size_t)prec) { 448 nconv = mbrlen_l(p, MB_CUR_MAX_L(loc), &mbs, loc); 449 if (nconv == 0 || nconv == (size_t)-1 || 450 nconv == (size_t)-2) 451 break; 452 p += nconv; 453 nchars++; 454 insize += nconv; 455 } 456 if (nconv == (size_t)-1 || nconv == (size_t)-2) 457 return NULL; 458 } else 459 insize = strlen(mbsarg); 460 461 /* 462 * Allocate buffer for the result and perform the conversion, 463 * converting at most `size' bytes of the input multibyte string to 464 * wide characters for printing. 465 */ 466 convbuf = NULL; 467 errno = reallocarr(&convbuf, insize + 1, sizeof(*convbuf)); 468 if (errno) 469 return NULL; 470 wcp = convbuf; 471 p = mbsarg; 472 mbs = initial; 473 nconv = 0; 474 while (insize != 0) { 475 nconv = mbrtowc_l(wcp, p, insize, &mbs, loc); 476 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2) 477 break; 478 wcp++; 479 p += nconv; 480 insize -= nconv; 481 } 482 if (nconv == (size_t)-1 || nconv == (size_t)-2) { 483 int serrno = errno; 484 free(convbuf); 485 errno = serrno; 486 return NULL; 487 } 488 *wcp = L'\0'; 489 490 return convbuf; 491 } 492 #else 493 /* 494 * Convert a wide-character string argument for the %ls format to a multibyte 495 * string representation. If not -1, prec specifies the maximum number of 496 * bytes to output, and also means that we can't assume that the wide-char. 497 * string ends is null-terminated. 498 */ 499 static char * 500 __wcsconv(wchar_t *wcsarg, int prec, locale_t loc) 501 { 502 static const mbstate_t initial; 503 mbstate_t mbs; 504 char buf[MB_LEN_MAX]; 505 wchar_t *p; 506 char *convbuf; 507 size_t clen, nbytes; 508 509 /* Allocate space for the maximum number of bytes we could output. */ 510 if (prec < 0) { 511 p = wcsarg; 512 mbs = initial; 513 nbytes = wcsrtombs_l(NULL, (void *)&p, 0, &mbs, loc); 514 if (nbytes == (size_t)-1) 515 return NULL; 516 } else { 517 /* 518 * Optimisation: if the output precision is small enough, 519 * just allocate enough memory for the maximum instead of 520 * scanning the string. 521 */ 522 if (prec < 128) 523 nbytes = prec; 524 else { 525 nbytes = 0; 526 p = wcsarg; 527 mbs = initial; 528 for (;;) { 529 clen = wcrtomb_l(buf, *p++, &mbs, loc); 530 if (clen == 0 || clen == (size_t)-1 || 531 nbytes + clen > (size_t)prec) 532 break; 533 nbytes += clen; 534 } 535 } 536 } 537 if ((convbuf = malloc(nbytes + 1)) == NULL) 538 return NULL; 539 540 /* Fill the output buffer. */ 541 p = wcsarg; 542 mbs = initial; 543 if ((nbytes = wcsrtombs_l(convbuf, (void *)&p, 544 nbytes, &mbs, loc)) == (size_t)-1) { 545 free(convbuf); 546 return NULL; 547 } 548 convbuf[nbytes] = '\0'; 549 return convbuf; 550 } 551 #endif 552 553 /* 554 * MT-safe version 555 */ 556 int 557 WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap) 558 { 559 int ret; 560 561 FLOCKFILE(fp); 562 ret = WDECL(__vf,printf_unlocked_l)(fp, _current_locale(), fmt0, ap); 563 FUNLOCKFILE(fp); 564 return ret; 565 } 566 567 int 568 WDECL(vf,printf_l)(FILE * __restrict fp, locale_t loc, const CHAR_T * __restrict fmt0, 569 va_list ap) 570 { 571 int ret; 572 573 FLOCKFILE(fp); 574 ret = WDECL(__vf,printf_unlocked_l)(fp, loc, fmt0, ap); 575 FUNLOCKFILE(fp); 576 return ret; 577 } 578 579 #ifndef NO_FLOATING_POINT 580 581 #include <float.h> 582 #include <math.h> 583 #include "floatio.h" 584 585 #define DEFPREC 6 586 587 static int exponent(CHAR_T *, int, int); 588 589 #endif /* !NO_FLOATING_POINT */ 590 591 /* 592 * The size of the buffer we use as scratch space for integer 593 * conversions, among other things. Technically, we would need the 594 * most space for base 10 conversions with thousands' grouping 595 * characters (up to 4 bytes ea) between each pair of digits. 596 * 240 bytes is a conservative overestimate even for a 128-bit uintmax_t. 597 */ 598 #define BUF 240 599 600 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */ 601 602 /* 603 * Flags used during conversion. 604 */ 605 #define ALT 0x001 /* alternate form */ 606 #define LADJUST 0x004 /* left adjustment */ 607 #define LONGDBL 0x008 /* long double */ 608 #define LONGINT 0x010 /* long integer */ 609 #define LLONGINT 0x020 /* long long integer */ 610 #define SHORTINT 0x040 /* short integer */ 611 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */ 612 #define FPT 0x100 /* Floating point number */ 613 #define GROUPING 0x200 /* use grouping ("'" flag) */ 614 /* C99 additional size modifiers: */ 615 #define SIZET 0x400 /* size_t */ 616 #define PTRDIFFT 0x800 /* ptrdiff_t */ 617 #define INTMAXT 0x1000 /* intmax_t */ 618 #define CHARINT 0x2000 /* print char using int format */ 619 620 /* 621 * Non-MT-safe version 622 */ 623 int 624 WDECL(__vf,printf_unlocked_l)(FILE *fp, locale_t loc, const CHAR_T *fmt0, va_list ap) 625 { 626 CHAR_T *fmt; /* format string */ 627 int ch; /* character from fmt */ 628 int n, n2; /* handy integer (short term usage) */ 629 CHAR_T *cp; /* handy char pointer (short term usage) */ 630 int flags; /* flags as above */ 631 int ret; /* return value accumulator */ 632 int width; /* width from format (%8d), or 0 */ 633 int prec; /* precision from format; <0 for N/A */ 634 CHAR_T sign; /* sign prefix (' ', '+', '-', or \0) */ 635 char *thousands_sep; /* locale specific thousands separator */ 636 int tsl; /* strlen(thousands_sep) */ 637 const char *grouping; /* locale specific numeric grouping rules */ 638 #ifndef NO_FLOATING_POINT 639 /* 640 * We can decompose the printed representation of floating 641 * point numbers into several parts, some of which may be empty: 642 * 643 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ 644 * A B ---C--- D E F 645 * 646 * A: 'sign' holds this value if present; '\0' otherwise 647 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal 648 * C: cp points to the string MMMNNN. Leading and trailing 649 * zeros are not in the string and must be added. 650 * D: expchar holds this character; '\0' if no exponent, e.g. %f 651 * F: at least two digits for decimal, at least one digit for hex 652 */ 653 char *decimal_point; /* locale specific decimal point */ 654 int decpt_len; /* length of decimal_point */ 655 int signflag; /* true if float is negative */ 656 union { /* floating point arguments %[aAeEfFgG] */ 657 double dbl; 658 #ifdef WIDE_DOUBLE 659 long double ldbl; 660 #endif 661 } fparg; 662 char *dtoaend; /* pointer to end of converted digits */ 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 = NULL; 831 tsl = 0; 832 grouping = NULL; 833 #ifndef NO_FLOATING_POINT 834 /* it might make sense to move all this to after the cantwrite test */ 835 decimal_point = localeconv_l(loc)->decimal_point; 836 if (decimal_point == NULL) /* should not happen */ 837 decimal_point = __UNCONST("."); /* XXX (or "" ?) */ 838 /* avoid calling strlen() in the common case its result is 1 */ 839 decpt_len = (decimal_point[0] != '\0' && decimal_point[1] == '\0') 840 ? 1 : (int)strlen(decimal_point); 841 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */ 842 ndig = -1; /* XXX gcc */ 843 #endif 844 convbuf = NULL; 845 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */ 846 if (cantwrite(fp)) { 847 errno = EBADF; 848 return END_OF_FILE; 849 } 850 851 /* optimise fprintf(stderr) (and other unbuffered Unix files) */ 852 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) && 853 __sfileno(fp) != -1) 854 return __sbprintf(fp, loc, fmt0, ap); 855 856 fmt = (CHAR_T *)__UNCONST(fmt0); 857 argtable = NULL; 858 nextarg = 1; 859 va_copy(orgap, ap); 860 #ifdef NARROW 861 uio.uio_iov = iovp = iov; 862 uio.uio_resid = 0; 863 uio.uio_iovcnt = 0; 864 #endif 865 ret = 0; 866 867 /* 868 * Scan the format for conversions (`%' character). 869 */ 870 for (;;) { 871 const CHAR_T *result; 872 873 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 874 continue; 875 _DIAGASSERT(__type_fit(int, fmt - cp)); 876 if ((n = (int)(fmt - cp)) != 0) { 877 if ((unsigned)ret + n > INT_MAX) { 878 ret = END_OF_FILE; 879 goto error; 880 } 881 PRINT(cp, n); 882 ret += n; 883 } 884 if (ch == '\0') 885 goto done; 886 fmt++; /* skip over '%' */ 887 888 flags = 0; 889 dprec = 0; 890 width = 0; 891 prec = -1; 892 sign = '\0'; 893 ox[1] = '\0'; 894 #ifndef NO_FLOATING_POINT 895 expchar = '\0'; 896 lead = 0; 897 nseps = nrepeats = 0; 898 #endif 899 ulval = 0; 900 ujval = 0; 901 xdigs = NULL; 902 903 rflag: ch = *fmt++; 904 reswitch: switch (ch) { 905 case ' ': 906 /*- 907 * ``If the space and + flags both appear, the space 908 * flag will be ignored.'' 909 * -- ANSI X3J11 910 */ 911 if (!sign) 912 sign = ' '; 913 goto rflag; 914 case '#': 915 flags |= ALT; 916 goto rflag; 917 case '*': 918 /*- 919 * ``A negative field width argument is taken as a 920 * - flag followed by a positive field width.'' 921 * -- ANSI X3J11 922 * They don't exclude field widths read from args. 923 */ 924 GETASTER (width); 925 if (width >= 0) 926 goto rflag; 927 width = -width; 928 /* FALLTHROUGH */ 929 case '-': 930 flags |= LADJUST; 931 goto rflag; 932 case '+': 933 sign = '+'; 934 goto rflag; 935 case '\'': 936 thousands_sep = localeconv_l(loc)->thousands_sep; 937 grouping = localeconv_l(loc)->grouping; 938 /* Use grouping if defined by locale */ 939 if (thousands_sep && *thousands_sep && grouping && 940 (int)*grouping > 0 && *grouping != CHAR_MAX) { 941 flags |= GROUPING; 942 if (thousands_sep[1] == '\0') 943 tsl = 1; 944 else { 945 tsl = (int)strlen(thousands_sep); 946 if (tsl > 4) /*XXX*/ 947 tsl = 0; 948 } 949 } else { 950 thousands_sep = NULL; 951 tsl = 0; 952 grouping = NULL; 953 } 954 goto rflag; 955 case '.': 956 if ((ch = *fmt++) == '*') { 957 GETASTER (prec); 958 goto rflag; 959 } 960 prec = 0; 961 while (is_digit(ch)) { 962 prec = 10 * prec + to_digit(ch); 963 ch = *fmt++; 964 } 965 goto reswitch; 966 case '0': 967 /*- 968 * ``Note that 0 is taken as a flag, not as the 969 * beginning of a field width.'' 970 * -- ANSI X3J11 971 */ 972 flags |= ZEROPAD; 973 goto rflag; 974 case '1': case '2': case '3': case '4': 975 case '5': case '6': case '7': case '8': case '9': 976 n = 0; 977 do { 978 n = 10 * n + to_digit(ch); 979 ch = *fmt++; 980 } while (is_digit(ch)); 981 if (ch == '$') { 982 nextarg = n; 983 if (argtable == NULL) { 984 argtable = statargtable; 985 if (__find_arguments(fmt0, orgap, 986 &argtable) == -1) 987 goto oomem; 988 } 989 goto rflag; 990 } 991 width = n; 992 goto reswitch; 993 #ifndef NO_FLOATING_POINT 994 case 'L': 995 flags |= LONGDBL; 996 goto rflag; 997 #endif 998 case 'h': 999 if (flags & SHORTINT) { 1000 flags &= ~SHORTINT; 1001 flags |= CHARINT; 1002 } else 1003 flags |= SHORTINT; 1004 goto rflag; 1005 case 'j': 1006 flags |= INTMAXT; 1007 goto rflag; 1008 case 'l': 1009 if (flags & LONGINT) { 1010 flags &= ~LONGINT; 1011 flags |= LLONGINT; 1012 } else 1013 flags |= LONGINT; 1014 goto rflag; 1015 case 'q': 1016 flags |= LLONGINT; /* not necessarily */ 1017 goto rflag; 1018 case 't': 1019 flags |= PTRDIFFT; 1020 goto rflag; 1021 case 'z': 1022 flags |= SIZET; 1023 goto rflag; 1024 case 'C': 1025 flags |= LONGINT; 1026 /*FALLTHROUGH*/ 1027 case 'c': 1028 #ifdef NARROW 1029 if (flags & LONGINT) { 1030 static const mbstate_t initial; 1031 mbstate_t mbs; 1032 size_t mbseqlen; 1033 1034 mbs = initial; 1035 mbseqlen = wcrtomb_l(buf, 1036 (wchar_t)GETARG(wint_t), &mbs, loc); 1037 if (mbseqlen == (size_t)-1) { 1038 fp->_flags |= __SERR; 1039 goto error; 1040 } 1041 size = (int)mbseqlen; 1042 } else { 1043 *buf = GETARG(int); 1044 size = 1; 1045 } 1046 #else 1047 if (flags & LONGINT) 1048 *buf = (wchar_t)GETARG(wint_t); 1049 else 1050 *buf = (wchar_t)btowc_l(GETARG(int), loc); 1051 size = 1; 1052 #endif 1053 result = buf; 1054 sign = '\0'; 1055 break; 1056 case 'D': 1057 flags |= LONGINT; 1058 /*FALLTHROUGH*/ 1059 case 'd': 1060 case 'i': 1061 if (flags & INTMAX_SIZE) { 1062 ujval = SJARG(); 1063 if ((intmax_t)ujval < 0) { 1064 ujval = -ujval; 1065 sign = '-'; 1066 } 1067 } else { 1068 ulval = SARG(); 1069 if ((long)ulval < 0) { 1070 ulval = -ulval; 1071 sign = '-'; 1072 } 1073 } 1074 base = 10; 1075 goto number; 1076 #ifndef NO_FLOATING_POINT 1077 case 'a': 1078 case 'A': 1079 if (ch == 'a') { 1080 ox[1] = 'x'; 1081 xdigs = xdigs_lower; 1082 expchar = 'p'; 1083 } else { 1084 ox[1] = 'X'; 1085 xdigs = xdigs_upper; 1086 expchar = 'P'; 1087 } 1088 if (prec >= 0) 1089 prec++; 1090 #ifdef WIDE_DOUBLE 1091 if (flags & LONGDBL) { 1092 fparg.ldbl = GETARG(long double); 1093 dtoaresult = 1094 __hldtoa(fparg.ldbl, xdigs, prec, 1095 &expt, &signflag, &dtoaend); 1096 } else 1097 #endif 1098 { 1099 fparg.dbl = GETARG(double); 1100 dtoaresult = 1101 __hdtoa(fparg.dbl, xdigs, prec, 1102 &expt, &signflag, &dtoaend); 1103 } 1104 if (dtoaresult == NULL) 1105 goto oomem; 1106 1107 if (prec < 0) { 1108 _DIAGASSERT(__type_fit(int, 1109 dtoaend - dtoaresult)); 1110 prec = (int)(dtoaend - dtoaresult); 1111 } 1112 if (expt == INT_MAX) 1113 ox[1] = '\0'; 1114 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1115 ndig = (int)(dtoaend - dtoaresult); 1116 if (convbuf != NULL) 1117 free(convbuf); 1118 #ifndef NARROW 1119 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1120 #else 1121 /*XXX inefficient*/ 1122 result = convbuf = strdup(dtoaresult); 1123 #endif 1124 if (result == NULL) 1125 goto oomem; 1126 __freedtoa(dtoaresult); 1127 goto fp_common; 1128 case 'e': 1129 case 'E': 1130 expchar = ch; 1131 if (prec < 0) /* account for digit before decpt */ 1132 prec = DEFPREC + 1; 1133 else 1134 prec++; 1135 goto fp_begin; 1136 case 'f': 1137 case 'F': 1138 expchar = '\0'; 1139 goto fp_begin; 1140 case 'g': 1141 case 'G': 1142 expchar = ch - ('g' - 'e'); 1143 if (prec == 0) 1144 prec = 1; 1145 fp_begin: 1146 if (prec < 0) 1147 prec = DEFPREC; 1148 #ifdef WIDE_DOUBLE 1149 if (flags & LONGDBL) { 1150 fparg.ldbl = GETARG(long double); 1151 dtoaresult = 1152 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, 1153 &expt, &signflag, &dtoaend); 1154 } else 1155 #endif 1156 { 1157 fparg.dbl = GETARG(double); 1158 dtoaresult = 1159 __dtoa(fparg.dbl, expchar ? 2 : 3, prec, 1160 &expt, &signflag, &dtoaend); 1161 if (expt == 9999) 1162 expt = INT_MAX; 1163 } 1164 if (dtoaresult == NULL) 1165 goto oomem; 1166 _DIAGASSERT(__type_fit(int, dtoaend - dtoaresult)); 1167 ndig = (int)(dtoaend - dtoaresult); 1168 if (convbuf != NULL) 1169 free(convbuf); 1170 #ifndef NARROW 1171 result = convbuf = __mbsconv(dtoaresult, -1, loc); 1172 #else 1173 /*XXX inefficient*/ 1174 result = convbuf = strdup(dtoaresult); 1175 #endif 1176 if (result == NULL) 1177 goto oomem; 1178 __freedtoa(dtoaresult); 1179 fp_common: 1180 if (signflag) 1181 sign = '-'; 1182 if (expt == INT_MAX) { /* inf or nan */ 1183 if (*result == 'N') { 1184 result = (ch >= 'a') ? STRCONST("nan") : 1185 STRCONST("NAN"); 1186 sign = '\0'; 1187 } else 1188 result = (ch >= 'a') ? STRCONST("inf") : 1189 STRCONST("INF"); 1190 size = 3; 1191 flags &= ~ZEROPAD; 1192 break; 1193 } 1194 1195 flags |= FPT; 1196 if (ch == 'g' || ch == 'G') { 1197 if (expt > -4 && expt <= prec) { 1198 /* Make %[gG] smell like %[fF] */ 1199 expchar = '\0'; 1200 if (flags & ALT) 1201 prec -= expt; 1202 else 1203 prec = ndig - expt; 1204 if (prec < 0) 1205 prec = 0; 1206 } else { 1207 /* 1208 * Make %[gG] smell like %[eE], but 1209 * trim trailing zeroes if no # flag. 1210 */ 1211 if (!(flags & ALT)) 1212 prec = ndig; 1213 } 1214 } 1215 if (expchar) { 1216 expsize = exponent(expstr, expt - 1, expchar); 1217 size = expsize + prec; 1218 if (prec > 1 || flags & ALT) 1219 size += decpt_len; 1220 } else { 1221 /* space for digits before decimal point */ 1222 if (expt > 0) 1223 size = expt; 1224 else /* "0" */ 1225 size = 1; 1226 /* space for decimal pt and following digits */ 1227 if (prec || flags & ALT) 1228 size += prec + decpt_len; 1229 if (grouping && expt > 0) { 1230 /* space for thousands' grouping */ 1231 nseps = nrepeats = 0; 1232 lead = expt; 1233 while ((unsigned char)*grouping 1234 != (unsigned char)CHAR_MAX) { 1235 if (lead <= *grouping) 1236 break; 1237 lead -= *grouping; 1238 if (*(grouping+1)) { 1239 nseps++; 1240 grouping++; 1241 } else 1242 nrepeats++; 1243 } 1244 size += (nseps + nrepeats) * tsl; 1245 } else 1246 lead = expt; 1247 } 1248 break; 1249 #endif /* !NO_FLOATING_POINT */ 1250 case 'n': 1251 /* 1252 * Assignment-like behavior is specified if the 1253 * value overflows or is otherwise unrepresentable. 1254 * C99 says to use `signed char' for %hhn conversions. 1255 */ 1256 if (flags & LLONGINT) 1257 *GETARG(long long *) = ret; 1258 else if (flags & SIZET) 1259 *GETARG(ssize_t *) = (ssize_t)ret; 1260 else if (flags & PTRDIFFT) 1261 *GETARG(ptrdiff_t *) = ret; 1262 else if (flags & INTMAXT) 1263 *GETARG(intmax_t *) = ret; 1264 else if (flags & LONGINT) 1265 *GETARG(long *) = ret; 1266 else if (flags & SHORTINT) 1267 *GETARG(short *) = ret; 1268 else if (flags & CHARINT) 1269 *GETARG(signed char *) = ret; 1270 else 1271 *GETARG(int *) = ret; 1272 continue; /* no output */ 1273 case 'O': 1274 flags |= LONGINT; 1275 /*FALLTHROUGH*/ 1276 case 'o': 1277 if (flags & INTMAX_SIZE) 1278 ujval = UJARG(); 1279 else 1280 ulval = UARG(); 1281 base = 8; 1282 goto nosign; 1283 case 'p': 1284 /*- 1285 * ``The argument shall be a pointer to void. The 1286 * value of the pointer is converted to a sequence 1287 * of printable characters, in an implementation- 1288 * defined manner.'' 1289 * -- ANSI X3J11 1290 */ 1291 ujval = (uintmax_t)(uintptr_t)GETARG(void *); 1292 base = 16; 1293 xdigs = xdigs_lower; 1294 flags = flags | INTMAXT; 1295 ox[1] = 'x'; 1296 goto nosign; 1297 case 'S': 1298 flags |= LONGINT; 1299 /*FALLTHROUGH*/ 1300 case 's': 1301 if ((flags & LONGINT) != MULTI) { 1302 if ((result = GETARG(CHAR_T *)) == NULL) 1303 result = STRCONST("(null)"); 1304 } else { 1305 MCHAR_T *mc; 1306 1307 if (convbuf != NULL) 1308 free(convbuf); 1309 if ((mc = GETARG(MCHAR_T *)) == NULL) 1310 result = STRCONST("(null)"); 1311 else { 1312 convbuf = SCONV(mc, prec, loc); 1313 if (convbuf == NULL) { 1314 fp->_flags |= __SERR; 1315 goto error; 1316 } 1317 result = convbuf; 1318 } 1319 } 1320 1321 if (prec >= 0) { 1322 /* 1323 * can't use STRLEN; can only look for the 1324 * NUL in the first `prec' characters, and 1325 * STRLEN() will go further. 1326 */ 1327 const CHAR_T *p = 1328 MEMCHR(result, 0, (size_t)prec); 1329 1330 if (p != NULL) { 1331 _DIAGASSERT(__type_fit(int, 1332 p - result)); 1333 size = (int)(p - result); 1334 if (size > prec) 1335 size = prec; 1336 } else 1337 size = prec; 1338 } else { 1339 size_t rlen = STRLEN(result); 1340 _DIAGASSERT(__type_fit(int, rlen)); 1341 size = (int)rlen; 1342 } 1343 sign = '\0'; 1344 break; 1345 case 'U': 1346 flags |= LONGINT; 1347 /*FALLTHROUGH*/ 1348 case 'u': 1349 if (flags & INTMAX_SIZE) 1350 ujval = UJARG(); 1351 else 1352 ulval = UARG(); 1353 base = 10; 1354 goto nosign; 1355 case 'X': 1356 xdigs = xdigs_upper; 1357 goto hex; 1358 case 'x': 1359 xdigs = xdigs_lower; 1360 hex: 1361 if (flags & INTMAX_SIZE) 1362 ujval = UJARG(); 1363 else 1364 ulval = UARG(); 1365 base = 16; 1366 /* leading 0x/X only if non-zero */ 1367 if (flags & ALT && 1368 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) 1369 ox[1] = ch; 1370 1371 flags &= ~GROUPING; 1372 /* unsigned conversions */ 1373 nosign: sign = '\0'; 1374 /*- 1375 * ``... diouXx conversions ... if a precision is 1376 * specified, the 0 flag will be ignored.'' 1377 * -- ANSI X3J11 1378 */ 1379 number: if ((dprec = prec) >= 0) 1380 flags &= ~ZEROPAD; 1381 1382 /*- 1383 * ``The result of converting a zero value with an 1384 * explicit precision of zero is no characters.'' 1385 * -- ANSI X3J11 1386 * 1387 * ``The C Standard is clear enough as is. The call 1388 * printf("%#.0o", 0) should print 0.'' 1389 * -- Defect Report #151 1390 */ 1391 result = cp = buf + BUF; 1392 if (flags & INTMAX_SIZE) { 1393 if (ujval != 0 || prec != 0 || 1394 (flags & ALT && base == 8)) 1395 result = __ujtoa(ujval, cp, base, 1396 flags & ALT, xdigs, 1397 ((flags & GROUPING) ? tsl : 0), 1398 thousands_sep, grouping); 1399 } else { 1400 if (ulval != 0 || prec != 0 || 1401 (flags & ALT && base == 8)) 1402 result = __ultoa(ulval, cp, base, 1403 flags & ALT, xdigs, 1404 ((flags & GROUPING) ? tsl : 0), 1405 thousands_sep, grouping); 1406 } 1407 _DIAGASSERT(__type_fit(int, buf + BUF - result)); 1408 size = (int)(buf + BUF - result); 1409 if (size > BUF) /* should never happen */ 1410 abort(); 1411 break; 1412 default: /* "%?" prints ?, unless ? is NUL */ 1413 if (ch == '\0') 1414 goto done; 1415 /* pretend it was %c with argument ch */ 1416 *buf = ch; 1417 result = buf; 1418 size = 1; 1419 sign = '\0'; 1420 break; 1421 } 1422 1423 /* 1424 * All reasonable formats wind up here. At this point, `result' 1425 * points to a string which (if not flags&LADJUST) should be 1426 * padded out to `width' places. If flags&ZEROPAD, it should 1427 * first be prefixed by any sign or other prefix; otherwise, 1428 * it should be blank padded before the prefix is emitted. 1429 * After any left-hand padding and prefixing, emit zeroes 1430 * required by a decimal [diouxX] precision, then print the 1431 * string proper, then emit zeroes required by any leftover 1432 * floating precision; finally, if LADJUST, pad with blanks. 1433 * 1434 * Compute actual size, so we know how much to pad. 1435 * size excludes decimal prec; realsz includes it. 1436 */ 1437 realsz = dprec > size ? dprec : size; 1438 if (sign) 1439 realsz++; 1440 if (ox[1]) 1441 realsz += 2; 1442 1443 prsize = width > realsz ? width : realsz; 1444 if ((unsigned)ret + prsize > INT_MAX) { 1445 ret = END_OF_FILE; 1446 goto error; 1447 } 1448 1449 /* right-adjusting blank padding */ 1450 if ((flags & (LADJUST|ZEROPAD)) == 0) 1451 PAD(width - realsz, blanks); 1452 1453 /* prefix */ 1454 if (sign) 1455 PRINT(&sign, 1); 1456 1457 if (ox[1]) { /* ox[1] is either x, X, or \0 */ 1458 ox[0] = '0'; 1459 PRINT(ox, 2); 1460 } 1461 1462 /* right-adjusting zero padding */ 1463 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) 1464 PAD(width - realsz, zeroes); 1465 1466 /* leading zeroes from decimal precision */ 1467 PAD(dprec - size, zeroes); 1468 1469 /* the string or number proper */ 1470 #ifndef NO_FLOATING_POINT 1471 if ((flags & FPT) == 0) { 1472 PRINT(result, size); 1473 } else { /* glue together f_p fragments */ 1474 if (!expchar) { /* %[fF] or sufficiently short %[gG] */ 1475 if (expt <= 0) { 1476 PRINT(zeroes, 1); 1477 if (prec || flags & ALT) 1478 PRINT(decimal_point, decpt_len); 1479 PAD(-expt, zeroes); 1480 /* already handled initial 0's */ 1481 prec += expt; 1482 } else { 1483 PRINTANDPAD(result, convbuf + ndig, 1484 lead, zeroes); 1485 result += lead; 1486 if (grouping) { 1487 while (nseps>0 || nrepeats>0) { 1488 if (nrepeats > 0) 1489 nrepeats--; 1490 else { 1491 grouping--; 1492 nseps--; 1493 } 1494 PRINT(thousands_sep, 1495 tsl); 1496 PRINTANDPAD(result, 1497 convbuf + ndig, 1498 *grouping, zeroes); 1499 result += *grouping; 1500 } 1501 if (result > convbuf + ndig) 1502 result = convbuf + ndig; 1503 } 1504 if (prec || flags & ALT) 1505 PRINT(decimal_point, decpt_len); 1506 } 1507 PRINTANDPAD(result, convbuf + ndig, prec, 1508 zeroes); 1509 } else { /* %[eE] or sufficiently long %[gG] */ 1510 if (prec > 1 || flags & ALT) { 1511 /* PRINT() ptr arg eval'd in loop */ 1512 /* using "result++" maybe OK, but... */ 1513 PRINT(result, 1); 1514 result++; 1515 PRINT(decimal_point, decpt_len); 1516 PRINT(result, ndig-1); 1517 PAD(prec - ndig, zeroes); 1518 } else /* XeYYY */ 1519 PRINT(result, 1); 1520 PRINT(expstr, expsize); 1521 } 1522 } 1523 #else 1524 PRINT(result, size); 1525 #endif 1526 /* left-adjusting padding (always blank) */ 1527 if (flags & LADJUST) 1528 PAD(width - realsz, blanks); 1529 1530 /* finally, adjust ret */ 1531 ret += prsize; 1532 FLUSH(); 1533 } 1534 done: 1535 FLUSH(); 1536 error: 1537 va_end(orgap); 1538 if (convbuf != NULL) 1539 free(convbuf); 1540 if (__sferror(fp)) 1541 ret = END_OF_FILE; 1542 if ((argtable != NULL) && (argtable != statargtable)) 1543 free (argtable); 1544 return ret; 1545 /* NOTREACHED */ 1546 oomem: 1547 errno = ENOMEM; 1548 ret = END_OF_FILE; 1549 goto error; 1550 } 1551 1552 /* 1553 * Find all arguments when a positional parameter is encountered. Returns a 1554 * table, indexed by argument number, of pointers to each arguments. The 1555 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries. 1556 * It will be replaces with a malloc-ed one if it overflows. 1557 */ 1558 static int 1559 __find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable) 1560 { 1561 CHAR_T *fmt; /* format string */ 1562 int ch; /* character from fmt */ 1563 size_t n, n2; /* handy index (short term usage) */ 1564 CHAR_T *cp; /* handy char pointer (short term usage) */ 1565 int flags; /* flags as above */ 1566 enum typeid *typetable; /* table of types */ 1567 enum typeid stattypetable [STATIC_ARG_TBL_SIZE]; 1568 size_t tablesize; /* current size of type table */ 1569 size_t tablemax; /* largest used index in table */ 1570 size_t nextarg; /* 1-based argument index */ 1571 size_t nitems; /* number of items we picked from the stack */ 1572 1573 /* 1574 * Add an argument type to the table, expanding if necessary. 1575 * Check for overflow. 1576 */ 1577 #define ADDTYPE(type) \ 1578 do { \ 1579 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \ 1580 if (typetable != stattypetable) \ 1581 free(typetable); \ 1582 return -1; \ 1583 } \ 1584 if (nextarg >= tablesize) \ 1585 if (__grow_type_table(nextarg, &typetable, \ 1586 &tablesize) == -1) \ 1587 return -1; \ 1588 if (nextarg > tablemax) \ 1589 tablemax = nextarg; \ 1590 typetable[nextarg++] = type; \ 1591 nitems++; \ 1592 } while (0) 1593 1594 #define ADDSARG() \ 1595 do { \ 1596 if (flags & INTMAXT) \ 1597 ADDTYPE(T_INTMAXT); \ 1598 else if (flags & SIZET) \ 1599 ADDTYPE(T_SSIZET); \ 1600 else if (flags & PTRDIFFT) \ 1601 ADDTYPE(T_PTRDIFFT); \ 1602 else if (flags & LLONGINT) \ 1603 ADDTYPE(T_LLONG); \ 1604 else if (flags & LONGINT) \ 1605 ADDTYPE(T_LONG); \ 1606 else \ 1607 ADDTYPE(T_INT); \ 1608 } while (0) 1609 1610 #define ADDUARG() \ 1611 do { \ 1612 if (flags & INTMAXT) \ 1613 ADDTYPE(T_UINTMAXT); \ 1614 else if (flags & SIZET) \ 1615 ADDTYPE(T_SIZET); \ 1616 else if (flags & PTRDIFFT) \ 1617 ADDTYPE(T_PTRDIFFT); \ 1618 else if (flags & LLONGINT) \ 1619 ADDTYPE(T_U_LLONG); \ 1620 else if (flags & LONGINT) \ 1621 ADDTYPE(T_U_LONG); \ 1622 else \ 1623 ADDTYPE(T_U_INT); \ 1624 } while (0) 1625 /* 1626 * Add * arguments to the type array. 1627 */ 1628 #define ADDASTER() \ 1629 n2 = 0; \ 1630 cp = fmt; \ 1631 while (is_digit(*cp)) { \ 1632 n2 = 10 * n2 + to_digit(*cp); \ 1633 cp++; \ 1634 } \ 1635 if (*cp == '$') { \ 1636 size_t hold = nextarg; \ 1637 nextarg = n2; \ 1638 ADDTYPE(T_INT); \ 1639 nextarg = hold; \ 1640 fmt = ++cp; \ 1641 } else { \ 1642 ADDTYPE(T_INT); \ 1643 } 1644 fmt = (CHAR_T *)__UNCONST(fmt0); 1645 memset(stattypetable, 0, sizeof(stattypetable)); 1646 typetable = stattypetable; 1647 tablesize = STATIC_ARG_TBL_SIZE; 1648 tablemax = 0; 1649 nextarg = 1; 1650 nitems = 1; 1651 1652 /* 1653 * Scan the format for conversions (`%' character). 1654 */ 1655 for (;;) { 1656 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++) 1657 /* void */; 1658 if (ch == '\0') 1659 goto done; 1660 fmt++; /* skip over '%' */ 1661 1662 flags = 0; 1663 1664 rflag: ch = *fmt++; 1665 reswitch: switch (ch) { 1666 case ' ': 1667 case '#': 1668 goto rflag; 1669 case '*': 1670 ADDASTER (); 1671 goto rflag; 1672 case '-': 1673 case '+': 1674 case '\'': 1675 goto rflag; 1676 case '.': 1677 if ((ch = *fmt++) == '*') { 1678 ADDASTER (); 1679 goto rflag; 1680 } 1681 while (is_digit(ch)) { 1682 ch = *fmt++; 1683 } 1684 goto reswitch; 1685 case '0': 1686 goto rflag; 1687 case '1': case '2': case '3': case '4': 1688 case '5': case '6': case '7': case '8': case '9': 1689 n = 0; 1690 do { 1691 n = 10 * n + to_digit(ch); 1692 ch = *fmt++; 1693 } while (is_digit(ch)); 1694 if (ch == '$') { 1695 nextarg = n; 1696 goto rflag; 1697 } 1698 goto reswitch; 1699 #ifndef NO_FLOATING_POINT 1700 case 'L': 1701 flags |= LONGDBL; 1702 goto rflag; 1703 #endif 1704 case 'h': 1705 if (flags & SHORTINT) { 1706 flags &= ~SHORTINT; 1707 flags |= CHARINT; 1708 } else 1709 flags |= SHORTINT; 1710 goto rflag; 1711 case 'j': 1712 flags |= INTMAXT; 1713 goto rflag; 1714 case 'l': 1715 if (flags & LONGINT) { 1716 flags &= ~LONGINT; 1717 flags |= LLONGINT; 1718 } else 1719 flags |= LONGINT; 1720 goto rflag; 1721 case 'q': 1722 flags |= LLONGINT; /* not necessarily */ 1723 goto rflag; 1724 case 't': 1725 flags |= PTRDIFFT; 1726 goto rflag; 1727 case 'z': 1728 flags |= SIZET; 1729 goto rflag; 1730 case 'C': 1731 flags |= LONGINT; 1732 /*FALLTHROUGH*/ 1733 case 'c': 1734 if (flags & LONGINT) 1735 ADDTYPE(T_WINT); 1736 else 1737 ADDTYPE(T_INT); 1738 break; 1739 case 'D': 1740 flags |= LONGINT; 1741 /*FALLTHROUGH*/ 1742 case 'd': 1743 case 'i': 1744 ADDSARG(); 1745 break; 1746 #ifndef NO_FLOATING_POINT 1747 case 'a': 1748 case 'A': 1749 case 'e': 1750 case 'E': 1751 case 'f': 1752 case 'F': 1753 case 'g': 1754 case 'G': 1755 if (flags & LONGDBL) 1756 ADDTYPE(T_LONG_DOUBLE); 1757 else 1758 ADDTYPE(T_DOUBLE); 1759 break; 1760 #endif /* !NO_FLOATING_POINT */ 1761 case 'n': 1762 if (flags & INTMAXT) 1763 ADDTYPE(TP_INTMAXT); 1764 else if (flags & PTRDIFFT) 1765 ADDTYPE(TP_PTRDIFFT); 1766 else if (flags & SIZET) 1767 ADDTYPE(TP_SIZET); 1768 else if (flags & LLONGINT) 1769 ADDTYPE(TP_LLONG); 1770 else if (flags & LONGINT) 1771 ADDTYPE(TP_LONG); 1772 else if (flags & SHORTINT) 1773 ADDTYPE(TP_SHORT); 1774 else if (flags & CHARINT) 1775 ADDTYPE(TP_SCHAR); 1776 else 1777 ADDTYPE(TP_INT); 1778 continue; /* no output */ 1779 case 'O': 1780 flags |= LONGINT; 1781 /*FALLTHROUGH*/ 1782 case 'o': 1783 ADDUARG(); 1784 break; 1785 case 'p': 1786 ADDTYPE(TP_VOID); 1787 break; 1788 case 'S': 1789 flags |= LONGINT; 1790 /*FALLTHROUGH*/ 1791 case 's': 1792 if (flags & LONGINT) 1793 ADDTYPE(TP_WCHAR); 1794 else 1795 ADDTYPE(TP_CHAR); 1796 break; 1797 case 'U': 1798 flags |= LONGINT; 1799 /*FALLTHROUGH*/ 1800 case 'u': 1801 case 'X': 1802 case 'x': 1803 ADDUARG(); 1804 break; 1805 default: /* "%?" prints ?, unless ? is NUL */ 1806 if (ch == '\0') 1807 goto done; 1808 break; 1809 } 1810 } 1811 done: 1812 /* 1813 * nitems contains the number of arguments we picked from the stack. 1814 * If tablemax is larger, this means that some positional argument, 1815 * tried to pick an argument the number of arguments possibly supplied. 1816 * Since positional arguments are typically used to swap the order of 1817 * the printf arguments and not to pick random arguments from strange 1818 * positions in the stack, we assume that if the positional argument 1819 * is trying to pick beyond the end of arguments, then this is wrong. 1820 * Alternatively we could find a way to figure out when va_arg() runs 1821 * out, but how to do that? 1822 */ 1823 if (nitems < tablemax) { 1824 if (typetable != stattypetable) 1825 free(typetable); 1826 return -1; 1827 } 1828 /* 1829 * Build the argument table. 1830 */ 1831 if (tablemax >= STATIC_ARG_TBL_SIZE) { 1832 *argtable = malloc(sizeof(**argtable) * (tablemax + 1)); 1833 if (*argtable == NULL) { 1834 free(typetable); 1835 return -1; 1836 } 1837 } 1838 1839 (*argtable) [0].intarg = 0; 1840 for (n = 1; n <= tablemax; n++) { 1841 switch (typetable [n]) { 1842 case T_UNUSED: /* whoops! */ 1843 (*argtable) [n].intarg = va_arg (ap, int); 1844 break; 1845 case TP_SCHAR: 1846 (*argtable) [n].pschararg = va_arg (ap, signed char *); 1847 break; 1848 case TP_SHORT: 1849 (*argtable) [n].pshortarg = va_arg (ap, short *); 1850 break; 1851 case T_INT: 1852 (*argtable) [n].intarg = va_arg (ap, int); 1853 break; 1854 case T_U_INT: 1855 (*argtable) [n].uintarg = va_arg (ap, unsigned int); 1856 break; 1857 case TP_INT: 1858 (*argtable) [n].pintarg = va_arg (ap, int *); 1859 break; 1860 case T_LONG: 1861 (*argtable) [n].longarg = va_arg (ap, long); 1862 break; 1863 case T_U_LONG: 1864 (*argtable) [n].ulongarg = va_arg (ap, unsigned long); 1865 break; 1866 case TP_LONG: 1867 (*argtable) [n].plongarg = va_arg (ap, long *); 1868 break; 1869 case T_LLONG: 1870 (*argtable) [n].longlongarg = va_arg (ap, long long); 1871 break; 1872 case T_U_LLONG: 1873 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long); 1874 break; 1875 case TP_LLONG: 1876 (*argtable) [n].plonglongarg = va_arg (ap, long long *); 1877 break; 1878 case T_PTRDIFFT: 1879 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t); 1880 break; 1881 case TP_PTRDIFFT: 1882 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *); 1883 break; 1884 case T_SSIZET: 1885 (*argtable) [n].ssizearg = va_arg (ap, ssize_t); 1886 break; 1887 case T_SIZET: 1888 (*argtable) [n].sizearg = va_arg (ap, size_t); 1889 break; 1890 case TP_SIZET: 1891 (*argtable) [n].psizearg = va_arg (ap, size_t *); 1892 break; 1893 case T_INTMAXT: 1894 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t); 1895 break; 1896 case T_UINTMAXT: 1897 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t); 1898 break; 1899 case TP_INTMAXT: 1900 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *); 1901 break; 1902 case T_DOUBLE: 1903 #ifndef NO_FLOATING_POINT 1904 (*argtable) [n].doublearg = va_arg (ap, double); 1905 #endif 1906 break; 1907 case T_LONG_DOUBLE: 1908 #ifndef NO_FLOATING_POINT 1909 (*argtable) [n].longdoublearg = va_arg (ap, long double); 1910 #endif 1911 break; 1912 case TP_CHAR: 1913 (*argtable) [n].pchararg = va_arg (ap, char *); 1914 break; 1915 case TP_VOID: 1916 (*argtable) [n].pvoidarg = va_arg (ap, void *); 1917 break; 1918 case T_WINT: 1919 (*argtable) [n].wintarg = va_arg (ap, wint_t); 1920 break; 1921 case TP_WCHAR: 1922 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *); 1923 break; 1924 } 1925 } 1926 1927 if (typetable != stattypetable) 1928 free (typetable); 1929 return 0; 1930 } 1931 1932 /* 1933 * Increase the size of the type table. 1934 */ 1935 static int 1936 __grow_type_table (size_t nextarg, enum typeid **typetable, size_t *tablesize) 1937 { 1938 enum typeid *const oldtable = *typetable; 1939 const size_t oldsize = *tablesize; 1940 enum typeid *newtable; 1941 size_t newsize = oldsize * 2; 1942 1943 if (newsize < nextarg + 1) 1944 newsize = nextarg + 1; 1945 if (oldsize == STATIC_ARG_TBL_SIZE) { 1946 newtable = NULL; 1947 errno = reallocarr(&newtable, newsize, sizeof(*newtable)); 1948 if (errno) 1949 return -1; 1950 memcpy(newtable, oldtable, oldsize * sizeof(*newtable)); 1951 } else { 1952 newtable = oldtable; 1953 errno = reallocarr(&newtable, newsize, sizeof(*newtable)); 1954 if (errno) { 1955 int serrno = errno; 1956 free(oldtable); 1957 errno = serrno; 1958 return -1; 1959 } 1960 } 1961 memset(&newtable[oldsize], 0, (newsize - oldsize) * sizeof(*newtable)); 1962 1963 *typetable = newtable; 1964 *tablesize = newsize; 1965 return 0; 1966 } 1967 1968 #ifndef NO_FLOATING_POINT 1969 1970 static int 1971 exponent(CHAR_T *p0, int expo, int fmtch) 1972 { 1973 CHAR_T *p, *t; 1974 CHAR_T expbuf[MAXEXPDIG]; 1975 1976 p = p0; 1977 *p++ = fmtch; 1978 if (expo < 0) { 1979 expo = -expo; 1980 *p++ = '-'; 1981 } 1982 else 1983 *p++ = '+'; 1984 t = expbuf + MAXEXPDIG; 1985 if (expo > 9) { 1986 do { 1987 *--t = to_char(expo % 10); 1988 } while ((expo /= 10) > 9); 1989 *--t = to_char(expo); 1990 for (; t < expbuf + MAXEXPDIG; *p++ = *t++); 1991 } 1992 else { 1993 /* 1994 * Exponents for decimal floating point conversions 1995 * (%[eEgG]) must be at least two characters long, 1996 * whereas exponents for hexadecimal conversions can 1997 * be only one character long. 1998 */ 1999 if (fmtch == 'e' || fmtch == 'E') 2000 *p++ = '0'; 2001 *p++ = to_char(expo); 2002 } 2003 _DIAGASSERT(__type_fit(int, p - p0)); 2004 return (int)(p - p0); 2005 } 2006 #endif /* !NO_FLOATING_POINT */ 2007