Deleted Added
full compact
vfprintf.c (256281) vfprintf.c (269482)
1/*-
2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Chris Torek.
7 *
8 * Copyright (c) 2011 The FreeBSD Foundation
9 * All rights reserved.
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38#if defined(LIBC_SCCS) && !defined(lint)
39static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
40#endif /* LIBC_SCCS and not lint */
41#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Chris Torek.
7 *
8 * Copyright (c) 2011 The FreeBSD Foundation
9 * All rights reserved.
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38#if defined(LIBC_SCCS) && !defined(lint)
39static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
40#endif /* LIBC_SCCS and not lint */
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: stable/10/lib/libc/stdio/vfprintf.c 249808 2013-04-23 13:33:13Z emaste $");
42__FBSDID("$FreeBSD: stable/10/lib/libc/stdio/vfprintf.c 269482 2014-08-03 18:28:10Z pfg $");
43
44/*
45 * Actual printf innards.
46 *
47 * This code is large and complicated...
48 */
49
50#include "namespace.h"
51#include <sys/types.h>
52
53#include <ctype.h>
54#include <errno.h>
55#include <limits.h>
56#include <locale.h>
57#include <stddef.h>
58#include <stdint.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <wchar.h>
63#include <printf.h>
64
65#include <stdarg.h>
66#include "xlocale_private.h"
67#include "un-namespace.h"
68
69#include "libc_private.h"
70#include "local.h"
71#include "fvwrite.h"
72#include "printflocal.h"
73
74static int __sprint(FILE *, struct __suio *, locale_t);
75static int __sbprintf(FILE *, locale_t, const char *, va_list) __printflike(3, 0)
76 __noinline;
77static char *__wcsconv(wchar_t *, int);
78
79#define CHAR char
80#include "printfcommon.h"
81
82struct 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 */
96static int
97grouping_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 */
124static int
125grouping_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 */
155static int
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 */
175static int
176__sbprintf(FILE *fp, locale_t locale, 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, 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 */
214static char *
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 */
270int
271vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0,
272 va_list ap)
273{
274 int ret;
275 FIX_LOCALE(locale);
276
277 FLOCKFILE(fp);
278 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
279 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
280 fp->_file >= 0)
281 ret = __sbprintf(fp, locale, fmt0, ap);
282 else
283 ret = __vfprintf(fp, locale, fmt0, ap);
284 FUNLOCKFILE(fp);
285 return (ret);
286}
287int
288vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
289{
290 return vfprintf_l(fp, __get_locale(), fmt0, ap);
291}
292
293/*
294 * The size of the buffer we use as scratch space for integer
295 * conversions, among other things. We need enough space to
296 * write a uintmax_t in octal (plus one byte).
297 */
298#if UINTMAX_MAX <= UINT64_MAX
299#define BUF 32
300#else
301#error "BUF must be large enough to format a uintmax_t"
302#endif
303
304/*
305 * Non-MT-safe version
306 */
307int
308__vfprintf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
309{
310 char *fmt; /* format string */
311 int ch; /* character from fmt */
312 int n, n2; /* handy integer (short term usage) */
313 char *cp; /* handy char pointer (short term usage) */
314 int flags; /* flags as above */
315 int ret; /* return value accumulator */
316 int width; /* width from format (%8d), or 0 */
317 int prec; /* precision from format; <0 for N/A */
318 char sign; /* sign prefix (' ', '+', '-', or \0) */
319 struct grouping_state gs; /* thousands' grouping info */
320
321#ifndef NO_FLOATING_POINT
322 /*
323 * We can decompose the printed representation of floating
324 * point numbers into several parts, some of which may be empty:
325 *
326 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
327 * A B ---C--- D E F
328 *
329 * A: 'sign' holds this value if present; '\0' otherwise
330 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
331 * C: cp points to the string MMMNNN. Leading and trailing
332 * zeros are not in the string and must be added.
333 * D: expchar holds this character; '\0' if no exponent, e.g. %f
334 * F: at least two digits for decimal, at least one digit for hex
335 */
336 char *decimal_point; /* locale specific decimal point */
337 int decpt_len; /* length of decimal_point */
338 int signflag; /* true if float is negative */
339 union { /* floating point arguments %[aAeEfFgG] */
340 double dbl;
341 long double ldbl;
342 } fparg;
343 int expt; /* integer value of exponent */
344 char expchar; /* exponent character: [eEpP\0] */
345 char *dtoaend; /* pointer to end of converted digits */
346 int expsize; /* character count for expstr */
347 int ndig; /* actual number of digits returned by dtoa */
348 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
349 char *dtoaresult; /* buffer allocated by dtoa */
350#endif
351 u_long ulval; /* integer arguments %[diouxX] */
352 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
353 int base; /* base for [diouxX] conversion */
354 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
355 int realsz; /* field size expanded by dprec, sign, etc */
356 int size; /* size of converted field or string */
357 int prsize; /* max size of printed field */
358 const char *xdigs; /* digits for %[xX] conversion */
359 struct io_state io; /* I/O buffering state */
360 char buf[BUF]; /* buffer with space for digits of uintmax_t */
361 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
362 union arg *argtable; /* args, built due to positional arg */
363 union arg statargtable [STATIC_ARG_TBL_SIZE];
364 int nextarg; /* 1-based argument index */
365 va_list orgap; /* original argument pointer */
366 char *convbuf; /* wide to multibyte conversion result */
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 */
43
44/*
45 * Actual printf innards.
46 *
47 * This code is large and complicated...
48 */
49
50#include "namespace.h"
51#include <sys/types.h>
52
53#include <ctype.h>
54#include <errno.h>
55#include <limits.h>
56#include <locale.h>
57#include <stddef.h>
58#include <stdint.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <wchar.h>
63#include <printf.h>
64
65#include <stdarg.h>
66#include "xlocale_private.h"
67#include "un-namespace.h"
68
69#include "libc_private.h"
70#include "local.h"
71#include "fvwrite.h"
72#include "printflocal.h"
73
74static int __sprint(FILE *, struct __suio *, locale_t);
75static int __sbprintf(FILE *, locale_t, const char *, va_list) __printflike(3, 0)
76 __noinline;
77static char *__wcsconv(wchar_t *, int);
78
79#define CHAR char
80#include "printfcommon.h"
81
82struct 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 */
96static int
97grouping_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 */
124static int
125grouping_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 */
155static int
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 */
175static int
176__sbprintf(FILE *fp, locale_t locale, 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, 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 */
214static char *
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 */
270int
271vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0,
272 va_list ap)
273{
274 int ret;
275 FIX_LOCALE(locale);
276
277 FLOCKFILE(fp);
278 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
279 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
280 fp->_file >= 0)
281 ret = __sbprintf(fp, locale, fmt0, ap);
282 else
283 ret = __vfprintf(fp, locale, fmt0, ap);
284 FUNLOCKFILE(fp);
285 return (ret);
286}
287int
288vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
289{
290 return vfprintf_l(fp, __get_locale(), fmt0, ap);
291}
292
293/*
294 * The size of the buffer we use as scratch space for integer
295 * conversions, among other things. We need enough space to
296 * write a uintmax_t in octal (plus one byte).
297 */
298#if UINTMAX_MAX <= UINT64_MAX
299#define BUF 32
300#else
301#error "BUF must be large enough to format a uintmax_t"
302#endif
303
304/*
305 * Non-MT-safe version
306 */
307int
308__vfprintf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
309{
310 char *fmt; /* format string */
311 int ch; /* character from fmt */
312 int n, n2; /* handy integer (short term usage) */
313 char *cp; /* handy char pointer (short term usage) */
314 int flags; /* flags as above */
315 int ret; /* return value accumulator */
316 int width; /* width from format (%8d), or 0 */
317 int prec; /* precision from format; <0 for N/A */
318 char sign; /* sign prefix (' ', '+', '-', or \0) */
319 struct grouping_state gs; /* thousands' grouping info */
320
321#ifndef NO_FLOATING_POINT
322 /*
323 * We can decompose the printed representation of floating
324 * point numbers into several parts, some of which may be empty:
325 *
326 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
327 * A B ---C--- D E F
328 *
329 * A: 'sign' holds this value if present; '\0' otherwise
330 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
331 * C: cp points to the string MMMNNN. Leading and trailing
332 * zeros are not in the string and must be added.
333 * D: expchar holds this character; '\0' if no exponent, e.g. %f
334 * F: at least two digits for decimal, at least one digit for hex
335 */
336 char *decimal_point; /* locale specific decimal point */
337 int decpt_len; /* length of decimal_point */
338 int signflag; /* true if float is negative */
339 union { /* floating point arguments %[aAeEfFgG] */
340 double dbl;
341 long double ldbl;
342 } fparg;
343 int expt; /* integer value of exponent */
344 char expchar; /* exponent character: [eEpP\0] */
345 char *dtoaend; /* pointer to end of converted digits */
346 int expsize; /* character count for expstr */
347 int ndig; /* actual number of digits returned by dtoa */
348 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
349 char *dtoaresult; /* buffer allocated by dtoa */
350#endif
351 u_long ulval; /* integer arguments %[diouxX] */
352 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
353 int base; /* base for [diouxX] conversion */
354 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
355 int realsz; /* field size expanded by dprec, sign, etc */
356 int size; /* size of converted field or string */
357 int prsize; /* max size of printed field */
358 const char *xdigs; /* digits for %[xX] conversion */
359 struct io_state io; /* I/O buffering state */
360 char buf[BUF]; /* buffer with space for digits of uintmax_t */
361 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
362 union arg *argtable; /* args, built due to positional arg */
363 union arg statargtable [STATIC_ARG_TBL_SIZE];
364 int nextarg; /* 1-based argument index */
365 va_list orgap; /* original argument pointer */
366 char *convbuf; /* wide to multibyte conversion result */
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)
458 if (prepwrite(fp) != 0) {
459 errno = EBADF;
459 return (EOF);
460 return (EOF);
461 }
460
461 convbuf = NULL;
462 fmt = (char *)fmt0;
463 argtable = NULL;
464 nextarg = 1;
465 va_copy(orgap, ap);
466 io_init(&io, fp);
467 ret = 0;
468#ifndef NO_FLOATING_POINT
469 dtoaresult = NULL;
470 decimal_point = localeconv_l(locale)->decimal_point;
471 /* The overwhelmingly common case is decpt_len == 1. */
472 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
473#endif
474
475 /*
476 * Scan the format for conversions (`%' character).
477 */
478 for (;;) {
479 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
480 /* void */;
481 if ((n = fmt - cp) != 0) {
482 if ((unsigned)ret + n > INT_MAX) {
483 ret = EOF;
484 errno = EOVERFLOW;
485 goto error;
486 }
487 PRINT(cp, n);
488 ret += n;
489 }
490 if (ch == '\0')
491 goto done;
492 fmt++; /* skip over '%' */
493
494 flags = 0;
495 dprec = 0;
496 width = 0;
497 prec = -1;
498 gs.grouping = NULL;
499 sign = '\0';
500 ox[1] = '\0';
501
502rflag: ch = *fmt++;
503reswitch: switch (ch) {
504 case ' ':
505 /*-
506 * ``If the space and + flags both appear, the space
507 * flag will be ignored.''
508 * -- ANSI X3J11
509 */
510 if (!sign)
511 sign = ' ';
512 goto rflag;
513 case '#':
514 flags |= ALT;
515 goto rflag;
516 case '*':
517 /*-
518 * ``A negative field width argument is taken as a
519 * - flag followed by a positive field width.''
520 * -- ANSI X3J11
521 * They don't exclude field widths read from args.
522 */
523 GETASTER (width);
524 if (width >= 0)
525 goto rflag;
526 width = -width;
527 /* FALLTHROUGH */
528 case '-':
529 flags |= LADJUST;
530 goto rflag;
531 case '+':
532 sign = '+';
533 goto rflag;
534 case '\'':
535 flags |= GROUPING;
536 goto rflag;
537 case '.':
538 if ((ch = *fmt++) == '*') {
539 GETASTER (prec);
540 goto rflag;
541 }
542 prec = 0;
543 while (is_digit(ch)) {
544 prec = 10 * prec + to_digit(ch);
545 ch = *fmt++;
546 }
547 goto reswitch;
548 case '0':
549 /*-
550 * ``Note that 0 is taken as a flag, not as the
551 * beginning of a field width.''
552 * -- ANSI X3J11
553 */
554 flags |= ZEROPAD;
555 goto rflag;
556 case '1': case '2': case '3': case '4':
557 case '5': case '6': case '7': case '8': case '9':
558 n = 0;
559 do {
560 n = 10 * n + to_digit(ch);
561 ch = *fmt++;
562 } while (is_digit(ch));
563 if (ch == '$') {
564 nextarg = n;
565 if (argtable == NULL) {
566 argtable = statargtable;
567 if (__find_arguments (fmt0, orgap,
568 &argtable)) {
569 ret = EOF;
570 goto error;
571 }
572 }
573 goto rflag;
574 }
575 width = n;
576 goto reswitch;
577#ifndef NO_FLOATING_POINT
578 case 'L':
579 flags |= LONGDBL;
580 goto rflag;
581#endif
582 case 'h':
583 if (flags & SHORTINT) {
584 flags &= ~SHORTINT;
585 flags |= CHARINT;
586 } else
587 flags |= SHORTINT;
588 goto rflag;
589 case 'j':
590 flags |= INTMAXT;
591 goto rflag;
592 case 'l':
593 if (flags & LONGINT) {
594 flags &= ~LONGINT;
595 flags |= LLONGINT;
596 } else
597 flags |= LONGINT;
598 goto rflag;
599 case 'q':
600 flags |= LLONGINT; /* not necessarily */
601 goto rflag;
602 case 't':
603 flags |= PTRDIFFT;
604 goto rflag;
605 case 'z':
606 flags |= SIZET;
607 goto rflag;
608 case 'C':
609 flags |= LONGINT;
610 /*FALLTHROUGH*/
611 case 'c':
612 if (flags & LONGINT) {
613 static const mbstate_t initial;
614 mbstate_t mbs;
615 size_t mbseqlen;
616
617 mbs = initial;
618 mbseqlen = wcrtomb(cp = buf,
619 (wchar_t)GETARG(wint_t), &mbs);
620 if (mbseqlen == (size_t)-1) {
621 fp->_flags |= __SERR;
622 goto error;
623 }
624 size = (int)mbseqlen;
625 } else {
626 *(cp = buf) = GETARG(int);
627 size = 1;
628 }
629 sign = '\0';
630 break;
631 case 'D':
632 flags |= LONGINT;
633 /*FALLTHROUGH*/
634 case 'd':
635 case 'i':
636 if (flags & INTMAX_SIZE) {
637 ujval = SJARG();
638 if ((intmax_t)ujval < 0) {
639 ujval = -ujval;
640 sign = '-';
641 }
642 } else {
643 ulval = SARG();
644 if ((long)ulval < 0) {
645 ulval = -ulval;
646 sign = '-';
647 }
648 }
649 base = 10;
650 goto number;
651#ifndef NO_FLOATING_POINT
652 case 'a':
653 case 'A':
654 if (ch == 'a') {
655 ox[1] = 'x';
656 xdigs = xdigs_lower;
657 expchar = 'p';
658 } else {
659 ox[1] = 'X';
660 xdigs = xdigs_upper;
661 expchar = 'P';
662 }
663 if (prec >= 0)
664 prec++;
665 if (dtoaresult != NULL)
666 freedtoa(dtoaresult);
667 if (flags & LONGDBL) {
668 fparg.ldbl = GETARG(long double);
669 dtoaresult = cp =
670 __hldtoa(fparg.ldbl, xdigs, prec,
671 &expt, &signflag, &dtoaend);
672 } else {
673 fparg.dbl = GETARG(double);
674 dtoaresult = cp =
675 __hdtoa(fparg.dbl, xdigs, prec,
676 &expt, &signflag, &dtoaend);
677 }
678 if (prec < 0)
679 prec = dtoaend - cp;
680 if (expt == INT_MAX)
681 ox[1] = '\0';
682 goto fp_common;
683 case 'e':
684 case 'E':
685 expchar = ch;
686 if (prec < 0) /* account for digit before decpt */
687 prec = DEFPREC + 1;
688 else
689 prec++;
690 goto fp_begin;
691 case 'f':
692 case 'F':
693 expchar = '\0';
694 goto fp_begin;
695 case 'g':
696 case 'G':
697 expchar = ch - ('g' - 'e');
698 if (prec == 0)
699 prec = 1;
700fp_begin:
701 if (prec < 0)
702 prec = DEFPREC;
703 if (dtoaresult != NULL)
704 freedtoa(dtoaresult);
705 if (flags & LONGDBL) {
706 fparg.ldbl = GETARG(long double);
707 dtoaresult = cp =
708 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
709 &expt, &signflag, &dtoaend);
710 } else {
711 fparg.dbl = GETARG(double);
712 dtoaresult = cp =
713 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
714 &expt, &signflag, &dtoaend);
715 if (expt == 9999)
716 expt = INT_MAX;
717 }
718fp_common:
719 if (signflag)
720 sign = '-';
721 if (expt == INT_MAX) { /* inf or nan */
722 if (*cp == 'N') {
723 cp = (ch >= 'a') ? "nan" : "NAN";
724 sign = '\0';
725 } else
726 cp = (ch >= 'a') ? "inf" : "INF";
727 size = 3;
728 flags &= ~ZEROPAD;
729 break;
730 }
731 flags |= FPT;
732 ndig = dtoaend - cp;
733 if (ch == 'g' || ch == 'G') {
734 if (expt > -4 && expt <= prec) {
735 /* Make %[gG] smell like %[fF] */
736 expchar = '\0';
737 if (flags & ALT)
738 prec -= expt;
739 else
740 prec = ndig - expt;
741 if (prec < 0)
742 prec = 0;
743 } else {
744 /*
745 * Make %[gG] smell like %[eE], but
746 * trim trailing zeroes if no # flag.
747 */
748 if (!(flags & ALT))
749 prec = ndig;
750 }
751 }
752 if (expchar) {
753 expsize = exponent(expstr, expt - 1, expchar);
754 size = expsize + prec;
755 if (prec > 1 || flags & ALT)
756 size += decpt_len;
757 } else {
758 /* space for digits before decimal point */
759 if (expt > 0)
760 size = expt;
761 else /* "0" */
762 size = 1;
763 /* space for decimal pt and following digits */
764 if (prec || flags & ALT)
765 size += prec + decpt_len;
766 if ((flags & GROUPING) && expt > 0)
767 size += grouping_init(&gs, expt, locale);
768 }
769 break;
770#endif /* !NO_FLOATING_POINT */
771 case 'n':
772 /*
773 * Assignment-like behavior is specified if the
774 * value overflows or is otherwise unrepresentable.
775 * C99 says to use `signed char' for %hhn conversions.
776 */
777 if (flags & LLONGINT)
778 *GETARG(long long *) = ret;
779 else if (flags & SIZET)
780 *GETARG(ssize_t *) = (ssize_t)ret;
781 else if (flags & PTRDIFFT)
782 *GETARG(ptrdiff_t *) = ret;
783 else if (flags & INTMAXT)
784 *GETARG(intmax_t *) = ret;
785 else if (flags & LONGINT)
786 *GETARG(long *) = ret;
787 else if (flags & SHORTINT)
788 *GETARG(short *) = ret;
789 else if (flags & CHARINT)
790 *GETARG(signed char *) = ret;
791 else
792 *GETARG(int *) = ret;
793 continue; /* no output */
794 case 'O':
795 flags |= LONGINT;
796 /*FALLTHROUGH*/
797 case 'o':
798 if (flags & INTMAX_SIZE)
799 ujval = UJARG();
800 else
801 ulval = UARG();
802 base = 8;
803 goto nosign;
804 case 'p':
805 /*-
806 * ``The argument shall be a pointer to void. The
807 * value of the pointer is converted to a sequence
808 * of printable characters, in an implementation-
809 * defined manner.''
810 * -- ANSI X3J11
811 */
812 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
813 base = 16;
814 xdigs = xdigs_lower;
815 flags = flags | INTMAXT;
816 ox[1] = 'x';
817 goto nosign;
818 case 'S':
819 flags |= LONGINT;
820 /*FALLTHROUGH*/
821 case 's':
822 if (flags & LONGINT) {
823 wchar_t *wcp;
824
825 if (convbuf != NULL)
826 free(convbuf);
827 if ((wcp = GETARG(wchar_t *)) == NULL)
828 cp = "(null)";
829 else {
830 convbuf = __wcsconv(wcp, prec);
831 if (convbuf == NULL) {
832 fp->_flags |= __SERR;
833 goto error;
834 }
835 cp = convbuf;
836 }
837 } else if ((cp = GETARG(char *)) == NULL)
838 cp = "(null)";
839 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
840 sign = '\0';
841 break;
842 case 'U':
843 flags |= LONGINT;
844 /*FALLTHROUGH*/
845 case 'u':
846 if (flags & INTMAX_SIZE)
847 ujval = UJARG();
848 else
849 ulval = UARG();
850 base = 10;
851 goto nosign;
852 case 'X':
853 xdigs = xdigs_upper;
854 goto hex;
855 case 'x':
856 xdigs = xdigs_lower;
857hex:
858 if (flags & INTMAX_SIZE)
859 ujval = UJARG();
860 else
861 ulval = UARG();
862 base = 16;
863 /* leading 0x/X only if non-zero */
864 if (flags & ALT &&
865 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
866 ox[1] = ch;
867
868 flags &= ~GROUPING;
869 /* unsigned conversions */
870nosign: sign = '\0';
871 /*-
872 * ``... diouXx conversions ... if a precision is
873 * specified, the 0 flag will be ignored.''
874 * -- ANSI X3J11
875 */
876number: if ((dprec = prec) >= 0)
877 flags &= ~ZEROPAD;
878
879 /*-
880 * ``The result of converting a zero value with an
881 * explicit precision of zero is no characters.''
882 * -- ANSI X3J11
883 *
884 * ``The C Standard is clear enough as is. The call
885 * printf("%#.0o", 0) should print 0.''
886 * -- Defect Report #151
887 */
888 cp = buf + BUF;
889 if (flags & INTMAX_SIZE) {
890 if (ujval != 0 || prec != 0 ||
891 (flags & ALT && base == 8))
892 cp = __ujtoa(ujval, cp, base,
893 flags & ALT, xdigs);
894 } else {
895 if (ulval != 0 || prec != 0 ||
896 (flags & ALT && base == 8))
897 cp = __ultoa(ulval, cp, base,
898 flags & ALT, xdigs);
899 }
900 size = buf + BUF - cp;
901 if (size > BUF) /* should never happen */
902 abort();
903 if ((flags & GROUPING) && size != 0)
904 size += grouping_init(&gs, size, locale);
905 break;
906 default: /* "%?" prints ?, unless ? is NUL */
907 if (ch == '\0')
908 goto done;
909 /* pretend it was %c with argument ch */
910 cp = buf;
911 *cp = ch;
912 size = 1;
913 sign = '\0';
914 break;
915 }
916
917 /*
918 * All reasonable formats wind up here. At this point, `cp'
919 * points to a string which (if not flags&LADJUST) should be
920 * padded out to `width' places. If flags&ZEROPAD, it should
921 * first be prefixed by any sign or other prefix; otherwise,
922 * it should be blank padded before the prefix is emitted.
923 * After any left-hand padding and prefixing, emit zeroes
924 * required by a decimal [diouxX] precision, then print the
925 * string proper, then emit zeroes required by any leftover
926 * floating precision; finally, if LADJUST, pad with blanks.
927 *
928 * Compute actual size, so we know how much to pad.
929 * size excludes decimal prec; realsz includes it.
930 */
931 realsz = dprec > size ? dprec : size;
932 if (sign)
933 realsz++;
934 if (ox[1])
935 realsz += 2;
936
937 prsize = width > realsz ? width : realsz;
938 if ((unsigned)ret + prsize > INT_MAX) {
939 ret = EOF;
940 errno = EOVERFLOW;
941 goto error;
942 }
943
944 /* right-adjusting blank padding */
945 if ((flags & (LADJUST|ZEROPAD)) == 0)
946 PAD(width - realsz, blanks);
947
948 /* prefix */
949 if (sign)
950 PRINT(&sign, 1);
951
952 if (ox[1]) { /* ox[1] is either x, X, or \0 */
953 ox[0] = '0';
954 PRINT(ox, 2);
955 }
956
957 /* right-adjusting zero padding */
958 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
959 PAD(width - realsz, zeroes);
960
961 /* the string or number proper */
962#ifndef NO_FLOATING_POINT
963 if ((flags & FPT) == 0) {
964#endif
965 /* leading zeroes from decimal precision */
966 PAD(dprec - size, zeroes);
967 if (gs.grouping) {
968 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
969 goto error;
970 } else {
971 PRINT(cp, size);
972 }
973#ifndef NO_FLOATING_POINT
974 } else { /* glue together f_p fragments */
975 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
976 if (expt <= 0) {
977 PRINT(zeroes, 1);
978 if (prec || flags & ALT)
979 PRINT(decimal_point,decpt_len);
980 PAD(-expt, zeroes);
981 /* already handled initial 0's */
982 prec += expt;
983 } else {
984 if (gs.grouping) {
985 n = grouping_print(&gs, &io,
986 cp, dtoaend, locale);
987 if (n < 0)
988 goto error;
989 cp += n;
990 } else {
991 PRINTANDPAD(cp, dtoaend,
992 expt, zeroes);
993 cp += expt;
994 }
995 if (prec || flags & ALT)
996 PRINT(decimal_point,decpt_len);
997 }
998 PRINTANDPAD(cp, dtoaend, prec, zeroes);
999 } else { /* %[eE] or sufficiently long %[gG] */
1000 if (prec > 1 || flags & ALT) {
1001 PRINT(cp++, 1);
1002 PRINT(decimal_point, decpt_len);
1003 PRINT(cp, ndig-1);
1004 PAD(prec - ndig, zeroes);
1005 } else /* XeYYY */
1006 PRINT(cp, 1);
1007 PRINT(expstr, expsize);
1008 }
1009 }
1010#endif
1011 /* left-adjusting padding (always blank) */
1012 if (flags & LADJUST)
1013 PAD(width - realsz, blanks);
1014
1015 /* finally, adjust ret */
1016 ret += prsize;
1017
1018 FLUSH(); /* copy out the I/O vectors */
1019 }
1020done:
1021 FLUSH();
1022error:
1023 va_end(orgap);
1024#ifndef NO_FLOATING_POINT
1025 if (dtoaresult != NULL)
1026 freedtoa(dtoaresult);
1027#endif
1028 if (convbuf != NULL)
1029 free(convbuf);
1030 if (__sferror(fp))
1031 ret = EOF;
1032 if ((argtable != NULL) && (argtable != statargtable))
1033 free (argtable);
1034 return (ret);
1035 /* NOTREACHED */
1036}
1037
462
463 convbuf = NULL;
464 fmt = (char *)fmt0;
465 argtable = NULL;
466 nextarg = 1;
467 va_copy(orgap, ap);
468 io_init(&io, fp);
469 ret = 0;
470#ifndef NO_FLOATING_POINT
471 dtoaresult = NULL;
472 decimal_point = localeconv_l(locale)->decimal_point;
473 /* The overwhelmingly common case is decpt_len == 1. */
474 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
475#endif
476
477 /*
478 * Scan the format for conversions (`%' character).
479 */
480 for (;;) {
481 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
482 /* void */;
483 if ((n = fmt - cp) != 0) {
484 if ((unsigned)ret + n > INT_MAX) {
485 ret = EOF;
486 errno = EOVERFLOW;
487 goto error;
488 }
489 PRINT(cp, n);
490 ret += n;
491 }
492 if (ch == '\0')
493 goto done;
494 fmt++; /* skip over '%' */
495
496 flags = 0;
497 dprec = 0;
498 width = 0;
499 prec = -1;
500 gs.grouping = NULL;
501 sign = '\0';
502 ox[1] = '\0';
503
504rflag: ch = *fmt++;
505reswitch: switch (ch) {
506 case ' ':
507 /*-
508 * ``If the space and + flags both appear, the space
509 * flag will be ignored.''
510 * -- ANSI X3J11
511 */
512 if (!sign)
513 sign = ' ';
514 goto rflag;
515 case '#':
516 flags |= ALT;
517 goto rflag;
518 case '*':
519 /*-
520 * ``A negative field width argument is taken as a
521 * - flag followed by a positive field width.''
522 * -- ANSI X3J11
523 * They don't exclude field widths read from args.
524 */
525 GETASTER (width);
526 if (width >= 0)
527 goto rflag;
528 width = -width;
529 /* FALLTHROUGH */
530 case '-':
531 flags |= LADJUST;
532 goto rflag;
533 case '+':
534 sign = '+';
535 goto rflag;
536 case '\'':
537 flags |= GROUPING;
538 goto rflag;
539 case '.':
540 if ((ch = *fmt++) == '*') {
541 GETASTER (prec);
542 goto rflag;
543 }
544 prec = 0;
545 while (is_digit(ch)) {
546 prec = 10 * prec + to_digit(ch);
547 ch = *fmt++;
548 }
549 goto reswitch;
550 case '0':
551 /*-
552 * ``Note that 0 is taken as a flag, not as the
553 * beginning of a field width.''
554 * -- ANSI X3J11
555 */
556 flags |= ZEROPAD;
557 goto rflag;
558 case '1': case '2': case '3': case '4':
559 case '5': case '6': case '7': case '8': case '9':
560 n = 0;
561 do {
562 n = 10 * n + to_digit(ch);
563 ch = *fmt++;
564 } while (is_digit(ch));
565 if (ch == '$') {
566 nextarg = n;
567 if (argtable == NULL) {
568 argtable = statargtable;
569 if (__find_arguments (fmt0, orgap,
570 &argtable)) {
571 ret = EOF;
572 goto error;
573 }
574 }
575 goto rflag;
576 }
577 width = n;
578 goto reswitch;
579#ifndef NO_FLOATING_POINT
580 case 'L':
581 flags |= LONGDBL;
582 goto rflag;
583#endif
584 case 'h':
585 if (flags & SHORTINT) {
586 flags &= ~SHORTINT;
587 flags |= CHARINT;
588 } else
589 flags |= SHORTINT;
590 goto rflag;
591 case 'j':
592 flags |= INTMAXT;
593 goto rflag;
594 case 'l':
595 if (flags & LONGINT) {
596 flags &= ~LONGINT;
597 flags |= LLONGINT;
598 } else
599 flags |= LONGINT;
600 goto rflag;
601 case 'q':
602 flags |= LLONGINT; /* not necessarily */
603 goto rflag;
604 case 't':
605 flags |= PTRDIFFT;
606 goto rflag;
607 case 'z':
608 flags |= SIZET;
609 goto rflag;
610 case 'C':
611 flags |= LONGINT;
612 /*FALLTHROUGH*/
613 case 'c':
614 if (flags & LONGINT) {
615 static const mbstate_t initial;
616 mbstate_t mbs;
617 size_t mbseqlen;
618
619 mbs = initial;
620 mbseqlen = wcrtomb(cp = buf,
621 (wchar_t)GETARG(wint_t), &mbs);
622 if (mbseqlen == (size_t)-1) {
623 fp->_flags |= __SERR;
624 goto error;
625 }
626 size = (int)mbseqlen;
627 } else {
628 *(cp = buf) = GETARG(int);
629 size = 1;
630 }
631 sign = '\0';
632 break;
633 case 'D':
634 flags |= LONGINT;
635 /*FALLTHROUGH*/
636 case 'd':
637 case 'i':
638 if (flags & INTMAX_SIZE) {
639 ujval = SJARG();
640 if ((intmax_t)ujval < 0) {
641 ujval = -ujval;
642 sign = '-';
643 }
644 } else {
645 ulval = SARG();
646 if ((long)ulval < 0) {
647 ulval = -ulval;
648 sign = '-';
649 }
650 }
651 base = 10;
652 goto number;
653#ifndef NO_FLOATING_POINT
654 case 'a':
655 case 'A':
656 if (ch == 'a') {
657 ox[1] = 'x';
658 xdigs = xdigs_lower;
659 expchar = 'p';
660 } else {
661 ox[1] = 'X';
662 xdigs = xdigs_upper;
663 expchar = 'P';
664 }
665 if (prec >= 0)
666 prec++;
667 if (dtoaresult != NULL)
668 freedtoa(dtoaresult);
669 if (flags & LONGDBL) {
670 fparg.ldbl = GETARG(long double);
671 dtoaresult = cp =
672 __hldtoa(fparg.ldbl, xdigs, prec,
673 &expt, &signflag, &dtoaend);
674 } else {
675 fparg.dbl = GETARG(double);
676 dtoaresult = cp =
677 __hdtoa(fparg.dbl, xdigs, prec,
678 &expt, &signflag, &dtoaend);
679 }
680 if (prec < 0)
681 prec = dtoaend - cp;
682 if (expt == INT_MAX)
683 ox[1] = '\0';
684 goto fp_common;
685 case 'e':
686 case 'E':
687 expchar = ch;
688 if (prec < 0) /* account for digit before decpt */
689 prec = DEFPREC + 1;
690 else
691 prec++;
692 goto fp_begin;
693 case 'f':
694 case 'F':
695 expchar = '\0';
696 goto fp_begin;
697 case 'g':
698 case 'G':
699 expchar = ch - ('g' - 'e');
700 if (prec == 0)
701 prec = 1;
702fp_begin:
703 if (prec < 0)
704 prec = DEFPREC;
705 if (dtoaresult != NULL)
706 freedtoa(dtoaresult);
707 if (flags & LONGDBL) {
708 fparg.ldbl = GETARG(long double);
709 dtoaresult = cp =
710 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
711 &expt, &signflag, &dtoaend);
712 } else {
713 fparg.dbl = GETARG(double);
714 dtoaresult = cp =
715 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
716 &expt, &signflag, &dtoaend);
717 if (expt == 9999)
718 expt = INT_MAX;
719 }
720fp_common:
721 if (signflag)
722 sign = '-';
723 if (expt == INT_MAX) { /* inf or nan */
724 if (*cp == 'N') {
725 cp = (ch >= 'a') ? "nan" : "NAN";
726 sign = '\0';
727 } else
728 cp = (ch >= 'a') ? "inf" : "INF";
729 size = 3;
730 flags &= ~ZEROPAD;
731 break;
732 }
733 flags |= FPT;
734 ndig = dtoaend - cp;
735 if (ch == 'g' || ch == 'G') {
736 if (expt > -4 && expt <= prec) {
737 /* Make %[gG] smell like %[fF] */
738 expchar = '\0';
739 if (flags & ALT)
740 prec -= expt;
741 else
742 prec = ndig - expt;
743 if (prec < 0)
744 prec = 0;
745 } else {
746 /*
747 * Make %[gG] smell like %[eE], but
748 * trim trailing zeroes if no # flag.
749 */
750 if (!(flags & ALT))
751 prec = ndig;
752 }
753 }
754 if (expchar) {
755 expsize = exponent(expstr, expt - 1, expchar);
756 size = expsize + prec;
757 if (prec > 1 || flags & ALT)
758 size += decpt_len;
759 } else {
760 /* space for digits before decimal point */
761 if (expt > 0)
762 size = expt;
763 else /* "0" */
764 size = 1;
765 /* space for decimal pt and following digits */
766 if (prec || flags & ALT)
767 size += prec + decpt_len;
768 if ((flags & GROUPING) && expt > 0)
769 size += grouping_init(&gs, expt, locale);
770 }
771 break;
772#endif /* !NO_FLOATING_POINT */
773 case 'n':
774 /*
775 * Assignment-like behavior is specified if the
776 * value overflows or is otherwise unrepresentable.
777 * C99 says to use `signed char' for %hhn conversions.
778 */
779 if (flags & LLONGINT)
780 *GETARG(long long *) = ret;
781 else if (flags & SIZET)
782 *GETARG(ssize_t *) = (ssize_t)ret;
783 else if (flags & PTRDIFFT)
784 *GETARG(ptrdiff_t *) = ret;
785 else if (flags & INTMAXT)
786 *GETARG(intmax_t *) = ret;
787 else if (flags & LONGINT)
788 *GETARG(long *) = ret;
789 else if (flags & SHORTINT)
790 *GETARG(short *) = ret;
791 else if (flags & CHARINT)
792 *GETARG(signed char *) = ret;
793 else
794 *GETARG(int *) = ret;
795 continue; /* no output */
796 case 'O':
797 flags |= LONGINT;
798 /*FALLTHROUGH*/
799 case 'o':
800 if (flags & INTMAX_SIZE)
801 ujval = UJARG();
802 else
803 ulval = UARG();
804 base = 8;
805 goto nosign;
806 case 'p':
807 /*-
808 * ``The argument shall be a pointer to void. The
809 * value of the pointer is converted to a sequence
810 * of printable characters, in an implementation-
811 * defined manner.''
812 * -- ANSI X3J11
813 */
814 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
815 base = 16;
816 xdigs = xdigs_lower;
817 flags = flags | INTMAXT;
818 ox[1] = 'x';
819 goto nosign;
820 case 'S':
821 flags |= LONGINT;
822 /*FALLTHROUGH*/
823 case 's':
824 if (flags & LONGINT) {
825 wchar_t *wcp;
826
827 if (convbuf != NULL)
828 free(convbuf);
829 if ((wcp = GETARG(wchar_t *)) == NULL)
830 cp = "(null)";
831 else {
832 convbuf = __wcsconv(wcp, prec);
833 if (convbuf == NULL) {
834 fp->_flags |= __SERR;
835 goto error;
836 }
837 cp = convbuf;
838 }
839 } else if ((cp = GETARG(char *)) == NULL)
840 cp = "(null)";
841 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
842 sign = '\0';
843 break;
844 case 'U':
845 flags |= LONGINT;
846 /*FALLTHROUGH*/
847 case 'u':
848 if (flags & INTMAX_SIZE)
849 ujval = UJARG();
850 else
851 ulval = UARG();
852 base = 10;
853 goto nosign;
854 case 'X':
855 xdigs = xdigs_upper;
856 goto hex;
857 case 'x':
858 xdigs = xdigs_lower;
859hex:
860 if (flags & INTMAX_SIZE)
861 ujval = UJARG();
862 else
863 ulval = UARG();
864 base = 16;
865 /* leading 0x/X only if non-zero */
866 if (flags & ALT &&
867 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
868 ox[1] = ch;
869
870 flags &= ~GROUPING;
871 /* unsigned conversions */
872nosign: sign = '\0';
873 /*-
874 * ``... diouXx conversions ... if a precision is
875 * specified, the 0 flag will be ignored.''
876 * -- ANSI X3J11
877 */
878number: if ((dprec = prec) >= 0)
879 flags &= ~ZEROPAD;
880
881 /*-
882 * ``The result of converting a zero value with an
883 * explicit precision of zero is no characters.''
884 * -- ANSI X3J11
885 *
886 * ``The C Standard is clear enough as is. The call
887 * printf("%#.0o", 0) should print 0.''
888 * -- Defect Report #151
889 */
890 cp = buf + BUF;
891 if (flags & INTMAX_SIZE) {
892 if (ujval != 0 || prec != 0 ||
893 (flags & ALT && base == 8))
894 cp = __ujtoa(ujval, cp, base,
895 flags & ALT, xdigs);
896 } else {
897 if (ulval != 0 || prec != 0 ||
898 (flags & ALT && base == 8))
899 cp = __ultoa(ulval, cp, base,
900 flags & ALT, xdigs);
901 }
902 size = buf + BUF - cp;
903 if (size > BUF) /* should never happen */
904 abort();
905 if ((flags & GROUPING) && size != 0)
906 size += grouping_init(&gs, size, locale);
907 break;
908 default: /* "%?" prints ?, unless ? is NUL */
909 if (ch == '\0')
910 goto done;
911 /* pretend it was %c with argument ch */
912 cp = buf;
913 *cp = ch;
914 size = 1;
915 sign = '\0';
916 break;
917 }
918
919 /*
920 * All reasonable formats wind up here. At this point, `cp'
921 * points to a string which (if not flags&LADJUST) should be
922 * padded out to `width' places. If flags&ZEROPAD, it should
923 * first be prefixed by any sign or other prefix; otherwise,
924 * it should be blank padded before the prefix is emitted.
925 * After any left-hand padding and prefixing, emit zeroes
926 * required by a decimal [diouxX] precision, then print the
927 * string proper, then emit zeroes required by any leftover
928 * floating precision; finally, if LADJUST, pad with blanks.
929 *
930 * Compute actual size, so we know how much to pad.
931 * size excludes decimal prec; realsz includes it.
932 */
933 realsz = dprec > size ? dprec : size;
934 if (sign)
935 realsz++;
936 if (ox[1])
937 realsz += 2;
938
939 prsize = width > realsz ? width : realsz;
940 if ((unsigned)ret + prsize > INT_MAX) {
941 ret = EOF;
942 errno = EOVERFLOW;
943 goto error;
944 }
945
946 /* right-adjusting blank padding */
947 if ((flags & (LADJUST|ZEROPAD)) == 0)
948 PAD(width - realsz, blanks);
949
950 /* prefix */
951 if (sign)
952 PRINT(&sign, 1);
953
954 if (ox[1]) { /* ox[1] is either x, X, or \0 */
955 ox[0] = '0';
956 PRINT(ox, 2);
957 }
958
959 /* right-adjusting zero padding */
960 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
961 PAD(width - realsz, zeroes);
962
963 /* the string or number proper */
964#ifndef NO_FLOATING_POINT
965 if ((flags & FPT) == 0) {
966#endif
967 /* leading zeroes from decimal precision */
968 PAD(dprec - size, zeroes);
969 if (gs.grouping) {
970 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
971 goto error;
972 } else {
973 PRINT(cp, size);
974 }
975#ifndef NO_FLOATING_POINT
976 } else { /* glue together f_p fragments */
977 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
978 if (expt <= 0) {
979 PRINT(zeroes, 1);
980 if (prec || flags & ALT)
981 PRINT(decimal_point,decpt_len);
982 PAD(-expt, zeroes);
983 /* already handled initial 0's */
984 prec += expt;
985 } else {
986 if (gs.grouping) {
987 n = grouping_print(&gs, &io,
988 cp, dtoaend, locale);
989 if (n < 0)
990 goto error;
991 cp += n;
992 } else {
993 PRINTANDPAD(cp, dtoaend,
994 expt, zeroes);
995 cp += expt;
996 }
997 if (prec || flags & ALT)
998 PRINT(decimal_point,decpt_len);
999 }
1000 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1001 } else { /* %[eE] or sufficiently long %[gG] */
1002 if (prec > 1 || flags & ALT) {
1003 PRINT(cp++, 1);
1004 PRINT(decimal_point, decpt_len);
1005 PRINT(cp, ndig-1);
1006 PAD(prec - ndig, zeroes);
1007 } else /* XeYYY */
1008 PRINT(cp, 1);
1009 PRINT(expstr, expsize);
1010 }
1011 }
1012#endif
1013 /* left-adjusting padding (always blank) */
1014 if (flags & LADJUST)
1015 PAD(width - realsz, blanks);
1016
1017 /* finally, adjust ret */
1018 ret += prsize;
1019
1020 FLUSH(); /* copy out the I/O vectors */
1021 }
1022done:
1023 FLUSH();
1024error:
1025 va_end(orgap);
1026#ifndef NO_FLOATING_POINT
1027 if (dtoaresult != NULL)
1028 freedtoa(dtoaresult);
1029#endif
1030 if (convbuf != NULL)
1031 free(convbuf);
1032 if (__sferror(fp))
1033 ret = EOF;
1034 if ((argtable != NULL) && (argtable != statargtable))
1035 free (argtable);
1036 return (ret);
1037 /* NOTREACHED */
1038}
1039