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 /**************************************************************************/
130 #define _ISOC99_SOURCE /* for ULLONG primarily... */
132 /* #include <stdio.h> */
139 #include <bits/uClibc_uintmaxtostr.h>
142 #ifdef __UCLIBC_HAS_THREADS__
144 #endif /* __UCLIBC_HAS_THREADS__ */
146 /* Experimentally off - libc_hidden_proto(strlen) */
147 /* Experimentally off - libc_hidden_proto(strnlen) */
148 /* Experimentally off - libc_hidden_proto(memcpy) */
149 libc_hidden_proto(putc_unlocked)
150 libc_hidden_proto(__fputc_unlocked)
151 libc_hidden_proto(__glibc_strerror_r)
153 /* #undef __UCLIBC_HAS_FLOATS__ */
154 /* #undef WANT_FLOAT_ERROR */
155 /* #define WANT_FLOAT_ERROR 1 */
157 /* #define __isdigit(c) (((unsigned int)(c - '0')) < 10) */
159 #ifdef __UCLIBC_HAS_PRINTF_M_SPEC__
160 #define WANT_GNU_ERRNO 1
162 #define WANT_GNU_ERRNO 0
169 #ifdef __STDIO_BUFFERS
171 #define PUTC(C,F) putc_unlocked((C),(F))
172 #define OUTNSTR _outnstr
173 #define _outnstr(stream, string, len) __stdio_fwrite(string, len, stream)
175 #else /* __STDIO_BUFFERS */
179 unsigned char *bufend; /* pointer to 1 past end of buffer */
180 unsigned char *bufpos;
183 #ifdef __UCLIBC_HAS_FLOATS__
184 static void _outnstr(FILE *stream, const unsigned char *s, size_t n)
186 __FILE_vsnprintf *f = (__FILE_vsnprintf *) stream;
188 if (!__STDIO_STREAM_IS_FAKE_VSNPRINTF_NB(&f->f)) {
189 __stdio_fwrite(s, n, &f->f);
190 } else if (f->bufend > f->bufpos) {
191 size_t r = f->bufend - f->bufpos;
195 memcpy(f->bufpos, s, r);
201 static void putc_unlocked_sprintf(int c, __FILE_vsnprintf *f)
203 if (!__STDIO_STREAM_IS_FAKE_VSNPRINTF_NB(&f->f)) {
204 putc_unlocked(c, &f->f);
205 } else if (f->bufpos < f->bufend) {
211 #define PUTC(C,F) putc_unlocked_sprintf((C),(__FILE_vsnprintf *)(F))
212 #define OUTNSTR _outnstr
214 #endif /* __STDIO_BUFFERS */
216 #ifdef __UCLIBC_HAS_FLOATS__
218 #include <bits/uClibc_fpmax.h>
220 typedef void (__fp_outfunc_t)(FILE *fp, intptr_t type, intptr_t len,
223 extern size_t _fpmaxtostr(FILE * fp, __fpmax_t x, struct printf_info *info,
224 __fp_outfunc_t fp_outfunc) attribute_hidden;
226 static void _charpad(FILE * __restrict stream, int padchar, size_t numpad)
228 /* TODO -- Use a buffer to cut down on function calls... */
233 OUTNSTR(stream, pad, 1);
238 static void _fp_out_narrow(FILE *fp, intptr_t type, intptr_t len, intptr_t buf)
240 if (type & 0x80) { /* Some type of padding needed. */
241 int buflen = strlen((const char *) buf);
242 if ((len -= buflen) > 0) {
243 _charpad(fp, (type & 0x7f), len);
248 OUTNSTR(fp, (const char *) buf, len);
264 static const char spec[] = "+-#0 ";
266 /**********************************************************************/
268 extern void _store_inttype(void *dest, int desttype, uintmax_t val) attribute_hidden;
269 extern uintmax_t _load_inttype(int desttype, const void *src, int uflag) attribute_hidden;
272 * In order to ease translation to what arginfo and _print_info._flags expect,
273 * we map: 0:int 1:char 2:longlong 4:long 8:short
274 * and then _flags |= (((q << 7) + q) & 0x701) and argtype |= (_flags & 0x701)
278 #error PDS already defined!
281 #error SS already defined!
284 #error IMS already defined!
287 #if PTRDIFF_MAX == INT_MAX
289 #elif PTRDIFF_MAX == LONG_MAX
291 #elif defined(LLONG_MAX) && (PTRDIFF_MAX == LLONG_MAX)
294 #error fix QUAL_CHARS ptrdiff_t entry 't'!
297 #if SIZE_MAX == UINT_MAX
299 #elif SIZE_MAX == ULONG_MAX
301 #elif defined(LLONG_MAX) && (SIZE_MAX == ULLONG_MAX)
304 #error fix QUAL_CHARS size_t entries 'z', 'Z'!
307 #if INTMAX_MAX == INT_MAX
309 #elif INTMAX_MAX == LONG_MAX
311 #elif defined(LLONG_MAX) && (INTMAX_MAX == LLONG_MAX)
314 #error fix QUAL_CHARS intmax_t entry 'j'!
317 #define QUAL_CHARS { \
318 /* j:(u)intmax_t z:(s)size_t t:ptrdiff_t \0:int */ \
319 /* q:long_long Z:(s)size_t */ \
320 'h', 'l', 'L', 'j', 'z', 't', 'q', 'Z', 0, \
321 2, 4, 8, IMS, SS, PDS, 8, SS, 0, /* TODO -- fix!!! */\
325 static const char qual_chars[] = QUAL_CHARS;
327 /* static const char qual[] = "hlLq"; */
328 /**********************************************************************/
330 #if !defined(__UCLIBC_HAS_FLOATS__) && WANT_FLOAT_ERROR
331 static const char dbl_err[] = "<DOUBLE>";
334 #if defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR
335 /* layout 012345678901234567 */
336 static const char u_spec[] = "%nbopxXudicsfgGeEaA";
338 /* layout 0123456789012 */
339 static const char u_spec[] = "%nbopxXudics";
342 /* WARNING: u_spec and u_radix need to stay in agreement!!! */
343 /* u_radix[i] <-> u_spec[i+2] for unsigned entries only */
344 static const char u_radix[] = "\x02\x08\x10\x10\x10\x0a";
346 libc_hidden_proto(vfprintf)
347 int vfprintf(FILE * __restrict op, register const char * __restrict fmt,
354 #if LONG_MAX != INT_MAX
359 int i, cnt, dataargtype, len;
360 const void *argptr = argptr; /* ok to be initialized. */
365 int radix, dpoint /*, upcase*/;
366 char tmp[65]; /* TODO - determine needed size from headers */
367 char flag[sizeof(spec)];
368 __STDIO_AUTO_THREADLOCK_VAR;
370 __STDIO_AUTO_THREADLOCK(op);
372 __STDIO_STREAM_VALIDATE(op);
376 if (__STDIO_STREAM_IS_NARROW_WRITING(op)
377 || !__STDIO_STREAM_TRANS_TO_WRITE(op, __FLAG_NARROW)
382 fmt0 = fmt; /* save our position in case of bad format */
384 width = -1; /* min field width */
385 preci = -5; /* max string width or mininum digits */
386 radix = 10; /* number base */
387 dpoint = 0; /* found decimal point */
390 for (p =(char *) spec ; *p ; p++) {
393 flag[FLAG_0_PAD] = ' ';
395 /* process optional flags */
396 for (p = (char *)spec ; *p ; ) {
398 flag[p-spec] = *fmt++;
399 p = (char *)spec; /* restart scan */
405 if (!flag[FLAG_PLUS]) {
406 flag[FLAG_PLUS] = flag[FLAG_SPACE];
409 /* process optional width and precision */
415 if (*fmt == '*') { /* parameter width value */
419 for ( i = 0 ; (*fmt >= '0') && (*fmt <= '9') ; ++fmt ) {
420 i = (i * 10) + (*fmt - '0');
433 flag[FLAG_MINUS_LJUSTIFY] = 1;
436 } while ((*fmt == '.') && !dpoint );
438 /* process optional qualifier */
439 p = (char *) qual_chars;
446 if ((p - qual_chars < 2) && (*fmt == *p)) {
447 p += ((sizeof(qual_chars)-2) / 2);
450 dataargtype = ((int)(p[(sizeof(qual_chars)-2) / 2])) << 8;
454 flag[FLAG_PLUS] = '\0';
455 flag[FLAG_0_PAD] = ' ';
456 p = __glibc_strerror_r(errno, tmp, sizeof(tmp));
461 /* process format specifier */
462 for (p = (char *) u_spec ; *p ; p++) {
463 if (*fmt != *p) continue;
464 if (p-u_spec < 1) { /* print a % */
467 if (p-u_spec < 2) { /* store output count in int ptr */
468 _store_inttype(va_arg(ap, void *),
476 #if INTPTR_MAX == INT_MAX
479 #error Fix dataargtype for pointers!
483 switch(dataargtype) {
484 case (PA_INT|PA_FLAG_LONG_LONG):
486 intarg.ll = va_arg(ap, long long);
490 case (PA_INT|PA_FLAG_LONG):
491 #if LONG_MAX != INT_MAX
492 intarg.l = va_arg(ap, long);
497 intarg.i = va_arg(ap, int);
503 if (p-u_spec < 8) { /* unsigned conversion */
504 radix = u_radix[p-u_spec-2];
505 upcase = ((*p == 'x') ? __UIM_LOWER : __UIM_UPPER);
507 upcase = __UIM_LOWER;
508 flag[FLAG_HASH] = 'p';
510 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
512 _load_inttype(dataargtype, argptr, radix),
515 flag[FLAG_PLUS] = '\0'; /* meaningless for unsigned */
516 if (*p != '0') { /* non-zero */
517 if (flag[FLAG_HASH]) {
519 *--p = '0'; /* add leadding zero */
520 } else if (radix != 10) { /* either 2 or 16 */
521 flag[FLAG_PLUS] = '0';
531 } else if (flag[FLAG_HASH] == 'p') { /* null pointer */
534 } else if (p-u_spec < 10) { /* signed conversion */
535 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
537 _load_inttype(dataargtype, argptr, -radix),
540 } else if (p-u_spec < 12) { /* character or string */
541 flag[FLAG_PLUS] = '\0';
542 flag[FLAG_0_PAD] = ' ';
543 if (*p == 'c') { /* character */
545 *p = va_arg(ap, int);
546 /* This takes care of the "%c",0 case */
549 } else { /* string */
550 p = va_arg(ap, char *);
559 len = strnlen(p, preci);
562 #if defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR
563 } else if (p-u_spec < 27) { /* floating point */
564 #endif /* defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR */
565 #if defined(__UCLIBC_HAS_FLOATS__)
566 struct printf_info info;
573 info.pad = flag[FLAG_0_PAD];
575 if (flag[FLAG_PLUS] == '+') {
576 PRINT_INFO_SET_FLAG(&info,showsign);
577 } else if (flag[FLAG_PLUS] == ' ') {
578 PRINT_INFO_SET_FLAG(&info,space);
580 if (flag[FLAG_HASH]) {
581 PRINT_INFO_SET_FLAG(&info,alt);
583 if (flag[FLAG_MINUS_LJUSTIFY]) {
584 PRINT_INFO_SET_FLAG(&info,left);
587 cnt += _fpmaxtostr(op,
589 ((dataargtype == (8 << 8))
590 ? va_arg(ap, long double)
591 : (long double) va_arg(ap, double)),
592 &info, _fp_out_narrow);
594 cnt += _fpmaxtostr(op,
597 ? va_arg(ap, long double)
598 : (long double) va_arg(ap, double)),
599 &info, _fp_out_narrow);
602 #elif WANT_FLOAT_ERROR
603 (void) ((lval > 1) ? va_arg(ap, long double)
604 : va_arg(ap, double)); /* carry on */
605 p = (char *) dbl_err;
606 #endif /* defined(__UCLIBC_HAS_FLOATS__) */
612 { /* this used to be printfield */
613 /* cheaper than strlen call */
614 /* for ( len = 0 ; p[len] ; len++ ) { } */
615 len = strnlen(p, SIZE_MAX);
622 flag[FLAG_PLUS] = *p++;
625 if (flag[FLAG_PLUS]) {
628 if (flag[FLAG_PLUS] == '0') { /* base 16 */
629 ++preci; /* account for x or X */
659 if (!flag[FLAG_MINUS_LJUSTIFY]
660 /* && flag[FLAG_PLUS] */
661 && (flag[FLAG_0_PAD] == '0')) {
667 while (width + len + preci) {
669 /* right padding || left padding */
671 || (width && !flag[FLAG_MINUS_LJUSTIFY])) {
674 } else if (flag[FLAG_PLUS]) {
675 ch = flag[FLAG_PLUS]; /* sign */
676 if (flag[FLAG_PLUS]=='0') { /* base 16 case */
677 flag[FLAG_PLUS] = *p++; /* get the x|X */
679 flag[FLAG_PLUS] = '\0';
686 ch = *p++; /* main field */
696 fmt = fmt0; /* this was an illegal format */
701 PUTC(*fmt, op); /* normal char out */
709 i = (__FERROR_UNLOCKED(op)) ? -1 : cnt;
711 __STDIO_STREAM_VALIDATE(op);
713 __STDIO_AUTO_THREADUNLOCK(op);
717 libc_hidden_def(vfprintf)