1 /*
2 * This file based on printf.c from 'Dlibs' on the atari ST (RdeBath)
3 *
4 *
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."
9 */
10
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
14 * will be either
15 * sizeof(xxx) == sizeof(long) or sizeof(xxx) == sizeof(short)
16 *
17 * -RDB
18 */
19
20 /*
21 * Manuel Novoa III Dec 2000
22 *
23 * The previous vfnprintf routine was almost completely rewritten with the
24 * goal of fixing some shortcomings and reducing object size.
25 *
26 * The summary of changes:
27 *
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
35 * improvements.
36 *
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.
41 *
42 * Added optional support for the GNU extension %m which prints the string
43 * corresponding the errno.
44 *
45 * Added optional support for long long ints and unsigned long long ints
46 * using the conversion qualifiers "ll", "L", or "q" (like glibc).
47 *
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.
51 *
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.
54 *
55 * Other Modifications:
56 * Modified sprintf, snprintf, vsprintf, vsnprintf to share on fake-file.
57 */
58
59 /*
60 * Manuel Novoa III Jan 2001
61 *
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!
75 *
76 *
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.
80 *
81 *
82 * June 2001
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
85 *
86 * Sep 5, 2003
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.
90 *
91 */
92
93 /*****************************************************************************/
94 /* OPTIONS */
95 /*****************************************************************************/
96 /* The optional support for long longs and doubles comes in two forms.
97 *
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.
101 */
102
103 /* These are now set in uClibc_config.h based on Config. */
104 /*
105 #define __UCLIBC_HAS_FLOATS__ 1
106 */
107
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.
114 */
115
116 #define WANT_FLOAT_ERROR 0
117
118 /*
119 * Set to support GNU extension of %m to print string corresponding to errno.
120 *
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.
123 */
124
125 /* Now controlled by uClibc_stdio.h and set below. */
126 /* #define WANT_GNU_ERRNO 0 */
127
128 /**************************************************************************/
129
130 #include "_stdio.h"
131 #include <stdarg.h>
132 #include <limits.h>
133 #include <stdint.h>
134 #include <string.h>
135 #include <errno.h>
136 #include <ctype.h>
137 #include <bits/uClibc_uintmaxtostr.h>
138
139 #include "_fpmaxtostr.h"
140
141 /* #undef WANT_FLOAT_ERROR */
142 /* #define WANT_FLOAT_ERROR 1 */
143
144 /* #define __isdigit(c) (((unsigned int)(c - '0')) < 10) */
145
146 #ifdef __UCLIBC_HAS_PRINTF_M_SPEC__
147 #define WANT_GNU_ERRNO 1
148 #else
149 #define WANT_GNU_ERRNO 0
150 #endif
151
152 #undef PUTC
153 #undef OUTNSTR
154 #undef _outnstr
155
156 #ifdef __STDIO_BUFFERS
157
158 #define PUTC(C,F) putc_unlocked((C),(F))
159 #define OUTNSTR _outnstr
160 #define _outnstr(stream, string, len) __stdio_fwrite(string, len, stream)
161
162 #else /* __STDIO_BUFFERS */
163
164 typedef struct {
165 FILE f;
166 unsigned char *bufend; /* pointer to 1 past end of buffer */
167 unsigned char *bufpos;
168 } __FILE_vsnprintf;
169
170 #ifdef __UCLIBC_HAS_FLOATS__
_outnstr(FILE * stream,const unsigned char * s,size_t n)171 static void _outnstr(FILE *stream, const unsigned char *s, size_t n)
172 {
173 __FILE_vsnprintf *f = (__FILE_vsnprintf *) stream;
174
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;
179 if (r > n) {
180 r = n;
181 }
182 memcpy(f->bufpos, s, r);
183 f->bufpos += r;
184 }
185 }
186 #endif
187
putc_unlocked_sprintf(int c,__FILE_vsnprintf * f)188 static void putc_unlocked_sprintf(int c, __FILE_vsnprintf *f)
189 {
190 if (!__STDIO_STREAM_IS_FAKE_VSNPRINTF_NB(&f->f)) {
191 putc_unlocked(c, &f->f);
192 } else if (f->bufpos < f->bufend) {
193 *f->bufpos++ = c;
194 }
195 }
196
197
198 #define PUTC(C,F) putc_unlocked_sprintf((C),(__FILE_vsnprintf *)(F))
199 #define OUTNSTR _outnstr
200
201 #endif /* __STDIO_BUFFERS */
202
203 #ifdef __UCLIBC_HAS_FLOATS__
204
_charpad(FILE * __restrict stream,int padchar,size_t numpad)205 static void _charpad(FILE * __restrict stream, int padchar, size_t numpad)
206 {
207 /* TODO -- Use a buffer to cut down on function calls... */
208 char pad[1];
209
210 *pad = padchar;
211 while (numpad) {
212 OUTNSTR(stream, pad, 1);
213 --numpad;
214 }
215 }
216
_fp_out_narrow(FILE * fp,intptr_t type,intptr_t len,intptr_t buf)217 static void _fp_out_narrow(FILE *fp, intptr_t type, intptr_t len, intptr_t buf)
218 {
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);
223 }
224 len = buflen;
225 }
226 if (len) {
227 OUTNSTR(fp, (const char *) buf, len);
228 }
229 }
230
231 #endif
232
233
234 enum {
235 FLAG_PLUS = 0,
236 FLAG_MINUS_LJUSTIFY,
237 FLAG_HASH,
238 FLAG_0_PAD,
239 FLAG_SPACE,
240 };
241
242 /* layout 01234 */
243 static const char spec[] = "+-#0 ";
244
245 /**********************************************************************/
246
247 /*
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)
251 */
252
253 #ifdef PDS
254 #error PDS already defined!
255 #endif
256 #ifdef SS
257 #error SS already defined!
258 #endif
259 #ifdef IMS
260 #error IMS already defined!
261 #endif
262
263 #if PTRDIFF_MAX == INT_MAX
264 #define PDS 0
265 #elif PTRDIFF_MAX == LONG_MAX
266 #define PDS 4
267 #elif defined(LLONG_MAX) && (PTRDIFF_MAX == LLONG_MAX)
268 #define PDS 8
269 #else
270 #error fix QUAL_CHARS ptrdiff_t entry 't'!
271 #endif
272
273 #if SIZE_MAX == UINT_MAX
274 #define SS 0
275 #elif SIZE_MAX == ULONG_MAX
276 #define SS 4
277 #elif defined(LLONG_MAX) && (SIZE_MAX == ULLONG_MAX)
278 #define SS 8
279 #else
280 #error fix QUAL_CHARS size_t entries 'z', 'Z'!
281 #endif
282
283 #if INTMAX_MAX == INT_MAX
284 #define IMS 0
285 #elif INTMAX_MAX == LONG_MAX
286 #define IMS 4
287 #elif defined(LLONG_MAX) && (INTMAX_MAX == LLONG_MAX)
288 #define IMS 8
289 #else
290 #error fix QUAL_CHARS intmax_t entry 'j'!
291 #endif
292
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!!! */\
298 1, 8 \
299 }
300
301 static const char qual_chars[] = QUAL_CHARS;
302
303 /* static const char qual[] = "hlLq"; */
304 /**********************************************************************/
305
306 #if !defined(__UCLIBC_HAS_FLOATS__) && WANT_FLOAT_ERROR
307 static const char dbl_err[] = "<DOUBLE>";
308 #endif
309
310 #if defined(__UCLIBC_HAS_FLOATS__) || WANT_FLOAT_ERROR
311 /* layout 012345678901234567 */
312 static const char u_spec[] = "%nbopxXudicsfgGeEaA";
313 #else
314 /* layout 0123456789012 */
315 static const char u_spec[] = "%nbopxXudics";
316 #endif
317
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";
321
vfprintf(FILE * __restrict op,register const char * __restrict fmt,va_list ap)322 int vfprintf(FILE * __restrict op, register const char * __restrict fmt,
323 va_list ap)
324 {
325 union {
326 #ifdef LLONG_MAX
327 long long ll;
328 #endif
329 #if LONG_MAX != INT_MAX
330 long l;
331 #endif
332 int i;
333 } intarg;
334 int i, cnt, dataargtype, len;
335 const void *argptr = argptr; /* ok to be initialized. */
336 register char *p;
337 const char *fmt0;
338 int preci, width;
339 #define upcase i
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;
344
345 __STDIO_AUTO_THREADLOCK(op);
346
347 __STDIO_STREAM_VALIDATE(op);
348
349 cnt = 0;
350
351 if (__STDIO_STREAM_IS_NARROW_WRITING(op)
352 || !__STDIO_STREAM_TRANS_TO_WRITE(op, __FLAG_NARROW)
353 ) {
354
355 while (*fmt) {
356 if (*fmt == '%') {
357 fmt0 = fmt; /* save our position in case of bad format */
358 ++fmt;
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 */
363
364 /* init flags */
365 for (p =(char *) spec ; *p ; p++) {
366 flag[p-spec] = '\0';
367 }
368 flag[FLAG_0_PAD] = ' ';
369
370 /* process optional flags */
371 for (p = (char *)spec ; *p ; ) {
372 if (*fmt == *p) {
373 flag[p-spec] = *fmt++;
374 p = (char *)spec; /* restart scan */
375 } else {
376 p++;
377 }
378 }
379
380 if (!flag[FLAG_PLUS]) {
381 flag[FLAG_PLUS] = flag[FLAG_SPACE];
382 }
383
384 /* process optional width and precision */
385 do {
386 if (*fmt == '.') {
387 ++fmt;
388 dpoint = 1;
389 }
390 if (*fmt == '*') { /* parameter width value */
391 ++fmt;
392 i = va_arg(ap, int);
393 } else {
394 for ( i = 0 ; (*fmt >= '0') && (*fmt <= '9') ; ++fmt ) {
395 i = (i * 10) + (*fmt - '0');
396 }
397 }
398
399 if (dpoint) {
400 preci = i;
401 if (i<0) {
402 preci = -5;
403 }
404 } else {
405 width = i;
406 if (i<0) {
407 width = -i;
408 flag[FLAG_MINUS_LJUSTIFY] = 1;
409 }
410 }
411 } while ((*fmt == '.') && !dpoint );
412
413 /* process optional qualifier */
414 p = (char *) qual_chars;
415 do {
416 if (*fmt == *p) {
417 ++fmt;
418 break;
419 }
420 } while (*++p);
421 if ((p - qual_chars < 2) && (*fmt == *p)) {
422 p += ((sizeof(qual_chars)-2) / 2);
423 ++fmt;
424 }
425 dataargtype = ((int)(p[(sizeof(qual_chars)-2) / 2])) << 8;
426
427 #if WANT_GNU_ERRNO
428 if (*fmt == 'm') {
429 flag[FLAG_PLUS] = '\0';
430 flag[FLAG_0_PAD] = ' ';
431 p = __glibc_strerror_r(errno, tmp, sizeof(tmp));
432 goto print;
433 }
434 #endif
435
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 % */
440 goto charout;
441 }
442 if (p-u_spec < 2) { /* store output count in int ptr */
443 _store_inttype(va_arg(ap, void *),
444 dataargtype,
445 (intmax_t) (cnt));
446 goto nextfmt;
447 }
448
449 if (p-u_spec < 10) {
450 if (*p == 'p') {
451 #if INTPTR_MAX == INT_MAX
452 dataargtype = 0;
453 #else
454 #error Fix dataargtype for pointers!
455 #endif
456 }
457
458 switch(dataargtype) {
459 case (PA_INT|PA_FLAG_LONG_LONG):
460 #ifdef LLONG_MAX
461 intarg.ll = va_arg(ap, long long);
462 argptr = &intarg.ll;
463 break;
464 #endif
465 case (PA_INT|PA_FLAG_LONG):
466 #if LONG_MAX != INT_MAX
467 intarg.l = va_arg(ap, long);
468 argptr = &intarg.l;
469 break;
470 #endif
471 default:
472 intarg.i = va_arg(ap, int);
473 argptr = &intarg.i;
474 break;
475 }
476 }
477
478 if (p-u_spec < 8) { /* unsigned conversion */
479 radix = u_radix[p-u_spec-2];
480 upcase = ((*p == 'x') ? __UIM_LOWER : __UIM_UPPER);
481 if (*p == 'p') {
482 upcase = __UIM_LOWER;
483 flag[FLAG_HASH] = 'p';
484 }
485 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
486 (uintmax_t)
487 _load_inttype(dataargtype, argptr, radix),
488 radix, upcase);
489
490 flag[FLAG_PLUS] = '\0'; /* meaningless for unsigned */
491 if (*p != '0') { /* non-zero */
492 if (flag[FLAG_HASH]) {
493 if (radix == 8) {
494 *--p = '0'; /* add leadding zero */
495 } else if (radix != 10) { /* either 2 or 16 */
496 flag[FLAG_PLUS] = '0';
497 *--p = 'b';
498 if (radix == 16) {
499 *p = 'x';
500 if (*fmt == 'X') {
501 *p = 'X';
502 }
503 }
504 }
505 }
506 } else if (flag[FLAG_HASH] == 'p') { /* null pointer */
507 p = "(nil)";
508 }
509 } else if (p-u_spec < 10) { /* signed conversion */
510 p = _uintmaxtostr(tmp + sizeof(tmp) - 1,
511 (uintmax_t)
512 _load_inttype(dataargtype, argptr, -radix),
513 -radix, upcase);
514
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 */
519 p = tmp;
520 *p = va_arg(ap, int);
521 /* This takes care of the "%c",0 case */
522 len = 1;
523 goto print_len_set;
524 } else { /* string */
525 p = va_arg(ap, char *);
526 if (!p) {
527 p = "(null)";
528 preci = 6;
529 } else {
530 if (preci < 0) {
531 preci = INT_MAX;
532 }
533 }
534 len = strnlen(p, preci);
535 goto print_len_set;
536 }
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;
542 if (preci < 0) {
543 preci = 6;
544 }
545 info.width = width;
546 info.prec = preci;
547 info.spec = *fmt;
548 info.pad = flag[FLAG_0_PAD];
549 info._flags = 0;
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);
554 }
555 if (flag[FLAG_HASH]) {
556 PRINT_INFO_SET_FLAG(&info,alt);
557 }
558 if (flag[FLAG_MINUS_LJUSTIFY]) {
559 PRINT_INFO_SET_FLAG(&info,left);
560 }
561 #if 1
562 cnt += _fpmaxtostr(op,
563 (__fpmax_t)
564 ((dataargtype == (8 << 8))
565 ? va_arg(ap, long double)
566 : (long double) va_arg(ap, double)),
567 &info, _fp_out_narrow);
568 #else
569 cnt += _fpmaxtostr(op,
570 (__fpmax_t)
571 ((lval > 1)
572 ? va_arg(ap, long double)
573 : (long double) va_arg(ap, double)),
574 &info, _fp_out_narrow);
575 #endif
576 goto nextfmt;
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__) */
582 }
583
584 #if WANT_GNU_ERRNO
585 print:
586 #endif
587 { /* this used to be printfield */
588 /* cheaper than strlen call */
589 /* for ( len = 0 ; p[len] ; len++ ) { } */
590 len = strnlen(p, SIZE_MAX);
591 print_len_set:
592 if ((*p == '-')
593 #if WANT_GNU_ERRNO
594 && (*fmt != 'm')
595 #endif
596 && (*fmt != 's')) {
597 flag[FLAG_PLUS] = *p++;
598 --len;
599 }
600 if (flag[FLAG_PLUS]) {
601 ++len;
602 ++preci;
603 if (flag[FLAG_PLUS] == '0') { /* base 16 */
604 ++preci; /* account for x or X */
605 }
606 }
607
608 if (preci >= 0) {
609 if ((*fmt == 's')
610 #if WANT_GNU_ERRNO
611 || (*fmt == 'm')
612 #endif
613 ) {
614 if (len > preci) {
615 len = preci;
616 } else {
617 preci = len;
618 }
619 }
620 preci -= len;
621 if (preci < 0) {
622 preci = 0;
623 }
624 width -= preci;
625 }
626
627 width -= len;
628 if (width < 0) {
629 width = 0;
630 }
631
632 if (preci < 0) {
633 preci = 0;
634 if (!flag[FLAG_MINUS_LJUSTIFY]
635 /* && flag[FLAG_PLUS] */
636 && (flag[FLAG_0_PAD] == '0')) {
637 preci = width;
638 width = 0;
639 }
640 }
641
642 while (width + len + preci) {
643 unsigned char ch;
644 /* right padding || left padding */
645 if ((!len && !preci)
646 || (width && !flag[FLAG_MINUS_LJUSTIFY])) {
647 ch = ' ';
648 --width;
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 */
653 } else {
654 flag[FLAG_PLUS] = '\0';
655 }
656 --len;
657 } else if (preci) {
658 ch = '0';
659 --preci;
660 } else {
661 ch = *p++; /* main field */
662 --len;
663 }
664 ++cnt;
665 PUTC(ch, op);
666 }
667 }
668 goto nextfmt;
669 }
670
671 fmt = fmt0; /* this was an illegal format */
672 }
673
674 charout:
675 ++cnt;
676 PUTC(*fmt, op); /* normal char out */
677
678 nextfmt:
679 ++fmt;
680 }
681
682 }
683
684 i = (__FERROR_UNLOCKED(op)) ? -1 : cnt;
685
686 __STDIO_STREAM_VALIDATE(op);
687
688 __STDIO_AUTO_THREADUNLOCK(op);
689
690 return i;
691 }
692 libc_hidden_def(vfprintf)
693