1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
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 * Copyright (c) 2011 The FreeBSD Foundation
11 *
12 * Portions of this software were developed by David Chisnall
13 * under sponsorship from the FreeBSD Foundation.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
42 #endif /* LIBC_SCCS and not lint */
43 /*
44 * Actual printf innards.
45 *
46 * This code is large and complicated...
47 */
48
49 #include "namespace.h"
50 #include <sys/types.h>
51
52 #include <ctype.h>
53 #include <errno.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <stddef.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <wchar.h>
62 #include <printf.h>
63
64 #include <stdarg.h>
65 #include "xlocale_private.h"
66 #include "un-namespace.h"
67
68 #include "libc_private.h"
69 #include "local.h"
70 #include "fvwrite.h"
71 #include "printflocal.h"
72
73 static int __sprint(FILE *, struct __suio *, locale_t);
74 static int __sbprintf(FILE *, locale_t, int, const char *, va_list)
75 __printflike(4, 0)
76 __noinline;
77 static char *__wcsconv(wchar_t *, int);
78
79 #define CHAR char
80 #include "printfcommon.h"
81
82 struct grouping_state {
83 char *thousands_sep; /* locale-specific thousands separator */
84 int thousep_len; /* length of thousands_sep */
85 const char *grouping; /* locale-specific numeric grouping rules */
86 int lead; /* sig figs before decimal or group sep */
87 int nseps; /* number of group separators with ' */
88 int nrepeats; /* number of repeats of the last group */
89 };
90
91 /*
92 * Initialize the thousands' grouping state in preparation to print a
93 * number with ndigits digits. This routine returns the total number
94 * of bytes that will be needed.
95 */
96 static int
grouping_init(struct grouping_state * gs,int ndigits,locale_t loc)97 grouping_init(struct grouping_state *gs, int ndigits, locale_t loc)
98 {
99 struct lconv *locale;
100
101 locale = localeconv_l(loc);
102 gs->grouping = locale->grouping;
103 gs->thousands_sep = locale->thousands_sep;
104 gs->thousep_len = strlen(gs->thousands_sep);
105
106 gs->nseps = gs->nrepeats = 0;
107 gs->lead = ndigits;
108 while (*gs->grouping != CHAR_MAX) {
109 if (gs->lead <= *gs->grouping)
110 break;
111 gs->lead -= *gs->grouping;
112 if (*(gs->grouping+1)) {
113 gs->nseps++;
114 gs->grouping++;
115 } else
116 gs->nrepeats++;
117 }
118 return ((gs->nseps + gs->nrepeats) * gs->thousep_len);
119 }
120
121 /*
122 * Print a number with thousands' separators.
123 */
124 static int
grouping_print(struct grouping_state * gs,struct io_state * iop,const CHAR * cp,const CHAR * ep,locale_t locale)125 grouping_print(struct grouping_state *gs, struct io_state *iop,
126 const CHAR *cp, const CHAR *ep, locale_t locale)
127 {
128 const CHAR *cp0 = cp;
129
130 if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
131 return (-1);
132 cp += gs->lead;
133 while (gs->nseps > 0 || gs->nrepeats > 0) {
134 if (gs->nrepeats > 0)
135 gs->nrepeats--;
136 else {
137 gs->grouping--;
138 gs->nseps--;
139 }
140 if (io_print(iop, gs->thousands_sep, gs->thousep_len, locale))
141 return (-1);
142 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
143 return (-1);
144 cp += *gs->grouping;
145 }
146 if (cp > ep)
147 cp = ep;
148 return (cp - cp0);
149 }
150
151 /*
152 * Flush out all the vectors defined by the given uio,
153 * then reset it so that it can be reused.
154 */
155 static int
__sprint(FILE * fp,struct __suio * uio,locale_t locale)156 __sprint(FILE *fp, struct __suio *uio, locale_t locale)
157 {
158 int err;
159
160 if (uio->uio_resid == 0) {
161 uio->uio_iovcnt = 0;
162 return (0);
163 }
164 err = __sfvwrite(fp, uio);
165 uio->uio_resid = 0;
166 uio->uio_iovcnt = 0;
167 return (err);
168 }
169
170 /*
171 * Helper function for `fprintf to unbuffered unix file': creates a
172 * temporary buffer. We only work on write-only files; this avoids
173 * worries about ungetc buffers and so forth.
174 */
175 static int
__sbprintf(FILE * fp,locale_t locale,int serrno,const char * fmt,va_list ap)176 __sbprintf(FILE *fp, locale_t locale, int serrno, const char *fmt, va_list ap)
177 {
178 int ret;
179 FILE fake = FAKE_FILE;
180 unsigned char buf[BUFSIZ];
181
182 /* XXX This is probably not needed. */
183 if (prepwrite(fp) != 0)
184 return (EOF);
185
186 /* copy the important variables */
187 fake._flags = fp->_flags & ~__SNBF;
188 fake._file = fp->_file;
189 fake._cookie = fp->_cookie;
190 fake._write = fp->_write;
191 fake._orientation = fp->_orientation;
192 fake._mbstate = fp->_mbstate;
193
194 /* set up the buffer */
195 fake._bf._base = fake._p = buf;
196 fake._bf._size = fake._w = sizeof(buf);
197 fake._lbfsize = 0; /* not actually used, but Just In Case */
198
199 /* do the work, then copy any error status */
200 ret = __vfprintf(&fake, locale, serrno, fmt, ap);
201 if (ret >= 0 && __fflush(&fake))
202 ret = EOF;
203 if (fake._flags & __SERR)
204 fp->_flags |= __SERR;
205 return (ret);
206 }
207
208 /*
209 * Convert a wide character string argument for the %ls format to a multibyte
210 * string representation. If not -1, prec specifies the maximum number of
211 * bytes to output, and also means that we can't assume that the wide char.
212 * string ends is null-terminated.
213 */
214 static char *
__wcsconv(wchar_t * wcsarg,int prec)215 __wcsconv(wchar_t *wcsarg, int prec)
216 {
217 static const mbstate_t initial;
218 mbstate_t mbs;
219 char buf[MB_LEN_MAX];
220 wchar_t *p;
221 char *convbuf;
222 size_t clen, nbytes;
223
224 /* Allocate space for the maximum number of bytes we could output. */
225 if (prec < 0) {
226 p = wcsarg;
227 mbs = initial;
228 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
229 if (nbytes == (size_t)-1)
230 return (NULL);
231 } else {
232 /*
233 * Optimisation: if the output precision is small enough,
234 * just allocate enough memory for the maximum instead of
235 * scanning the string.
236 */
237 if (prec < 128)
238 nbytes = prec;
239 else {
240 nbytes = 0;
241 p = wcsarg;
242 mbs = initial;
243 for (;;) {
244 clen = wcrtomb(buf, *p++, &mbs);
245 if (clen == 0 || clen == (size_t)-1 ||
246 nbytes + clen > prec)
247 break;
248 nbytes += clen;
249 }
250 }
251 }
252 if ((convbuf = malloc(nbytes + 1)) == NULL)
253 return (NULL);
254
255 /* Fill the output buffer. */
256 p = wcsarg;
257 mbs = initial;
258 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
259 nbytes, &mbs)) == (size_t)-1) {
260 free(convbuf);
261 return (NULL);
262 }
263 convbuf[nbytes] = '\0';
264 return (convbuf);
265 }
266
267 /*
268 * MT-safe version
269 */
270 int
vfprintf_l(FILE * __restrict fp,locale_t locale,const char * __restrict fmt0,va_list ap)271 vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0,
272 va_list ap)
273 {
274 int serrno = errno;
275 int ret;
276 FIX_LOCALE(locale);
277
278 FLOCKFILE_CANCELSAFE(fp);
279 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
280 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
281 fp->_file >= 0)
282 ret = __sbprintf(fp, locale, serrno, fmt0, ap);
283 else
284 ret = __vfprintf(fp, locale, serrno, fmt0, ap);
285 FUNLOCKFILE_CANCELSAFE();
286 return (ret);
287 }
288 int
vfprintf(FILE * __restrict fp,const char * __restrict fmt0,va_list ap)289 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
290 {
291 return vfprintf_l(fp, __get_locale(), fmt0, ap);
292 }
293
294 /*
295 * The size of the buffer we use as scratch space for integer
296 * conversions, among other things. We need enough space to
297 * write a uintmax_t in octal (plus one byte).
298 */
299 #if UINTMAX_MAX <= UINT64_MAX
300 #define BUF 32
301 #else
302 #error "BUF must be large enough to format a uintmax_t"
303 #endif
304
305 /*
306 * Non-MT-safe version
307 */
308 int
__vfprintf(FILE * fp,locale_t locale,int serrno,const char * fmt0,va_list ap)309 __vfprintf(FILE *fp, locale_t locale, int serrno, const char *fmt0, va_list ap)
310 {
311 char *fmt; /* format string */
312 int ch; /* character from fmt */
313 int n, n2; /* handy integer (short term usage) */
314 char *cp; /* handy char pointer (short term usage) */
315 int flags; /* flags as above */
316 int ret; /* return value accumulator */
317 int width; /* width from format (%8d), or 0 */
318 int prec; /* precision from format; <0 for N/A */
319 int error;
320 char errnomsg[NL_TEXTMAX];
321 char sign; /* sign prefix (' ', '+', '-', or \0) */
322 struct grouping_state gs; /* thousands' grouping info */
323
324 #ifndef NO_FLOATING_POINT
325 /*
326 * We can decompose the printed representation of floating
327 * point numbers into several parts, some of which may be empty:
328 *
329 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
330 * A B ---C--- D E F
331 *
332 * A: 'sign' holds this value if present; '\0' otherwise
333 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
334 * C: cp points to the string MMMNNN. Leading and trailing
335 * zeros are not in the string and must be added.
336 * D: expchar holds this character; '\0' if no exponent, e.g. %f
337 * F: at least two digits for decimal, at least one digit for hex
338 */
339 char *decimal_point; /* locale specific decimal point */
340 int decpt_len; /* length of decimal_point */
341 int signflag; /* true if float is negative */
342 union { /* floating point arguments %[aAeEfFgG] */
343 double dbl;
344 long double ldbl;
345 } fparg;
346 int expt; /* integer value of exponent */
347 char expchar; /* exponent character: [eEpP\0] */
348 char *dtoaend; /* pointer to end of converted digits */
349 int expsize; /* character count for expstr */
350 int ndig; /* actual number of digits returned by dtoa */
351 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
352 char *dtoaresult; /* buffer allocated by dtoa */
353 #endif
354 u_long ulval; /* integer arguments %[diouxX] */
355 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
356 int base; /* base for [diouxX] conversion */
357 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
358 int realsz; /* field size expanded by dprec, sign, etc */
359 int size; /* size of converted field or string */
360 int prsize; /* max size of printed field */
361 const char *xdigs; /* digits for %[xX] conversion */
362 struct io_state io; /* I/O buffering state */
363 char buf[BUF]; /* buffer with space for digits of uintmax_t */
364 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
365 union arg *argtable; /* args, built due to positional arg */
366 union arg statargtable [STATIC_ARG_TBL_SIZE];
367 int nextarg; /* 1-based argument index */
368 va_list orgap; /* original argument pointer */
369 char *convbuf; /* wide to multibyte conversion result */
370 int savserr;
371
372 static const char xdigs_lower[16] = "0123456789abcdef";
373 static const char xdigs_upper[16] = "0123456789ABCDEF";
374
375 /* BEWARE, these `goto error' on error. */
376 #define PRINT(ptr, len) { \
377 if (io_print(&io, (ptr), (len), locale)) \
378 goto error; \
379 }
380 #define PAD(howmany, with) { \
381 if (io_pad(&io, (howmany), (with), locale)) \
382 goto error; \
383 }
384 #define PRINTANDPAD(p, ep, len, with) { \
385 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
386 goto error; \
387 }
388 #define FLUSH() { \
389 if (io_flush(&io, locale)) \
390 goto error; \
391 }
392
393 /*
394 * Get the argument indexed by nextarg. If the argument table is
395 * built, use it to get the argument. If its not, get the next
396 * argument (and arguments must be gotten sequentially).
397 */
398 #define GETARG(type) \
399 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
400 (nextarg++, va_arg(ap, type)))
401
402 /*
403 * To extend shorts properly, we need both signed and unsigned
404 * argument extraction methods.
405 */
406 #define SARG() \
407 (flags&LONGINT ? GETARG(long) : \
408 flags&SHORTINT ? (long)(short)GETARG(int) : \
409 flags&CHARINT ? (long)(signed char)GETARG(int) : \
410 (long)GETARG(int))
411 #define UARG() \
412 (flags&LONGINT ? GETARG(u_long) : \
413 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
414 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
415 (u_long)GETARG(u_int))
416 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
417 #define SJARG() \
418 (flags&INTMAXT ? GETARG(intmax_t) : \
419 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
420 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
421 (intmax_t)GETARG(long long))
422 #define UJARG() \
423 (flags&INTMAXT ? GETARG(uintmax_t) : \
424 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
425 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
426 (uintmax_t)GETARG(unsigned long long))
427
428 /*
429 * Get * arguments, including the form *nn$. Preserve the nextarg
430 * that the argument can be gotten once the type is determined.
431 */
432 #define GETASTER(val) \
433 n2 = 0; \
434 cp = fmt; \
435 while (is_digit(*cp)) { \
436 n2 = 10 * n2 + to_digit(*cp); \
437 cp++; \
438 } \
439 if (*cp == '$') { \
440 int hold = nextarg; \
441 if (argtable == NULL) { \
442 argtable = statargtable; \
443 if (__find_arguments (fmt0, orgap, &argtable)) { \
444 ret = EOF; \
445 goto error; \
446 } \
447 } \
448 nextarg = n2; \
449 val = GETARG (int); \
450 nextarg = hold; \
451 fmt = ++cp; \
452 } else { \
453 val = GETARG (int); \
454 }
455
456 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
457 __use_xprintf = 1;
458 if (__use_xprintf > 0)
459 return (__xvprintf(fp, fmt0, ap));
460
461 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
462 if (prepwrite(fp) != 0) {
463 errno = EBADF;
464 return (EOF);
465 }
466
467 savserr = fp->_flags & __SERR;
468 fp->_flags &= ~__SERR;
469
470 convbuf = NULL;
471 fmt = (char *)fmt0;
472 argtable = NULL;
473 nextarg = 1;
474 va_copy(orgap, ap);
475 io_init(&io, fp);
476 ret = 0;
477 #ifndef NO_FLOATING_POINT
478 dtoaresult = NULL;
479 decimal_point = localeconv_l(locale)->decimal_point;
480 /* The overwhelmingly common case is decpt_len == 1. */
481 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
482 #endif
483
484 /*
485 * Scan the format for conversions (`%' character).
486 */
487 for (;;) {
488 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
489 /* void */;
490 if ((n = fmt - cp) != 0) {
491 if ((unsigned)ret + n > INT_MAX) {
492 ret = EOF;
493 errno = EOVERFLOW;
494 goto error;
495 }
496 PRINT(cp, n);
497 ret += n;
498 }
499 if (ch == '\0')
500 goto done;
501 fmt++; /* skip over '%' */
502
503 flags = 0;
504 dprec = 0;
505 width = 0;
506 prec = -1;
507 gs.grouping = NULL;
508 sign = '\0';
509 ox[1] = '\0';
510
511 rflag: ch = *fmt++;
512 reswitch: switch (ch) {
513 case ' ':
514 /*-
515 * ``If the space and + flags both appear, the space
516 * flag will be ignored.''
517 * -- ANSI X3J11
518 */
519 if (!sign)
520 sign = ' ';
521 goto rflag;
522 case '#':
523 flags |= ALT;
524 goto rflag;
525 case '*':
526 /*-
527 * ``A negative field width argument is taken as a
528 * - flag followed by a positive field width.''
529 * -- ANSI X3J11
530 * They don't exclude field widths read from args.
531 */
532 GETASTER (width);
533 if (width >= 0)
534 goto rflag;
535 width = -width;
536 /* FALLTHROUGH */
537 case '-':
538 flags |= LADJUST;
539 goto rflag;
540 case '+':
541 sign = '+';
542 goto rflag;
543 case '\'':
544 flags |= GROUPING;
545 goto rflag;
546 case '.':
547 if ((ch = *fmt++) == '*') {
548 GETASTER (prec);
549 goto rflag;
550 }
551 prec = 0;
552 while (is_digit(ch)) {
553 prec = 10 * prec + to_digit(ch);
554 ch = *fmt++;
555 }
556 goto reswitch;
557 case '0':
558 /*-
559 * ``Note that 0 is taken as a flag, not as the
560 * beginning of a field width.''
561 * -- ANSI X3J11
562 */
563 flags |= ZEROPAD;
564 goto rflag;
565 case '1': case '2': case '3': case '4':
566 case '5': case '6': case '7': case '8': case '9':
567 n = 0;
568 do {
569 n = 10 * n + to_digit(ch);
570 ch = *fmt++;
571 } while (is_digit(ch));
572 if (ch == '$') {
573 nextarg = n;
574 if (argtable == NULL) {
575 argtable = statargtable;
576 if (__find_arguments (fmt0, orgap,
577 &argtable)) {
578 ret = EOF;
579 goto error;
580 }
581 }
582 goto rflag;
583 }
584 width = n;
585 goto reswitch;
586 #ifndef NO_FLOATING_POINT
587 case 'L':
588 flags |= LONGDBL;
589 goto rflag;
590 #endif
591 case 'h':
592 if (flags & SHORTINT) {
593 flags &= ~SHORTINT;
594 flags |= CHARINT;
595 } else
596 flags |= SHORTINT;
597 goto rflag;
598 case 'j':
599 flags |= INTMAXT;
600 goto rflag;
601 case 'l':
602 if (flags & LONGINT) {
603 flags &= ~LONGINT;
604 flags |= LLONGINT;
605 } else
606 flags |= LONGINT;
607 goto rflag;
608 case 'q':
609 flags |= LLONGINT; /* not necessarily */
610 goto rflag;
611 case 't':
612 flags |= PTRDIFFT;
613 goto rflag;
614 case 'w':
615 /*
616 * Fixed-width integer types. On all platforms we
617 * support, int8_t is equivalent to char, int16_t
618 * is equivalent to short, int32_t is equivalent
619 * to int, int64_t is equivalent to long long int.
620 * Furthermore, int_fast8_t, int_fast16_t and
621 * int_fast32_t are equivalent to int, and
622 * int_fast64_t is equivalent to long long int.
623 */
624 flags &= ~(CHARINT|SHORTINT|LONGINT|LLONGINT|INTMAXT);
625 if (fmt[0] == 'f') {
626 flags |= FASTINT;
627 fmt++;
628 } else {
629 flags &= ~FASTINT;
630 }
631 if (fmt[0] == '8') {
632 if (!(flags & FASTINT))
633 flags |= CHARINT;
634 else
635 /* no flag set = 32 */ ;
636 fmt += 1;
637 } else if (fmt[0] == '1' && fmt[1] == '6') {
638 if (!(flags & FASTINT))
639 flags |= SHORTINT;
640 else
641 /* no flag set = 32 */ ;
642 fmt += 2;
643 } else if (fmt[0] == '3' && fmt[1] == '2') {
644 /* no flag set = 32 */ ;
645 fmt += 2;
646 } else if (fmt[0] == '6' && fmt[1] == '4') {
647 flags |= LLONGINT;
648 fmt += 2;
649 } else {
650 if (flags & FASTINT) {
651 flags &= ~FASTINT;
652 fmt--;
653 }
654 goto invalid;
655 }
656 goto rflag;
657 case 'z':
658 flags |= SIZET;
659 goto rflag;
660 case 'B':
661 case 'b':
662 if (flags & INTMAX_SIZE)
663 ujval = UJARG();
664 else
665 ulval = UARG();
666 base = 2;
667 /* leading 0b/B only if non-zero */
668 if (flags & ALT &&
669 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
670 ox[1] = ch;
671 goto nosign;
672 break;
673 case 'C':
674 flags |= LONGINT;
675 /*FALLTHROUGH*/
676 case 'c':
677 if (flags & LONGINT) {
678 static const mbstate_t initial;
679 mbstate_t mbs;
680 size_t mbseqlen;
681
682 mbs = initial;
683 mbseqlen = wcrtomb(cp = buf,
684 (wchar_t)GETARG(wint_t), &mbs);
685 if (mbseqlen == (size_t)-1) {
686 fp->_flags |= __SERR;
687 goto error;
688 }
689 size = (int)mbseqlen;
690 } else {
691 *(cp = buf) = GETARG(int);
692 size = 1;
693 }
694 sign = '\0';
695 break;
696 case 'D':
697 flags |= LONGINT;
698 /*FALLTHROUGH*/
699 case 'd':
700 case 'i':
701 if (flags & INTMAX_SIZE) {
702 ujval = SJARG();
703 if ((intmax_t)ujval < 0) {
704 ujval = -ujval;
705 sign = '-';
706 }
707 } else {
708 ulval = SARG();
709 if ((long)ulval < 0) {
710 ulval = -ulval;
711 sign = '-';
712 }
713 }
714 base = 10;
715 goto number;
716 #ifndef NO_FLOATING_POINT
717 case 'a':
718 case 'A':
719 if (ch == 'a') {
720 ox[1] = 'x';
721 xdigs = xdigs_lower;
722 expchar = 'p';
723 } else {
724 ox[1] = 'X';
725 xdigs = xdigs_upper;
726 expchar = 'P';
727 }
728 if (prec >= 0)
729 prec++;
730 if (dtoaresult != NULL)
731 freedtoa(dtoaresult);
732 if (flags & LONGDBL) {
733 fparg.ldbl = GETARG(long double);
734 dtoaresult = cp =
735 __hldtoa(fparg.ldbl, xdigs, prec,
736 &expt, &signflag, &dtoaend);
737 } else {
738 fparg.dbl = GETARG(double);
739 dtoaresult = cp =
740 __hdtoa(fparg.dbl, xdigs, prec,
741 &expt, &signflag, &dtoaend);
742 }
743 if (prec < 0)
744 prec = dtoaend - cp;
745 if (expt == INT_MAX)
746 ox[1] = '\0';
747 goto fp_common;
748 case 'e':
749 case 'E':
750 expchar = ch;
751 if (prec < 0) /* account for digit before decpt */
752 prec = DEFPREC + 1;
753 else
754 prec++;
755 goto fp_begin;
756 case 'f':
757 case 'F':
758 expchar = '\0';
759 goto fp_begin;
760 case 'g':
761 case 'G':
762 expchar = ch - ('g' - 'e');
763 if (prec == 0)
764 prec = 1;
765 fp_begin:
766 if (prec < 0)
767 prec = DEFPREC;
768 if (dtoaresult != NULL)
769 freedtoa(dtoaresult);
770 if (flags & LONGDBL) {
771 fparg.ldbl = GETARG(long double);
772 dtoaresult = cp =
773 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
774 &expt, &signflag, &dtoaend);
775 } else {
776 fparg.dbl = GETARG(double);
777 dtoaresult = cp =
778 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
779 &expt, &signflag, &dtoaend);
780 if (expt == 9999)
781 expt = INT_MAX;
782 }
783 fp_common:
784 if (signflag)
785 sign = '-';
786 if (expt == INT_MAX) { /* inf or nan */
787 if (*cp == 'N') {
788 cp = (ch >= 'a') ? "nan" : "NAN";
789 sign = '\0';
790 } else
791 cp = (ch >= 'a') ? "inf" : "INF";
792 size = 3;
793 flags &= ~ZEROPAD;
794 break;
795 }
796 flags |= FPT;
797 ndig = dtoaend - cp;
798 if (ch == 'g' || ch == 'G') {
799 if (expt > -4 && expt <= prec) {
800 /* Make %[gG] smell like %[fF] */
801 expchar = '\0';
802 if (flags & ALT)
803 prec -= expt;
804 else
805 prec = ndig - expt;
806 if (prec < 0)
807 prec = 0;
808 } else {
809 /*
810 * Make %[gG] smell like %[eE], but
811 * trim trailing zeroes if no # flag.
812 */
813 if (!(flags & ALT))
814 prec = ndig;
815 }
816 }
817 if (expchar) {
818 expsize = exponent(expstr, expt - 1, expchar);
819 size = expsize + prec;
820 if (prec > 1 || flags & ALT)
821 size += decpt_len;
822 } else {
823 /* space for digits before decimal point */
824 if (expt > 0)
825 size = expt;
826 else /* "0" */
827 size = 1;
828 /* space for decimal pt and following digits */
829 if (prec || flags & ALT)
830 size += prec + decpt_len;
831 if ((flags & GROUPING) && expt > 0)
832 size += grouping_init(&gs, expt, locale);
833 }
834 break;
835 #endif /* !NO_FLOATING_POINT */
836 case 'm':
837 error = __strerror_rl(serrno, errnomsg,
838 sizeof(errnomsg), locale);
839 cp = error == 0 ? errnomsg : "<strerror failure>";
840 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
841 sign = '\0';
842 break;
843 case 'n':
844 /*
845 * Assignment-like behavior is specified if the
846 * value overflows or is otherwise unrepresentable.
847 * C99 says to use `signed char' for %hhn conversions.
848 */
849 if (flags & LLONGINT)
850 *GETARG(long long *) = ret;
851 else if (flags & SIZET)
852 *GETARG(ssize_t *) = (ssize_t)ret;
853 else if (flags & PTRDIFFT)
854 *GETARG(ptrdiff_t *) = ret;
855 else if (flags & INTMAXT)
856 *GETARG(intmax_t *) = ret;
857 else if (flags & LONGINT)
858 *GETARG(long *) = ret;
859 else if (flags & SHORTINT)
860 *GETARG(short *) = ret;
861 else if (flags & CHARINT)
862 *GETARG(signed char *) = ret;
863 else
864 *GETARG(int *) = ret;
865 continue; /* no output */
866 case 'O':
867 flags |= LONGINT;
868 /*FALLTHROUGH*/
869 case 'o':
870 if (flags & INTMAX_SIZE)
871 ujval = UJARG();
872 else
873 ulval = UARG();
874 base = 8;
875 goto nosign;
876 case 'p':
877 /*-
878 * ``The argument shall be a pointer to void. The
879 * value of the pointer is converted to a sequence
880 * of printable characters, in an implementation-
881 * defined manner.''
882 * -- ANSI X3J11
883 */
884 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
885 base = 16;
886 xdigs = xdigs_lower;
887 flags = flags | INTMAXT;
888 ox[1] = 'x';
889 goto nosign;
890 case 'S':
891 flags |= LONGINT;
892 /*FALLTHROUGH*/
893 case 's':
894 if (flags & LONGINT) {
895 wchar_t *wcp;
896
897 if (convbuf != NULL)
898 free(convbuf);
899 if ((wcp = GETARG(wchar_t *)) == NULL)
900 cp = "(null)";
901 else {
902 convbuf = __wcsconv(wcp, prec);
903 if (convbuf == NULL) {
904 fp->_flags |= __SERR;
905 goto error;
906 }
907 cp = convbuf;
908 }
909 } else if ((cp = GETARG(char *)) == NULL)
910 cp = "(null)";
911 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
912 sign = '\0';
913 break;
914 case 'U':
915 flags |= LONGINT;
916 /*FALLTHROUGH*/
917 case 'u':
918 if (flags & INTMAX_SIZE)
919 ujval = UJARG();
920 else
921 ulval = UARG();
922 base = 10;
923 goto nosign;
924 case 'X':
925 xdigs = xdigs_upper;
926 goto hex;
927 case 'x':
928 xdigs = xdigs_lower;
929 hex:
930 if (flags & INTMAX_SIZE)
931 ujval = UJARG();
932 else
933 ulval = UARG();
934 base = 16;
935 /* leading 0x/X only if non-zero */
936 if (flags & ALT &&
937 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
938 ox[1] = ch;
939
940 flags &= ~GROUPING;
941 /* unsigned conversions */
942 nosign: sign = '\0';
943 /*-
944 * ``... diouXx conversions ... if a precision is
945 * specified, the 0 flag will be ignored.''
946 * -- ANSI X3J11
947 */
948 number: if ((dprec = prec) >= 0)
949 flags &= ~ZEROPAD;
950
951 /*-
952 * ``The result of converting a zero value with an
953 * explicit precision of zero is no characters.''
954 * -- ANSI X3J11
955 *
956 * ``The C Standard is clear enough as is. The call
957 * printf("%#.0o", 0) should print 0.''
958 * -- Defect Report #151
959 */
960 cp = buf + BUF;
961 if (flags & INTMAX_SIZE) {
962 if (ujval != 0 || prec != 0 ||
963 (flags & ALT && base == 8))
964 cp = __ujtoa(ujval, cp, base,
965 flags & ALT, xdigs);
966 } else {
967 if (ulval != 0 || prec != 0 ||
968 (flags & ALT && base == 8))
969 cp = __ultoa(ulval, cp, base,
970 flags & ALT, xdigs);
971 }
972 size = buf + BUF - cp;
973 if (size > BUF) /* should never happen */
974 abort();
975 if ((flags & GROUPING) && size != 0)
976 size += grouping_init(&gs, size, locale);
977 break;
978 default: /* "%?" prints ?, unless ? is NUL */
979 if (ch == '\0')
980 goto done;
981 invalid:
982 /* pretend it was %c with argument ch */
983 cp = buf;
984 *cp = ch;
985 size = 1;
986 sign = '\0';
987 break;
988 }
989
990 /*
991 * All reasonable formats wind up here. At this point, `cp'
992 * points to a string which (if not flags&LADJUST) should be
993 * padded out to `width' places. If flags&ZEROPAD, it should
994 * first be prefixed by any sign or other prefix; otherwise,
995 * it should be blank padded before the prefix is emitted.
996 * After any left-hand padding and prefixing, emit zeroes
997 * required by a decimal [diouxX] precision, then print the
998 * string proper, then emit zeroes required by any leftover
999 * floating precision; finally, if LADJUST, pad with blanks.
1000 *
1001 * Compute actual size, so we know how much to pad.
1002 * size excludes decimal prec; realsz includes it.
1003 */
1004 realsz = dprec > size ? dprec : size;
1005 if (sign)
1006 realsz++;
1007 if (ox[1])
1008 realsz += 2;
1009
1010 prsize = width > realsz ? width : realsz;
1011 if ((unsigned)ret + prsize > INT_MAX) {
1012 ret = EOF;
1013 errno = EOVERFLOW;
1014 goto error;
1015 }
1016
1017 /* right-adjusting blank padding */
1018 if ((flags & (LADJUST|ZEROPAD)) == 0)
1019 PAD(width - realsz, blanks);
1020
1021 /* prefix */
1022 if (sign)
1023 PRINT(&sign, 1);
1024
1025 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1026 ox[0] = '0';
1027 PRINT(ox, 2);
1028 }
1029
1030 /* right-adjusting zero padding */
1031 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1032 PAD(width - realsz, zeroes);
1033
1034 /* the string or number proper */
1035 #ifndef NO_FLOATING_POINT
1036 if ((flags & FPT) == 0) {
1037 #endif
1038 /* leading zeroes from decimal precision */
1039 PAD(dprec - size, zeroes);
1040 if (gs.grouping) {
1041 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1042 goto error;
1043 } else {
1044 PRINT(cp, size);
1045 }
1046 #ifndef NO_FLOATING_POINT
1047 } else { /* glue together f_p fragments */
1048 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1049 if (expt <= 0) {
1050 PRINT(zeroes, 1);
1051 if (prec || flags & ALT)
1052 PRINT(decimal_point,decpt_len);
1053 PAD(-expt, zeroes);
1054 /* already handled initial 0's */
1055 prec += expt;
1056 } else {
1057 if (gs.grouping) {
1058 n = grouping_print(&gs, &io,
1059 cp, dtoaend, locale);
1060 if (n < 0)
1061 goto error;
1062 cp += n;
1063 } else {
1064 PRINTANDPAD(cp, dtoaend,
1065 expt, zeroes);
1066 cp += expt;
1067 }
1068 if (prec || flags & ALT)
1069 PRINT(decimal_point,decpt_len);
1070 }
1071 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1072 } else { /* %[eE] or sufficiently long %[gG] */
1073 if (prec > 1 || flags & ALT) {
1074 PRINT(cp++, 1);
1075 PRINT(decimal_point, decpt_len);
1076 PRINT(cp, ndig-1);
1077 PAD(prec - ndig, zeroes);
1078 } else /* XeYYY */
1079 PRINT(cp, 1);
1080 PRINT(expstr, expsize);
1081 }
1082 }
1083 #endif
1084 /* left-adjusting padding (always blank) */
1085 if (flags & LADJUST)
1086 PAD(width - realsz, blanks);
1087
1088 /* finally, adjust ret */
1089 ret += prsize;
1090
1091 FLUSH(); /* copy out the I/O vectors */
1092 }
1093 done:
1094 FLUSH();
1095 error:
1096 va_end(orgap);
1097 #ifndef NO_FLOATING_POINT
1098 if (dtoaresult != NULL)
1099 freedtoa(dtoaresult);
1100 #endif
1101 if (convbuf != NULL)
1102 free(convbuf);
1103 if (__sferror(fp))
1104 ret = EOF;
1105 else
1106 fp->_flags |= savserr;
1107 if ((argtable != NULL) && (argtable != statargtable))
1108 free (argtable);
1109 return (ret);
1110 /* NOTREACHED */
1111 }
1112
1113