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