2 * This file based on printf.c from 'Dlibs' on the atari ST (RdeBath)
5 * Dale Schumacher 399 Beacon Ave.
6 * (alias: Dalnefre') St. Paul, MN 55104
7 * dal@syntel.UUCP United States of America
8 * "It's not reality that's important, but how you perceive things."
11 /* Altered to use stdarg, made the core function vfnprintf.
12 * Hooked into the stdio package using 'inside information'
13 * Altered sizeof() assumptions, now assumes all integers except chars
15 * sizeof(xxx) == sizeof(long) or sizeof(xxx) == sizeof(short)
21 * Manuel Novoa III Dec 2000
23 * The previous vfnprintf routine was almost completely rewritten with the
24 * goal of fixing some shortcomings and reducing object size.
26 * The summary of changes:
28 * Converted print conversion specification parsing from one big switch
29 * to a method using string tables. This new method verifies that the
30 * conversion flags, field width, precision, qualifier, and specifier
31 * appear in the correct order. Many questionable specifications were
32 * accepted by the previous code. This new method also resulted in a
33 * substantial reduction in object size of about 330 bytes (20%) from
34 * the old version (1627 bytes) on i386, even with the following
37 * Implemented %n specifier as required by the standards.
38 * Implemented proper handling of precision for int types.
39 * Implemented # for hex and pointer, fixed error for octal rep of 0.
40 * Implemented return of -1 on stream error.
42 * Added optional support for the GNU extension %m which prints the string
43 * corresponding the errno.
45 * Added optional support for long long ints and unsigned long long ints
46 * using the conversion qualifiers "ll", "L", or "q" (like glibc).
48 * Added optional support for doubles in a very limited form. None of
49 * the formating options are obeyed. The string returned by __dtostr
50 * is printed directly.
52 * Converted to use my (un)signed long (long) to string routines, which are
53 * smaller than the previous functions and don't require static buffers.
55 * Other Modifications:
56 * Modified sprintf, snprintf, vsprintf, vsnprintf to share on fake-file.
60 * Manuel Novoa III Jan 2001
62 * Removed fake file from *s*printf functions because of possible problems
63 * if called recursively. Instead, have sprintf, snprintf, and vsprintf
64 * call vsnprintf which allocates a fake file on the stack.
65 * Removed WANT_FPUTC option. Always use standard putc macro to avoid
66 * problems with the fake file used by the *s*printf functions.
67 * Fixed bug parsing flags -- did not restart scan.
68 * Added function asprintf.
69 * Fixed 0-pad prefixing bug.
70 * Converted sizeof(int) == sizeof(long) tests to compile time vs run time.
71 * This saves 112 bytes of code on i386.
72 * Fixed precision bug -- when negative set to default.
73 * Added function fnprintf to support __dtostr.
74 * Added floating point support for doubles. Yeah!
77 * May 2001 Fixes from Johan Adolfsson (johan.adolfsson@axis.com)
78 * 1) printf("%c",0) returned 0 instead of 1.
79 * 2) unrolled loop in asprintf to reduce size and remove compile warning.
83 * 1) fix %p so that "0x" is prepended to outputed hex val
84 * 2) fix %p so that "(nil)" is output for (void *)0 to match glibc
87 * Convert to new floating point conversion routine.
88 * Fix qualifier handling on integer and %n conversions.
89 * Add support for vsnprintf when in non-buffered/no-wchar configuration.
93 /*****************************************************************************/
95 /*****************************************************************************/
96 /* The optional support for long longs and doubles comes in two forms.
98 * 1) Normal (or partial for doubles) output support. Set to 1 to turn on.
99 * Adds about 130 bytes for doubles, about 220 bytes for long longs,
100 * and about 275 for both to the base code size of 1163 on i386.
103 /* These are now set in uClibc_config.h based on Config. */
105 #define __UCLIBC_HAS_FLOATS__ 1
108 /* 2) An error message is inserted into the stream, an arg of the
109 * appropriate size is removed from the arglist, and processing
110 * continues. This is adds less code and may be useful in some
111 * cases. Set to 1 to turn on. Adds about 50 bytes for doubles,
112 * about 140 bytes for long longs, and about 175 bytes for both
113 * to the base code size of 1163 on i386.
116 #define WANT_FLOAT_ERROR 0
119 * Set to support GNU extension of %m to print string corresponding to errno.
121 * Warning: This adds about 50 bytes (i386) to the code but it also pulls in
122 * strerror and the corresponding string table which together are about 3.8k.
125 /* Now controlled by uClibc_stdio.h and set below. */
126 /* #define WANT_GNU_ERRNO 0 */
128 /**************************************************************************/
137 #include <bits/uClibc_uintmaxtostr.h>
139 #include "_fpmaxtostr.h"
141 /* #undef WANT_FLOAT_ERROR */
142 /* #define WANT_FLOAT_ERROR 1 */
144 /* #define __isdigit(c) (((unsigned int)(c - '0')) < 10) */
146 #ifdef __UCLIBC_HAS_PRINTF_M_SPEC__
147 #define WANT_GNU_ERRNO 1
149 #define WANT_GNU_ERRNO 0
156 #ifdef __STDIO_BUFFERS
158 #define PUTC(C,F) putc_unlocked((C),(F))
159 #define OUTNSTR _outnstr
160 #define _outnstr(stream, string, len) __stdio_fwrite(string, len, stream)
162 #else /* __STDIO_BUFFERS */
166 unsigned char *bufend; /* pointer to 1 past end of buffer */
167 unsigned char *bufpos;
170 #ifdef __UCLIBC_HAS_FLOATS__
171 static void _outnstr(FILE *stream, const unsigned char *s, size_t n)
173 __FILE_vsnprintf *f = (__FILE_vsnprintf *) stream;
175 if (!__STDIO_STREAM_IS_FAKE_VSNPRINTF_NB(&f->f)) {
176 __stdio_fwrite(s, n, &f->f);
177 } else if (f->bufend > f->bufpos) {
178 size_t r = f->bufend - f->bufpos;
182 memcpy(f->bufpos, s, r);
188 static void putc_unlocked_sprintf(int c, __FILE_vsnprintf *f)
190 if (!__STDIO_STREAM_IS_FAKE_VSNPRINTF_NB(&f->f)) {
191 putc_unlocked(c, &f->f);
192 } else if (f->bufpos < f->bufend) {
198 #define PUTC(C,F) putc_unlocked_sprintf((C),(__FILE_vsnprintf *)(F))
199 #define OUTNSTR _outnstr
201 #endif /* __STDIO_BUFFERS */
203 #ifdef __UCLIBC_HAS_FLOATS__
205 static void _charpad(FILE * __restrict stream, int padchar, size_t numpad)
207 /* TODO -- Use a buffer to cut down on function calls... */
212 OUTNSTR(stream, pad, 1);
217 static void _fp_out_narrow(FILE *fp, intptr_t type, intptr_t len, intptr_t buf)
219 if (type & 0x80) { /* Some type of padding needed. */
220 int buflen = strlen((const char *) buf);
221 if ((len -= buflen) > 0) {
222 _charpad(fp, (type & 0x7f), len);
227 OUTNSTR(fp, (const char *) buf, len);
243 static const char spec[] = "+-#0 ";
245 /**********************************************************************/
248 * In order to ease translation to what arginfo and _print_info._flags expect,
249 * we map: 0:int 1:char 2:longlong 4:long 8:short
250 * and then _flags |= (((q << 7) + q) & 0x701) and argtype |= (_flags & 0x701)
254 #error PDS already defined!
257 #error SS already defined!
260 #error IMS already defined!
263 #if PTRDIFF_MAX == INT_MAX
265 #elif PTRDIFF_MAX == LONG_MAX
267 #elif defined(LLONG_MAX) && (PTRDIFF_MAX == LLONG_MAX)
270 #error fix QUAL_CHARS ptrdiff_t entry 't'!
273 #if SIZE_MAX == UINT_MAX
275 #elif SIZE_MAX == ULONG_MAX
277 #elif defined(LLONG_MAX) && (SIZE_MAX == ULLONG_MAX)
280 #error fix QUAL_CHARS size_t entries 'z', 'Z'!
283 #if INTMAX_MAX == INT_MAX
285 #elif INTMAX_MAX == LONG_MAX
287 #elif defined(LLONG_MAX) && (INTMAX_MAX == LLONG_MAX)
290 #error fix QUAL_CHARS intmax_t entry 'j'!
293 #define QUAL_CHARS { \
294 /* j:(u)intmax_t z:(s)size_t t:ptrdiff_t \0:int */ \
295 /* q:long_long Z:(s)size_t */ \
296 'h', 'l', 'L', 'j', 'z', 't', 'q', 'Z', 0, \
297 2, 4, 8, IMS, SS, PDS, 8, SS, 0, /* TODO -- fix!!! */\
301 static const char qual_chars[] = QUAL_CHARS;
303 /* static const char qual[] = "hlLq"; */
304 /**********************************************************************/
306 #if !defined(__UCLIBC_HAS_FLOATS__) && WANT_FLOAT_ERROR
307 static const char dbl_err[] = "<DOUBLE>";
310 #if defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR
311 /* layout 012345678901234567 */
312 static const char u_spec[] = "%nbopxXudicsfgGeEaA";
314 /* layout 0123456789012 */
315 static const char u_spec[] = "%nbopxXudics";
318 /* WARNING: u_spec and u_radix need to stay in agreement!!! */
319 /* u_radix[i] <-> u_spec[i+2] for unsigned entries only */
320 static const char u_radix[] = "\x02\x08\x10\x10\x10\x0a";
322 int vfprintf(FILE * __restrict op, register const char * __restrict fmt,
329 #if LONG_MAX != INT_MAX
334 int i, cnt, dataargtype, len;
335 const void *argptr = argptr; /* ok to be initialized. */
340 int radix, dpoint /*, upcase*/;
341 char tmp[65]; /* TODO - determine needed size from headers */
342 char flag[sizeof(spec)];
343 __STDIO_AUTO_THREADLOCK_VAR;
345 __STDIO_AUTO_THREADLOCK(op);
347 __STDIO_STREAM_VALIDATE(op);
351 if (__STDIO_STREAM_IS_NARROW_WRITING(op)
352 || !__STDIO_STREAM_TRANS_TO_WRITE(op, __FLAG_NARROW)
357 fmt0 = fmt; /* save our position in case of bad format */
359 width = -1; /* min field width */
360 preci = -5; /* max string width or mininum digits */
361 radix = 10; /* number base */
362 dpoint = 0; /* found decimal point */
365 for (p =(char *) spec ; *p ; p++) {
368 flag[FLAG_0_PAD] = ' ';
370 /* process optional flags */
371 for (p = (char *)spec ; *p ; ) {
373 flag[p-spec] = *fmt++;
374 p = (char *)spec; /* restart scan */
380 if (!flag[FLAG_PLUS]) {
381 flag[FLAG_PLUS] = flag[FLAG_SPACE];
384 /* process optional width and precision */
390 if (*fmt == '*') { /* parameter width value */
394 for ( i = 0 ; (*fmt >= '0') && (*fmt <= '9') ; ++fmt ) {
395 i = (i * 10) + (*fmt - '0');
408 flag[FLAG_MINUS_LJUSTIFY] = 1;
411 } while ((*fmt == '.') && !dpoint );
413 /* process optional qualifier */
414 p = (char *) qual_chars;
421 if ((p - qual_chars < 2) && (*fmt == *p)) {
422 p += ((sizeof(qual_chars)-2) / 2);
425 dataargtype = ((int)(p[(sizeof(qual_chars)-2) / 2])) << 8;
429 flag[FLAG_PLUS] = '\0';
430 flag[FLAG_0_PAD] = ' ';
431 p = __glibc_strerror_r(errno, tmp, sizeof(tmp));
436 /* process format specifier */
437 for (p = (char *) u_spec ; *p ; p++) {
438 if (*fmt != *p) continue;
439 if (p-u_spec < 1) { /* print a % */
442 if (p-u_spec < 2) { /* store output count in int ptr */
443 _store_inttype(va_arg(ap, void *),
451 #if INTPTR_MAX == INT_MAX
454 #error Fix dataargtype for pointers!
458 switch(dataargtype) {
459 case (PA_INT|PA_FLAG_LONG_LONG):
461 intarg.ll = va_arg(ap, long long);
465 case (PA_INT|PA_FLAG_LONG):
466 #if LONG_MAX != INT_MAX
467 intarg.l = va_arg(ap, long);
472 intarg.i = va_arg(ap, int);
478 if (p-u_spec < 8) { /* unsigned conversion */
479 radix = u_radix[p-u_spec-2];
480 upcase = ((*p == 'x') ? __UIM_LOWER : __UIM_UPPER);
482 upcase = __UIM_LOWER;
483 flag[FLAG_HASH] = 'p';
485 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
487 _load_inttype(dataargtype, argptr, radix),
490 flag[FLAG_PLUS] = '\0'; /* meaningless for unsigned */
491 if (*p != '0') { /* non-zero */
492 if (flag[FLAG_HASH]) {
494 *--p = '0'; /* add leadding zero */
495 } else if (radix != 10) { /* either 2 or 16 */
496 flag[FLAG_PLUS] = '0';
506 } else if (flag[FLAG_HASH] == 'p') { /* null pointer */
509 } else if (p-u_spec < 10) { /* signed conversion */
510 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
512 _load_inttype(dataargtype, argptr, -radix),
515 } else if (p-u_spec < 12) { /* character or string */
516 flag[FLAG_PLUS] = '\0';
517 flag[FLAG_0_PAD] = ' ';
518 if (*p == 'c') { /* character */
520 *p = va_arg(ap, int);
521 /* This takes care of the "%c",0 case */
524 } else { /* string */
525 p = va_arg(ap, char *);
534 len = strnlen(p, preci);
537 #if defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR
538 } else if (p-u_spec < 27) { /* floating point */
539 #endif /* defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR */
540 #if defined(__UCLIBC_HAS_FLOATS__)
541 struct printf_info info;
548 info.pad = flag[FLAG_0_PAD];
550 if (flag[FLAG_PLUS] == '+') {
551 PRINT_INFO_SET_FLAG(&info,showsign);
552 } else if (flag[FLAG_PLUS] == ' ') {
553 PRINT_INFO_SET_FLAG(&info,space);
555 if (flag[FLAG_HASH]) {
556 PRINT_INFO_SET_FLAG(&info,alt);
558 if (flag[FLAG_MINUS_LJUSTIFY]) {
559 PRINT_INFO_SET_FLAG(&info,left);
562 cnt += _fpmaxtostr(op,
564 ((dataargtype == (8 << 8))
565 ? va_arg(ap, long double)
566 : (long double) va_arg(ap, double)),
567 &info, _fp_out_narrow);
569 cnt += _fpmaxtostr(op,
572 ? va_arg(ap, long double)
573 : (long double) va_arg(ap, double)),
574 &info, _fp_out_narrow);
577 #elif WANT_FLOAT_ERROR
578 (void) ((lval > 1) ? va_arg(ap, long double)
579 : va_arg(ap, double)); /* carry on */
580 p = (char *) dbl_err;
581 #endif /* defined(__UCLIBC_HAS_FLOATS__) */
587 { /* this used to be printfield */
588 /* cheaper than strlen call */
589 /* for ( len = 0 ; p[len] ; len++ ) { } */
590 len = strnlen(p, SIZE_MAX);
597 flag[FLAG_PLUS] = *p++;
600 if (flag[FLAG_PLUS]) {
603 if (flag[FLAG_PLUS] == '0') { /* base 16 */
604 ++preci; /* account for x or X */
634 if (!flag[FLAG_MINUS_LJUSTIFY]
635 /* && flag[FLAG_PLUS] */
636 && (flag[FLAG_0_PAD] == '0')) {
642 while (width + len + preci) {
644 /* right padding || left padding */
646 || (width && !flag[FLAG_MINUS_LJUSTIFY])) {
649 } else if (flag[FLAG_PLUS]) {
650 ch = flag[FLAG_PLUS]; /* sign */
651 if (flag[FLAG_PLUS]=='0') { /* base 16 case */
652 flag[FLAG_PLUS] = *p++; /* get the x|X */
654 flag[FLAG_PLUS] = '\0';
661 ch = *p++; /* main field */
671 fmt = fmt0; /* this was an illegal format */
676 PUTC(*fmt, op); /* normal char out */
684 i = (__FERROR_UNLOCKED(op)) ? -1 : cnt;
686 __STDIO_STREAM_VALIDATE(op);
688 __STDIO_AUTO_THREADUNLOCK(op);
692 libc_hidden_def(vfprintf)