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 binary.
298 */
299 #define BUF (sizeof(uintmax_t) * CHAR_BIT)
300
301 /*
302 * Non-MT-safe version
303 */
304 int
__vfprintf(FILE * fp,locale_t locale,int serrno,const char * fmt0,va_list ap)305 __vfprintf(FILE *fp, locale_t locale, int serrno, const char *fmt0, va_list ap)
306 {
307 char *fmt; /* format string */
308 int ch; /* character from fmt */
309 int n, n2; /* handy integer (short term usage) */
310 char *cp; /* handy char pointer (short term usage) */
311 int flags; /* flags as above */
312 int ret; /* return value accumulator */
313 int width; /* width from format (%8d), or 0 */
314 int prec; /* precision from format; <0 for N/A */
315 int error;
316 char errnomsg[NL_TEXTMAX];
317 char sign; /* sign prefix (' ', '+', '-', or \0) */
318 struct grouping_state gs; /* thousands' grouping info */
319
320 #ifndef NO_FLOATING_POINT
321 /*
322 * We can decompose the printed representation of floating
323 * point numbers into several parts, some of which may be empty:
324 *
325 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
326 * A B ---C--- D E F
327 *
328 * A: 'sign' holds this value if present; '\0' otherwise
329 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
330 * C: cp points to the string MMMNNN. Leading and trailing
331 * zeros are not in the string and must be added.
332 * D: expchar holds this character; '\0' if no exponent, e.g. %f
333 * F: at least two digits for decimal, at least one digit for hex
334 */
335 char *decimal_point; /* locale specific decimal point */
336 int decpt_len; /* length of decimal_point */
337 int signflag; /* true if float is negative */
338 union { /* floating point arguments %[aAeEfFgG] */
339 double dbl;
340 long double ldbl;
341 } fparg;
342 int expt; /* integer value of exponent */
343 char expchar; /* exponent character: [eEpP\0] */
344 char *dtoaend; /* pointer to end of converted digits */
345 int expsize; /* character count for expstr */
346 int ndig; /* actual number of digits returned by dtoa */
347 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
348 char *dtoaresult; /* buffer allocated by dtoa */
349 #endif
350 u_long ulval; /* integer arguments %[diouxX] */
351 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
352 int base; /* base for [diouxX] conversion */
353 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
354 int realsz; /* field size expanded by dprec, sign, etc */
355 int size; /* size of converted field or string */
356 int prsize; /* max size of printed field */
357 const char *xdigs; /* digits for %[xX] conversion */
358 struct io_state io; /* I/O buffering state */
359 char buf[BUF]; /* buffer with space for digits of uintmax_t */
360 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
361 union arg *argtable; /* args, built due to positional arg */
362 union arg statargtable [STATIC_ARG_TBL_SIZE];
363 int nextarg; /* 1-based argument index */
364 va_list orgap; /* original argument pointer */
365 char *convbuf; /* wide to multibyte conversion result */
366 int savserr;
367
368 static const char xdigs_lower[16] = "0123456789abcdef";
369 static const char xdigs_upper[16] = "0123456789ABCDEF";
370
371 /* BEWARE, these `goto error' on error. */
372 #define PRINT(ptr, len) { \
373 if (io_print(&io, (ptr), (len), locale)) \
374 goto error; \
375 }
376 #define PAD(howmany, with) { \
377 if (io_pad(&io, (howmany), (with), locale)) \
378 goto error; \
379 }
380 #define PRINTANDPAD(p, ep, len, with) { \
381 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
382 goto error; \
383 }
384 #define FLUSH() { \
385 if (io_flush(&io, locale)) \
386 goto error; \
387 }
388
389 /*
390 * Get the argument indexed by nextarg. If the argument table is
391 * built, use it to get the argument. If its not, get the next
392 * argument (and arguments must be gotten sequentially).
393 */
394 #define GETARG(type) \
395 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
396 (nextarg++, va_arg(ap, type)))
397
398 /*
399 * To extend shorts properly, we need both signed and unsigned
400 * argument extraction methods.
401 */
402 #define SARG() \
403 (flags&LONGINT ? GETARG(long) : \
404 flags&SHORTINT ? (long)(short)GETARG(int) : \
405 flags&CHARINT ? (long)(signed char)GETARG(int) : \
406 (long)GETARG(int))
407 #define UARG() \
408 (flags&LONGINT ? GETARG(u_long) : \
409 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
410 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
411 (u_long)GETARG(u_int))
412 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
413 #define SJARG() \
414 (flags&INTMAXT ? GETARG(intmax_t) : \
415 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
416 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
417 (intmax_t)GETARG(long long))
418 #define UJARG() \
419 (flags&INTMAXT ? GETARG(uintmax_t) : \
420 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
421 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
422 (uintmax_t)GETARG(unsigned long long))
423
424 /*
425 * Get * arguments, including the form *nn$. Preserve the nextarg
426 * that the argument can be gotten once the type is determined.
427 */
428 #define GETASTER(val) \
429 n2 = 0; \
430 cp = fmt; \
431 while (is_digit(*cp)) { \
432 n2 = 10 * n2 + to_digit(*cp); \
433 cp++; \
434 } \
435 if (*cp == '$') { \
436 int hold = nextarg; \
437 if (argtable == NULL) { \
438 argtable = statargtable; \
439 if (__find_arguments (fmt0, orgap, &argtable)) { \
440 ret = EOF; \
441 goto error; \
442 } \
443 } \
444 nextarg = n2; \
445 val = GETARG (int); \
446 nextarg = hold; \
447 fmt = ++cp; \
448 } else { \
449 val = GETARG (int); \
450 }
451
452 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
453 __use_xprintf = 1;
454 if (__use_xprintf > 0)
455 return (__xvprintf(fp, fmt0, ap));
456
457 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
458 if (prepwrite(fp) != 0) {
459 errno = EBADF;
460 return (EOF);
461 }
462
463 savserr = fp->_flags & __SERR;
464 fp->_flags &= ~__SERR;
465
466 convbuf = NULL;
467 fmt = (char *)fmt0;
468 argtable = NULL;
469 nextarg = 1;
470 va_copy(orgap, ap);
471 io_init(&io, fp);
472 ret = 0;
473 #ifndef NO_FLOATING_POINT
474 dtoaresult = NULL;
475 decimal_point = localeconv_l(locale)->decimal_point;
476 /* The overwhelmingly common case is decpt_len == 1. */
477 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
478 #endif
479
480 /*
481 * Scan the format for conversions (`%' character).
482 */
483 for (;;) {
484 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
485 /* void */;
486 if ((n = fmt - cp) != 0) {
487 if ((unsigned)ret + n > INT_MAX) {
488 ret = EOF;
489 errno = EOVERFLOW;
490 goto error;
491 }
492 PRINT(cp, n);
493 ret += n;
494 }
495 if (ch == '\0')
496 goto done;
497 fmt++; /* skip over '%' */
498
499 flags = 0;
500 dprec = 0;
501 width = 0;
502 prec = -1;
503 gs.grouping = NULL;
504 sign = '\0';
505 ox[1] = '\0';
506
507 rflag: ch = *fmt++;
508 reswitch: switch (ch) {
509 case ' ':
510 /*-
511 * ``If the space and + flags both appear, the space
512 * flag will be ignored.''
513 * -- ANSI X3J11
514 */
515 if (!sign)
516 sign = ' ';
517 goto rflag;
518 case '#':
519 flags |= ALT;
520 goto rflag;
521 case '*':
522 /*-
523 * ``A negative field width argument is taken as a
524 * - flag followed by a positive field width.''
525 * -- ANSI X3J11
526 * They don't exclude field widths read from args.
527 */
528 GETASTER (width);
529 if (width >= 0)
530 goto rflag;
531 width = -width;
532 /* FALLTHROUGH */
533 case '-':
534 flags |= LADJUST;
535 goto rflag;
536 case '+':
537 sign = '+';
538 goto rflag;
539 case '\'':
540 flags |= GROUPING;
541 goto rflag;
542 case '.':
543 if ((ch = *fmt++) == '*') {
544 GETASTER (prec);
545 goto rflag;
546 }
547 prec = 0;
548 while (is_digit(ch)) {
549 prec = 10 * prec + to_digit(ch);
550 ch = *fmt++;
551 }
552 goto reswitch;
553 case '0':
554 /*-
555 * ``Note that 0 is taken as a flag, not as the
556 * beginning of a field width.''
557 * -- ANSI X3J11
558 */
559 flags |= ZEROPAD;
560 goto rflag;
561 case '1': case '2': case '3': case '4':
562 case '5': case '6': case '7': case '8': case '9':
563 n = 0;
564 do {
565 n = 10 * n + to_digit(ch);
566 ch = *fmt++;
567 } while (is_digit(ch));
568 if (ch == '$') {
569 nextarg = n;
570 if (argtable == NULL) {
571 argtable = statargtable;
572 if (__find_arguments (fmt0, orgap,
573 &argtable)) {
574 ret = EOF;
575 goto error;
576 }
577 }
578 goto rflag;
579 }
580 width = n;
581 goto reswitch;
582 #ifndef NO_FLOATING_POINT
583 case 'L':
584 flags |= LONGDBL;
585 goto rflag;
586 #endif
587 case 'h':
588 if (flags & SHORTINT) {
589 flags &= ~SHORTINT;
590 flags |= CHARINT;
591 } else
592 flags |= SHORTINT;
593 goto rflag;
594 case 'j':
595 flags |= INTMAXT;
596 goto rflag;
597 case 'l':
598 if (flags & LONGINT) {
599 flags &= ~LONGINT;
600 flags |= LLONGINT;
601 } else
602 flags |= LONGINT;
603 goto rflag;
604 case 'q':
605 flags |= LLONGINT; /* not necessarily */
606 goto rflag;
607 case 't':
608 flags |= PTRDIFFT;
609 goto rflag;
610 case 'w':
611 /*
612 * Fixed-width integer types. On all platforms we
613 * support, int8_t is equivalent to char, int16_t
614 * is equivalent to short, int32_t is equivalent
615 * to int, int64_t is equivalent to long long int.
616 * Furthermore, int_fast8_t, int_fast16_t and
617 * int_fast32_t are equivalent to int, and
618 * int_fast64_t is equivalent to long long int.
619 */
620 flags &= ~(CHARINT|SHORTINT|LONGINT|LLONGINT|INTMAXT);
621 if (fmt[0] == 'f') {
622 flags |= FASTINT;
623 fmt++;
624 } else {
625 flags &= ~FASTINT;
626 }
627 if (fmt[0] == '8') {
628 if (!(flags & FASTINT))
629 flags |= CHARINT;
630 else
631 /* no flag set = 32 */ ;
632 fmt += 1;
633 } else if (fmt[0] == '1' && fmt[1] == '6') {
634 if (!(flags & FASTINT))
635 flags |= SHORTINT;
636 else
637 /* no flag set = 32 */ ;
638 fmt += 2;
639 } else if (fmt[0] == '3' && fmt[1] == '2') {
640 /* no flag set = 32 */ ;
641 fmt += 2;
642 } else if (fmt[0] == '6' && fmt[1] == '4') {
643 flags |= LLONGINT;
644 fmt += 2;
645 } else {
646 if (flags & FASTINT) {
647 flags &= ~FASTINT;
648 fmt--;
649 }
650 goto invalid;
651 }
652 goto rflag;
653 case 'z':
654 flags |= SIZET;
655 goto rflag;
656 case 'B':
657 case 'b':
658 if (flags & INTMAX_SIZE)
659 ujval = UJARG();
660 else
661 ulval = UARG();
662 base = 2;
663 /* leading 0b/B only if non-zero */
664 if (flags & ALT &&
665 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
666 ox[1] = ch;
667 goto nosign;
668 break;
669 case 'C':
670 flags |= LONGINT;
671 /*FALLTHROUGH*/
672 case 'c':
673 if (flags & LONGINT) {
674 static const mbstate_t initial;
675 mbstate_t mbs;
676 size_t mbseqlen;
677
678 mbs = initial;
679 mbseqlen = wcrtomb(cp = buf,
680 (wchar_t)GETARG(wint_t), &mbs);
681 if (mbseqlen == (size_t)-1) {
682 fp->_flags |= __SERR;
683 goto error;
684 }
685 size = (int)mbseqlen;
686 } else {
687 *(cp = buf) = GETARG(int);
688 size = 1;
689 }
690 sign = '\0';
691 break;
692 case 'D':
693 flags |= LONGINT;
694 /*FALLTHROUGH*/
695 case 'd':
696 case 'i':
697 if (flags & INTMAX_SIZE) {
698 ujval = SJARG();
699 if ((intmax_t)ujval < 0) {
700 ujval = -ujval;
701 sign = '-';
702 }
703 } else {
704 ulval = SARG();
705 if ((long)ulval < 0) {
706 ulval = -ulval;
707 sign = '-';
708 }
709 }
710 base = 10;
711 goto number;
712 #ifndef NO_FLOATING_POINT
713 case 'a':
714 case 'A':
715 if (ch == 'a') {
716 ox[1] = 'x';
717 xdigs = xdigs_lower;
718 expchar = 'p';
719 } else {
720 ox[1] = 'X';
721 xdigs = xdigs_upper;
722 expchar = 'P';
723 }
724 if (prec >= 0)
725 prec++;
726 if (dtoaresult != NULL)
727 freedtoa(dtoaresult);
728 if (flags & LONGDBL) {
729 fparg.ldbl = GETARG(long double);
730 dtoaresult = cp =
731 __hldtoa(fparg.ldbl, xdigs, prec,
732 &expt, &signflag, &dtoaend);
733 } else {
734 fparg.dbl = GETARG(double);
735 dtoaresult = cp =
736 __hdtoa(fparg.dbl, xdigs, prec,
737 &expt, &signflag, &dtoaend);
738 }
739 if (prec < 0)
740 prec = dtoaend - cp;
741 if (expt == INT_MAX)
742 ox[1] = '\0';
743 goto fp_common;
744 case 'e':
745 case 'E':
746 expchar = ch;
747 if (prec < 0) /* account for digit before decpt */
748 prec = DEFPREC + 1;
749 else
750 prec++;
751 goto fp_begin;
752 case 'f':
753 case 'F':
754 expchar = '\0';
755 goto fp_begin;
756 case 'g':
757 case 'G':
758 expchar = ch - ('g' - 'e');
759 if (prec == 0)
760 prec = 1;
761 fp_begin:
762 if (prec < 0)
763 prec = DEFPREC;
764 if (dtoaresult != NULL)
765 freedtoa(dtoaresult);
766 if (flags & LONGDBL) {
767 fparg.ldbl = GETARG(long double);
768 dtoaresult = cp =
769 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
770 &expt, &signflag, &dtoaend);
771 } else {
772 fparg.dbl = GETARG(double);
773 dtoaresult = cp =
774 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
775 &expt, &signflag, &dtoaend);
776 if (expt == 9999)
777 expt = INT_MAX;
778 }
779 fp_common:
780 if (signflag)
781 sign = '-';
782 if (expt == INT_MAX) { /* inf or nan */
783 if (*cp == 'N') {
784 cp = (ch >= 'a') ? "nan" : "NAN";
785 sign = '\0';
786 } else
787 cp = (ch >= 'a') ? "inf" : "INF";
788 size = 3;
789 flags &= ~ZEROPAD;
790 break;
791 }
792 flags |= FPT;
793 ndig = dtoaend - cp;
794 if (ch == 'g' || ch == 'G') {
795 if (expt > -4 && expt <= prec) {
796 /* Make %[gG] smell like %[fF] */
797 expchar = '\0';
798 if (flags & ALT)
799 prec -= expt;
800 else
801 prec = ndig - expt;
802 if (prec < 0)
803 prec = 0;
804 } else {
805 /*
806 * Make %[gG] smell like %[eE], but
807 * trim trailing zeroes if no # flag.
808 */
809 if (!(flags & ALT))
810 prec = ndig;
811 }
812 }
813 if (expchar) {
814 expsize = exponent(expstr, expt - 1, expchar);
815 size = expsize + prec;
816 if (prec > 1 || flags & ALT)
817 size += decpt_len;
818 } else {
819 /* space for digits before decimal point */
820 if (expt > 0)
821 size = expt;
822 else /* "0" */
823 size = 1;
824 /* space for decimal pt and following digits */
825 if (prec || flags & ALT)
826 size += prec + decpt_len;
827 if ((flags & GROUPING) && expt > 0)
828 size += grouping_init(&gs, expt, locale);
829 }
830 break;
831 #endif /* !NO_FLOATING_POINT */
832 case 'm':
833 error = __strerror_rl(serrno, errnomsg,
834 sizeof(errnomsg), locale);
835 cp = error == 0 ? errnomsg : "<strerror failure>";
836 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
837 sign = '\0';
838 break;
839 case 'n':
840 /*
841 * Assignment-like behavior is specified if the
842 * value overflows or is otherwise unrepresentable.
843 * C99 says to use `signed char' for %hhn conversions.
844 */
845 if (flags & LLONGINT)
846 *GETARG(long long *) = ret;
847 else if (flags & SIZET)
848 *GETARG(ssize_t *) = (ssize_t)ret;
849 else if (flags & PTRDIFFT)
850 *GETARG(ptrdiff_t *) = ret;
851 else if (flags & INTMAXT)
852 *GETARG(intmax_t *) = ret;
853 else if (flags & LONGINT)
854 *GETARG(long *) = ret;
855 else if (flags & SHORTINT)
856 *GETARG(short *) = ret;
857 else if (flags & CHARINT)
858 *GETARG(signed char *) = ret;
859 else
860 *GETARG(int *) = ret;
861 continue; /* no output */
862 case 'O':
863 flags |= LONGINT;
864 /*FALLTHROUGH*/
865 case 'o':
866 if (flags & INTMAX_SIZE)
867 ujval = UJARG();
868 else
869 ulval = UARG();
870 base = 8;
871 goto nosign;
872 case 'p':
873 /*-
874 * ``The argument shall be a pointer to void. The
875 * value of the pointer is converted to a sequence
876 * of printable characters, in an implementation-
877 * defined manner.''
878 * -- ANSI X3J11
879 */
880 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
881 base = 16;
882 xdigs = xdigs_lower;
883 flags = flags | INTMAXT;
884 ox[1] = 'x';
885 goto nosign;
886 case 'S':
887 flags |= LONGINT;
888 /*FALLTHROUGH*/
889 case 's':
890 if (flags & LONGINT) {
891 wchar_t *wcp;
892
893 if (convbuf != NULL)
894 free(convbuf);
895 if ((wcp = GETARG(wchar_t *)) == NULL)
896 cp = "(null)";
897 else {
898 convbuf = __wcsconv(wcp, prec);
899 if (convbuf == NULL) {
900 fp->_flags |= __SERR;
901 goto error;
902 }
903 cp = convbuf;
904 }
905 } else if ((cp = GETARG(char *)) == NULL)
906 cp = "(null)";
907 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
908 sign = '\0';
909 break;
910 case 'U':
911 flags |= LONGINT;
912 /*FALLTHROUGH*/
913 case 'u':
914 if (flags & INTMAX_SIZE)
915 ujval = UJARG();
916 else
917 ulval = UARG();
918 base = 10;
919 goto nosign;
920 case 'X':
921 xdigs = xdigs_upper;
922 goto hex;
923 case 'x':
924 xdigs = xdigs_lower;
925 hex:
926 if (flags & INTMAX_SIZE)
927 ujval = UJARG();
928 else
929 ulval = UARG();
930 base = 16;
931 /* leading 0x/X only if non-zero */
932 if (flags & ALT &&
933 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
934 ox[1] = ch;
935
936 flags &= ~GROUPING;
937 /* unsigned conversions */
938 nosign: sign = '\0';
939 /*-
940 * ``... diouXx conversions ... if a precision is
941 * specified, the 0 flag will be ignored.''
942 * -- ANSI X3J11
943 */
944 number: if ((dprec = prec) >= 0)
945 flags &= ~ZEROPAD;
946
947 /*-
948 * ``The result of converting a zero value with an
949 * explicit precision of zero is no characters.''
950 * -- ANSI X3J11
951 *
952 * ``The C Standard is clear enough as is. The call
953 * printf("%#.0o", 0) should print 0.''
954 * -- Defect Report #151
955 */
956 cp = buf + BUF;
957 if (flags & INTMAX_SIZE) {
958 if (ujval != 0 || prec != 0 ||
959 (flags & ALT && base == 8))
960 cp = __ujtoa(ujval, cp, base,
961 flags & ALT, xdigs);
962 } else {
963 if (ulval != 0 || prec != 0 ||
964 (flags & ALT && base == 8))
965 cp = __ultoa(ulval, cp, base,
966 flags & ALT, xdigs);
967 }
968 size = buf + BUF - cp;
969 if (size > BUF) /* should never happen */
970 abort();
971 if ((flags & GROUPING) && size != 0)
972 size += grouping_init(&gs, size, locale);
973 break;
974 default: /* "%?" prints ?, unless ? is NUL */
975 if (ch == '\0')
976 goto done;
977 invalid:
978 /* pretend it was %c with argument ch */
979 cp = buf;
980 *cp = ch;
981 size = 1;
982 sign = '\0';
983 break;
984 }
985
986 /*
987 * All reasonable formats wind up here. At this point, `cp'
988 * points to a string which (if not flags&LADJUST) should be
989 * padded out to `width' places. If flags&ZEROPAD, it should
990 * first be prefixed by any sign or other prefix; otherwise,
991 * it should be blank padded before the prefix is emitted.
992 * After any left-hand padding and prefixing, emit zeroes
993 * required by a decimal [diouxX] precision, then print the
994 * string proper, then emit zeroes required by any leftover
995 * floating precision; finally, if LADJUST, pad with blanks.
996 *
997 * Compute actual size, so we know how much to pad.
998 * size excludes decimal prec; realsz includes it.
999 */
1000 realsz = dprec > size ? dprec : size;
1001 if (sign)
1002 realsz++;
1003 if (ox[1])
1004 realsz += 2;
1005
1006 prsize = width > realsz ? width : realsz;
1007 if ((unsigned)ret + prsize > INT_MAX) {
1008 ret = EOF;
1009 errno = EOVERFLOW;
1010 goto error;
1011 }
1012
1013 /* right-adjusting blank padding */
1014 if ((flags & (LADJUST|ZEROPAD)) == 0)
1015 PAD(width - realsz, blanks);
1016
1017 /* prefix */
1018 if (sign)
1019 PRINT(&sign, 1);
1020
1021 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1022 ox[0] = '0';
1023 PRINT(ox, 2);
1024 }
1025
1026 /* right-adjusting zero padding */
1027 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1028 PAD(width - realsz, zeroes);
1029
1030 /* the string or number proper */
1031 #ifndef NO_FLOATING_POINT
1032 if ((flags & FPT) == 0) {
1033 #endif
1034 /* leading zeroes from decimal precision */
1035 PAD(dprec - size, zeroes);
1036 if (gs.grouping) {
1037 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1038 goto error;
1039 } else {
1040 PRINT(cp, size);
1041 }
1042 #ifndef NO_FLOATING_POINT
1043 } else { /* glue together f_p fragments */
1044 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1045 if (expt <= 0) {
1046 PRINT(zeroes, 1);
1047 if (prec || flags & ALT)
1048 PRINT(decimal_point,decpt_len);
1049 PAD(-expt, zeroes);
1050 /* already handled initial 0's */
1051 prec += expt;
1052 } else {
1053 if (gs.grouping) {
1054 n = grouping_print(&gs, &io,
1055 cp, dtoaend, locale);
1056 if (n < 0)
1057 goto error;
1058 cp += n;
1059 } else {
1060 PRINTANDPAD(cp, dtoaend,
1061 expt, zeroes);
1062 cp += expt;
1063 }
1064 if (prec || flags & ALT)
1065 PRINT(decimal_point,decpt_len);
1066 }
1067 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1068 } else { /* %[eE] or sufficiently long %[gG] */
1069 if (prec > 1 || flags & ALT) {
1070 PRINT(cp++, 1);
1071 PRINT(decimal_point, decpt_len);
1072 PRINT(cp, ndig-1);
1073 PAD(prec - ndig, zeroes);
1074 } else /* XeYYY */
1075 PRINT(cp, 1);
1076 PRINT(expstr, expsize);
1077 }
1078 }
1079 #endif
1080 /* left-adjusting padding (always blank) */
1081 if (flags & LADJUST)
1082 PAD(width - realsz, blanks);
1083
1084 /* finally, adjust ret */
1085 ret += prsize;
1086
1087 FLUSH(); /* copy out the I/O vectors */
1088 }
1089 done:
1090 FLUSH();
1091 error:
1092 va_end(orgap);
1093 #ifndef NO_FLOATING_POINT
1094 if (dtoaresult != NULL)
1095 freedtoa(dtoaresult);
1096 #endif
1097 if (convbuf != NULL)
1098 free(convbuf);
1099 if (__sferror(fp))
1100 ret = EOF;
1101 else
1102 fp->_flags |= savserr;
1103 if ((argtable != NULL) && (argtable != statargtable))
1104 free (argtable);
1105 return (ret);
1106 /* NOTREACHED */
1107 }
1108
1109