2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Copyright (c) 2011 The FreeBSD Foundation
7 * Portions of this software were developed by David Chisnall
8 * under sponsorship from the FreeBSD Foundation.
10 * This code is derived from software contributed to Berkeley by
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
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.
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
37 * @(#)vfscanf.c 8.1 (Berkeley) 6/4/93
38 * $FreeBSD: head/lib/libc/stdio/vfscanf.c 249808 2013-04-23 13:33:13Z emaste $
42 #include "namespace.h"
52 #include "un-namespace.h"
55 #include "libc_private.h"
57 #include "xlocale_private.h"
59 #ifndef NO_FLOATING_POINT
63 #define BUF 513 /* Maximum length of numeric string. */
66 * Flags used during conversion.
68 #define LONG 0x01 /* l: long or double */
69 #define LONGDBL 0x02 /* L: long double */
70 #define SHORT 0x04 /* h: short */
71 #define SUPPRESS 0x08 /* *: suppress assignment */
72 #define POINTER 0x10 /* p: void * (as hex) */
73 #define NOSKIP 0x20 /* [ or c: do not skip blanks */
74 #define LONGLONG 0x400 /* ll: long long (+ deprecated q: quad) */
75 #define INTMAXT 0x800 /* j: intmax_t */
76 #define PTRDIFFT 0x1000 /* t: ptrdiff_t */
77 #define SIZET 0x2000 /* z: size_t */
78 #define SHORTSHORT 0x4000 /* hh: char */
79 #define UNSIGNED 0x8000 /* %[oupxX] conversions */
82 * The following are used in integral conversions only:
83 * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
85 #define SIGNOK 0x40 /* +/- is (still) legal */
86 #define NDIGITS 0x80 /* no digits detected */
87 #define PFXOK 0x100 /* 0x prefix is (still) legal */
88 #define NZDIGITS 0x200 /* no zero digits detected */
89 #define HAVESIGN 0x10000 /* sign detected */
94 #define CT_CHAR 0 /* %c conversion */
95 #define CT_CCL 1 /* %[...] conversion */
96 #define CT_STRING 2 /* %s conversion */
97 #define CT_INT 3 /* %[dioupxX] conversion */
98 #define CT_FLOAT 4 /* %[efgEFG] conversion */
100 static const u_char *__sccl(char *, const u_char *);
101 #ifndef NO_FLOATING_POINT
102 static int parsefloat(FILE *, char *, char *, locale_t);
106 * Conversion functions are passed a pointer to this object instead of
107 * a real parameter to indicate that the assignment-suppression (*)
108 * flag was specified. We could use a NULL pointer to indicate this,
109 * but that would mask bugs in applications that call scanf() with a
112 static const int suppress;
113 #define SUPPRESS_PTR ((void *)&suppress)
115 static const mbstate_t initial_mbs;
118 * The following conversion functions return the number of characters consumed,
119 * or -1 on input failure. Character class conversion returns 0 on match
124 convert_char(FILE *fp, char * p, int width)
128 if (p == SUPPRESS_PTR) {
131 if ((n = fp->pub._r) < width) {
149 size_t r = __fread(p, 1, width, fp);
158 convert_wchar(FILE *fp, wchar_t *wcp, int width, locale_t locale)
166 while (width-- != 0 &&
167 (wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF) {
168 if (wcp != SUPPRESS_PTR)
169 *wcp++ = (wchar_t)wi;
178 convert_ccl(FILE *fp, char * p, int width, const char *ccltab)
183 if (p == SUPPRESS_PTR) {
185 while (ccltab[*fp->pub._p]) {
186 n++, fp->pub._r--, fp->pub._p++;
189 if (fp->pub._r <= 0 && __srefill(fp)) {
197 while (ccltab[*fp->pub._p]) {
199 *p++ = *fp->pub._p++;
202 if (fp->pub._r <= 0 && __srefill(fp)) {
217 convert_wccl(FILE *fp, wchar_t *wcp, int width, const char *ccltab,
226 if (wcp == SUPPRESS_PTR) {
227 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
228 width-- != 0 && ccltab[wctob(wi)])
231 __ungetwc(wi, fp, __get_locale());
233 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
234 width-- != 0 && ccltab[wctob(wi)]) {
235 *wcp++ = (wchar_t)wi;
239 __ungetwc(wi, fp, __get_locale());
248 convert_string(FILE *fp, char * p, int width)
253 if (p == SUPPRESS_PTR) {
255 while (!isspace(*fp->pub._p)) {
256 n++, fp->pub._r--, fp->pub._p++;
259 if (fp->pub._r <= 0 && __srefill(fp))
264 while (!isspace(*fp->pub._p)) {
266 *p++ = *fp->pub._p++;
269 if (fp->pub._r <= 0 && __srefill(fp))
279 convert_wstring(FILE *fp, wchar_t *wcp, int width, locale_t locale)
287 if (wcp == SUPPRESS_PTR) {
288 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
289 width-- != 0 && !iswspace(wi))
292 __ungetwc(wi, fp, __get_locale());
294 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
295 width-- != 0 && !iswspace(wi)) {
296 *wcp++ = (wchar_t)wi;
300 __ungetwc(wi, fp, __get_locale());
307 * Read an integer, storing it in buf. The only relevant bit in the
308 * flags argument is PFXOK.
310 * Return 0 on a match failure, and the number of characters read
314 parseint(FILE *fp, char * __restrict buf, int width, int base, int flags)
316 /* `basefix' is used to avoid `if' tests */
317 static const short basefix[17] =
318 { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
322 flags |= SIGNOK | NDIGITS | NZDIGITS;
323 for (p = buf; width; width--) {
326 * Switch on the character; `goto ok' if we accept it
327 * as a part of number.
332 * The digit 0 is always legal, but is special. For
333 * %i conversions, if no digits (zero or nonzero) have
334 * been scanned (only signs), we will have base==0.
335 * In that case, we should set it to 8 and enable 0x
336 * prefixing. Also, if we have not scanned zero
337 * digits before this, do not turn off prefixing
338 * (someone else will turn it off if we have scanned
339 * any nonzero digits).
346 if (flags & NZDIGITS)
347 flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
349 flags &= ~(SIGNOK|PFXOK|NDIGITS);
352 /* 1 through 7 always legal */
353 case '1': case '2': case '3':
354 case '4': case '5': case '6': case '7':
355 base = basefix[base];
356 flags &= ~(SIGNOK | PFXOK | NDIGITS);
359 /* digits 8 and 9 ok iff decimal or hex */
361 base = basefix[base];
363 break; /* not legal here */
364 flags &= ~(SIGNOK | PFXOK | NDIGITS);
367 /* letters ok iff hex */
368 case 'A': case 'B': case 'C':
369 case 'D': case 'E': case 'F':
370 case 'a': case 'b': case 'c':
371 case 'd': case 'e': case 'f':
372 /* no need to fix base here */
374 break; /* not legal here */
375 flags &= ~(SIGNOK | PFXOK | NDIGITS);
378 /* sign ok only as first character */
380 if (flags & SIGNOK) {
388 * x ok iff flag still set & 2nd char (or 3rd char if
392 if (flags & PFXOK && p ==
393 buf + 1 + !!(flags & HAVESIGN)) {
394 base = 16; /* if %i */
402 * If we got here, c is not a legal character for a
403 * number. Stop accumulating digits.
408 * c is legal: store it and look at the next.
411 if (--fp->pub._r > 0)
413 else if (__srefill(fp))
417 * If we had only a sign, it is no good; push back the sign.
418 * If the number ends in `x', it was [sign] '0' 'x', so push
419 * back the x and treat it as [sign] '0'.
421 if (flags & NDIGITS) {
423 (void) __ungetc(*(u_char *)--p, fp);
426 c = ((u_char *)p)[-1];
427 if (c == 'x' || c == 'X') {
429 (void) __ungetc(c, fp);
435 * __vfscanf - MT-safe version
438 __vfscanf(FILE *fp, char const *fmt0, va_list ap)
443 ret = __svfscanf(fp, __get_locale(), fmt0, ap);
448 __weak_reference(__vfscanf, vfscanf);
451 vfscanf_l(FILE *fp, locale_t locale, char const *fmt0, va_list ap)
457 ret = __svfscanf(fp, locale, fmt0, ap);
463 * __svfscanf - non-MT-safe version of __vfscanf
466 __svfscanf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
468 #define GETARG(type) ((flags & SUPPRESS) ? SUPPRESS_PTR : va_arg(ap, type))
469 const u_char *fmt = (const u_char *)fmt0;
470 int c; /* character from format, or conversion */
471 size_t width; /* field width, or 0 */
472 int flags; /* flags as defined above */
473 int nassigned; /* number of fields assigned */
474 int nconversions; /* number of conversions */
475 int nr; /* characters read by the current conversion */
476 int nread; /* number of characters consumed from fp */
477 int base; /* base argument to conversion function */
478 char ccltab[256]; /* character class table for %[...] */
479 char buf[BUF]; /* buffer for numeric conversions */
491 while ((fp->pub._r > 0 || __srefill(fp) == 0) && isspace(*fp->pub._p))
492 nread++, fp->pub._r--, fp->pub._p++;
500 * switch on the format. continue if done;
501 * break once format type is derived.
507 if (fp->pub._r <= 0 && __srefill(fp))
509 if (*fp->pub._p != c)
511 fp->pub._r--, fp->pub._p++;
529 flags |= LONGLONG; /* not quite */
548 case '0': case '1': case '2': case '3': case '4':
549 case '5': case '6': case '7': case '8': case '9':
550 width = width * 10 + c - '0';
580 flags |= PFXOK; /* enable 0x prefixing */
586 #ifndef NO_FLOATING_POINT
587 case 'A': case 'E': case 'F': case 'G':
588 case 'a': case 'e': case 'f': case 'g':
601 fmt = __sccl(ccltab, fmt);
614 case 'p': /* pointer format is like hex */
615 flags |= POINTER | PFXOK;
616 c = CT_INT; /* assumes sizeof(uintmax_t) */
617 flags |= UNSIGNED; /* >= sizeof(uintptr_t) */
622 if (flags & SUPPRESS) /* ??? */
624 if (flags & SHORTSHORT)
625 *va_arg(ap, char *) = nread;
626 else if (flags & SHORT)
627 *va_arg(ap, short *) = nread;
628 else if (flags & LONG)
629 *va_arg(ap, long *) = nread;
630 else if (flags & LONGLONG)
631 *va_arg(ap, long long *) = nread;
632 else if (flags & INTMAXT)
633 *va_arg(ap, intmax_t *) = nread;
634 else if (flags & SIZET)
635 *va_arg(ap, size_t *) = nread;
636 else if (flags & PTRDIFFT)
637 *va_arg(ap, ptrdiff_t *) = nread;
639 *va_arg(ap, int *) = nread;
646 * Disgusting backwards compatibility hack. XXX
648 case '\0': /* compat */
653 * We have a conversion that requires input.
655 if (fp->pub._r <= 0 && __srefill(fp))
659 * Consume leading white space, except for formats
660 * that suppress this.
662 if ((flags & NOSKIP) == 0) {
663 while (isspace(*fp->pub._p)) {
665 if (--fp->pub._r > 0)
667 else if (__srefill(fp))
671 * Note that there is at least one character in
672 * the buffer, so conversions that do not set NOSKIP
673 * ca no longer result in an input failure.
683 /* scan arbitrary characters (sets NOSKIP) */
687 nr = convert_wchar(fp, GETARG(wchar_t *),
690 nr = convert_char(fp, GETARG(char *), width);
697 /* scan a (nonempty) character class (sets NOSKIP) */
699 width = (size_t)~0; /* `infinity' */
701 nr = convert_wccl(fp, GETARG(wchar_t *), width,
704 nr = convert_ccl(fp, GETARG(char *), width,
716 /* like CCL, but zero-length string OK, & no NOSKIP */
720 nr = convert_wstring(fp, GETARG(wchar_t *),
723 nr = convert_string(fp, GETARG(char *), width);
730 /* scan an integer as if by the conversion function */
732 if (width == 0 || width > sizeof(buf) - 1)
733 width = sizeof(buf) - 1;
735 /* size_t is unsigned, hence this optimisation */
736 if (--width > sizeof(buf) - 2)
737 width = sizeof(buf) - 2;
740 nr = parseint(fp, buf, width, base, flags);
743 if ((flags & SUPPRESS) == 0) {
747 if ((flags & UNSIGNED) == 0)
748 res = strtoimax_l(buf, NULL, base, locale);
750 res = strtoumax_l(buf, NULL, base, locale);
752 *va_arg(ap, void **) =
753 (void *)(uintptr_t)res;
754 else if (flags & SHORTSHORT)
755 *va_arg(ap, char *) = res;
756 else if (flags & SHORT)
757 *va_arg(ap, short *) = res;
758 else if (flags & LONG)
759 *va_arg(ap, long *) = res;
760 else if (flags & LONGLONG)
761 *va_arg(ap, long long *) = res;
762 else if (flags & INTMAXT)
763 *va_arg(ap, intmax_t *) = res;
764 else if (flags & PTRDIFFT)
765 *va_arg(ap, ptrdiff_t *) = res;
766 else if (flags & SIZET)
767 *va_arg(ap, size_t *) = res;
769 *va_arg(ap, int *) = res;
773 #ifndef NO_FLOATING_POINT
775 /* scan a floating point number as if by strtod */
776 if (width == 0 || width > sizeof(buf) - 1)
777 width = sizeof(buf) - 1;
778 nr = parsefloat(fp, buf, buf + width, locale);
781 if ((flags & SUPPRESS) == 0) {
782 if (flags & LONGDBL) {
783 long double res = strtold_l(buf, NULL,
785 *va_arg(ap, long double *) = res;
786 } else if (flags & LONG) {
787 double res = strtod_l(buf, NULL,
789 *va_arg(ap, double *) = res;
791 float res = strtof_l(buf, NULL, locale);
792 *va_arg(ap, float *) = res;
796 #endif /* !NO_FLOATING_POINT */
798 if (!(flags & SUPPRESS))
804 return (nconversions != 0 ? nassigned : EOF);
810 * Fill in the given table from the scanset at the given format
811 * (just after `['). Return a pointer to the character past the
812 * closing `]'. The table has a 1 wherever characters should be
813 * considered part of the scanset.
815 static const u_char *
816 __sccl(char *tab, const u_char *fmt)
819 struct xlocale_collate *table =
820 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
822 /* first `clear' the whole table */
823 c = *fmt++; /* first char hat => negated scanset */
825 v = 1; /* default => accept */
826 c = *fmt++; /* get new first char */
828 v = 0; /* default => reject */
830 /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
831 (void) memset(tab, v, 256);
834 return (fmt - 1);/* format ended before closing ] */
837 * Now set the entries corresponding to the actual scanset
838 * to the opposite of the above.
840 * The first character may be ']' (or '-') without being special;
841 * the last character may be '-'.
845 tab[c] = v; /* take character c */
847 n = *fmt++; /* and examine the next */
850 case 0: /* format ended too soon */
855 * A scanset of the form
857 * is defined as `the digit 0, the digit 1,
858 * the character +, the character -', but
859 * the effect of a scanset such as
861 * is implementation defined. The V7 Unix
862 * scanf treats `a-z' as `the letters a through
863 * z', but treats `a-a' as `the letter a, the
864 * character -, and the letter a'.
866 * For compatibility, the `-' is not considered
867 * to define a range if the character following
868 * it is either a close bracket (required by ANSI)
869 * or is not numerically greater than the character
870 * we just stored in the table (c).
874 || (table->__collate_load_error ? n < c :
875 __collate_range_cmp(n, c) < 0
879 break; /* resume the for(;;) */
882 /* fill in the range */
883 if (table->__collate_load_error) {
888 for (i = 0; i < 256; i ++)
889 if (__collate_range_cmp(c, i) <= 0 &&
890 __collate_range_cmp(i, n) <= 0
894 #if 1 /* XXX another disgusting compatibility hack */
897 * Alas, the V7 Unix scanf also treats formats
898 * such as [a-c-e] as `the letters a through e'.
899 * This too is permitted by the standard....
911 case ']': /* end of scanset */
914 default: /* just another character */
922 #ifndef NO_FLOATING_POINT
924 parsefloat(FILE *fp, char *buf, char *end, locale_t locale)
927 int infnanpos = 0, decptpos = 0;
929 S_START, S_GOTSIGN, S_INF, S_NAN, S_DONE, S_MAYBEHEX,
930 S_DIGITS, S_DECPT, S_FRAC, S_EXP, S_EXPDIGITS
933 const char *decpt = localeconv_l(locale)->decimal_point;
934 _Bool gotmantdig = 0, ishex = 0;
937 * We set commit = p whenever the string we have read so far
938 * constitutes a valid representation of a floating point
939 * number by itself. At some point, the parse will complete
940 * or fail, and we will ungetc() back to the last commit point.
941 * To ensure that the file offset gets updated properly, it is
942 * always necessary to read at least one character that doesn't
943 * match; thus, we can't short-circuit "infinity" or "nan(...)".
946 for (p = buf; p < end; ) {
952 if (c == '-' || c == '+')
977 (c != "nfinity"[infnanpos] &&
978 c != "NFINITY"[infnanpos]))
980 if (infnanpos == 1 || infnanpos == 6)
981 commit = p; /* inf or infinity */
987 if (c != 'A' && c != 'a')
991 if (c != 'N' && c != 'n')
1004 } else if (!isalnum(c) && c != '_')
1014 if (c == 'X' || c == 'x') {
1017 } else { /* we saw a '0', but no 'x' */
1022 if ((ishex && isxdigit(c)) || isdigit(c)) {
1031 if (c == decpt[decptpos]) {
1032 if (decpt[++decptpos] == '\0') {
1033 /* We read the complete decpt seq. */
1039 } else if (!decptpos) {
1040 /* We didn't read any decpt characters. */
1045 * We read part of a multibyte decimal point,
1046 * but the rest is invalid, so bail.
1051 if (((c == 'E' || c == 'e') && !ishex) ||
1052 ((c == 'P' || c == 'p') && ishex)) {
1057 } else if ((ishex && isxdigit(c)) || isdigit(c)) {
1064 state = S_EXPDIGITS;
1065 if (c == '-' || c == '+')
1079 if (--fp->pub._r > 0)
1081 else if (__srefill(fp))
1086 while (commit < --p)
1087 __ungetc(*(u_char *)p, fp);
1089 return (commit - buf);