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
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)vfscanf.c 8.1 (Berkeley) 6/4/93";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include "namespace.h"
54 #include "un-namespace.h"
57 #include "libc_private.h"
59 #include "xlocale_private.h"
61 #ifndef NO_FLOATING_POINT
65 #define BUF 513 /* Maximum length of numeric string. */
68 * Flags used during conversion.
70 #define LONG 0x01 /* l: long or double */
71 #define LONGDBL 0x02 /* L: long double */
72 #define SHORT 0x04 /* h: short */
73 #define SUPPRESS 0x08 /* *: suppress assignment */
74 #define POINTER 0x10 /* p: void * (as hex) */
75 #define NOSKIP 0x20 /* [ or c: do not skip blanks */
76 #define LONGLONG 0x400 /* ll: long long (+ deprecated q: quad) */
77 #define INTMAXT 0x800 /* j: intmax_t */
78 #define PTRDIFFT 0x1000 /* t: ptrdiff_t */
79 #define SIZET 0x2000 /* z: size_t */
80 #define SHORTSHORT 0x4000 /* hh: char */
81 #define UNSIGNED 0x8000 /* %[oupxX] conversions */
84 * The following are used in integral conversions only:
85 * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
87 #define SIGNOK 0x40 /* +/- is (still) legal */
88 #define NDIGITS 0x80 /* no digits detected */
89 #define PFXOK 0x100 /* 0x prefix is (still) legal */
90 #define NZDIGITS 0x200 /* no zero digits detected */
91 #define HAVESIGN 0x10000 /* sign detected */
96 #define CT_CHAR 0 /* %c conversion */
97 #define CT_CCL 1 /* %[...] conversion */
98 #define CT_STRING 2 /* %s conversion */
99 #define CT_INT 3 /* %[dioupxX] conversion */
100 #define CT_FLOAT 4 /* %[efgEFG] conversion */
102 static const u_char *__sccl(char *, const u_char *);
103 #ifndef NO_FLOATING_POINT
104 static int parsefloat(FILE *, char *, char *, locale_t);
107 __weak_reference(__vfscanf, vfscanf);
110 * Conversion functions are passed a pointer to this object instead of
111 * a real parameter to indicate that the assignment-suppression (*)
112 * flag was specified. We could use a NULL pointer to indicate this,
113 * but that would mask bugs in applications that call scanf() with a
116 static const int suppress;
117 #define SUPPRESS_PTR ((void *)&suppress)
119 static const mbstate_t initial_mbs;
122 * The following conversion functions return the number of characters consumed,
123 * or -1 on input failure. Character class conversion returns 0 on match
128 convert_char(FILE *fp, char * p, int width)
132 if (p == SUPPRESS_PTR) {
135 if ((n = fp->_r) < width) {
153 size_t r = __fread(p, 1, width, fp);
162 convert_wchar(FILE *fp, wchar_t *wcp, int width, locale_t locale)
170 while (width-- != 0 &&
171 (wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF) {
172 if (wcp != SUPPRESS_PTR)
173 *wcp++ = (wchar_t)wi;
182 convert_ccl(FILE *fp, char * p, int width, const char *ccltab)
187 if (p == SUPPRESS_PTR) {
189 while (ccltab[*fp->_p]) {
190 n++, fp->_r--, fp->_p++;
193 if (fp->_r <= 0 && __srefill(fp)) {
201 while (ccltab[*fp->_p]) {
206 if (fp->_r <= 0 && __srefill(fp)) {
221 convert_wccl(FILE *fp, wchar_t *wcp, int width, const char *ccltab,
230 if (wcp == SUPPRESS_PTR) {
231 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
232 width-- != 0 && ccltab[wctob(wi)])
235 __ungetwc(wi, fp, __get_locale());
237 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
238 width-- != 0 && ccltab[wctob(wi)]) {
239 *wcp++ = (wchar_t)wi;
243 __ungetwc(wi, fp, __get_locale());
252 convert_string(FILE *fp, char * p, int width)
257 if (p == SUPPRESS_PTR) {
259 while (!isspace(*fp->_p)) {
260 n++, fp->_r--, fp->_p++;
263 if (fp->_r <= 0 && __srefill(fp))
268 while (!isspace(*fp->_p)) {
273 if (fp->_r <= 0 && __srefill(fp))
283 convert_wstring(FILE *fp, wchar_t *wcp, int width, locale_t locale)
291 if (wcp == SUPPRESS_PTR) {
292 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
293 width-- != 0 && !iswspace(wi))
296 __ungetwc(wi, fp, __get_locale());
298 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
299 width-- != 0 && !iswspace(wi)) {
300 *wcp++ = (wchar_t)wi;
304 __ungetwc(wi, fp, __get_locale());
311 * Read an integer, storing it in buf. The only relevant bit in the
312 * flags argument is PFXOK.
314 * Return 0 on a match failure, and the number of characters read
318 parseint(FILE *fp, char * __restrict buf, int width, int base, int flags)
320 /* `basefix' is used to avoid `if' tests */
321 static const short basefix[17] =
322 { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
326 flags |= SIGNOK | NDIGITS | NZDIGITS;
327 for (p = buf; width; width--) {
330 * Switch on the character; `goto ok' if we accept it
331 * as a part of number.
336 * The digit 0 is always legal, but is special. For
337 * %i conversions, if no digits (zero or nonzero) have
338 * been scanned (only signs), we will have base==0.
339 * In that case, we should set it to 8 and enable 0x
340 * prefixing. Also, if we have not scanned zero
341 * digits before this, do not turn off prefixing
342 * (someone else will turn it off if we have scanned
343 * any nonzero digits).
350 if (flags & NZDIGITS)
351 flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
353 flags &= ~(SIGNOK|PFXOK|NDIGITS);
356 /* 1 through 7 always legal */
357 case '1': case '2': case '3':
358 case '4': case '5': case '6': case '7':
359 base = basefix[base];
360 flags &= ~(SIGNOK | PFXOK | NDIGITS);
363 /* digits 8 and 9 ok iff decimal or hex */
365 base = basefix[base];
367 break; /* not legal here */
368 flags &= ~(SIGNOK | PFXOK | NDIGITS);
371 /* letters ok iff hex */
372 case 'A': case 'B': case 'C':
373 case 'D': case 'E': case 'F':
374 case 'a': case 'b': case 'c':
375 case 'd': case 'e': case 'f':
376 /* no need to fix base here */
378 break; /* not legal here */
379 flags &= ~(SIGNOK | PFXOK | NDIGITS);
382 /* sign ok only as first character */
384 if (flags & SIGNOK) {
392 * x ok iff flag still set & 2nd char (or 3rd char if
396 if (flags & PFXOK && p ==
397 buf + 1 + !!(flags & HAVESIGN)) {
398 base = 16; /* if %i */
406 * If we got here, c is not a legal character for a
407 * number. Stop accumulating digits.
412 * c is legal: store it and look at the next.
417 else if (__srefill(fp))
421 * If we had only a sign, it is no good; push back the sign.
422 * If the number ends in `x', it was [sign] '0' 'x', so push
423 * back the x and treat it as [sign] '0'.
425 if (flags & NDIGITS) {
427 (void) __ungetc(*(u_char *)--p, fp);
430 c = ((u_char *)p)[-1];
431 if (c == 'x' || c == 'X') {
433 (void) __ungetc(c, fp);
439 * __vfscanf - MT-safe version
442 __vfscanf(FILE *fp, char const *fmt0, va_list ap)
447 ret = __svfscanf(fp, __get_locale(), fmt0, ap);
452 vfscanf_l(FILE *fp, locale_t locale, char const *fmt0, va_list ap)
458 ret = __svfscanf(fp, locale, fmt0, ap);
464 * __svfscanf - non-MT-safe version of __vfscanf
467 __svfscanf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
469 #define GETARG(type) ((flags & SUPPRESS) ? SUPPRESS_PTR : va_arg(ap, type))
470 const u_char *fmt = (const u_char *)fmt0;
471 int c; /* character from format, or conversion */
472 size_t width; /* field width, or 0 */
473 int flags; /* flags as defined above */
474 int nassigned; /* number of fields assigned */
475 int nconversions; /* number of conversions */
476 int nr; /* characters read by the current conversion */
477 int nread; /* number of characters consumed from fp */
478 int base; /* base argument to conversion function */
479 char ccltab[256]; /* character class table for %[...] */
480 char buf[BUF]; /* buffer for numeric conversions */
492 while ((fp->_r > 0 || __srefill(fp) == 0) && isspace(*fp->_p))
493 nread++, fp->_r--, fp->_p++;
501 * switch on the format. continue if done;
502 * break once format type is derived.
508 if (fp->_r <= 0 && __srefill(fp))
530 flags |= LONGLONG; /* not quite */
549 case '0': case '1': case '2': case '3': case '4':
550 case '5': case '6': case '7': case '8': case '9':
551 width = width * 10 + c - '0';
581 flags |= PFXOK; /* enable 0x prefixing */
587 #ifndef NO_FLOATING_POINT
588 case 'A': case 'E': case 'F': case 'G':
589 case 'a': case 'e': case 'f': case 'g':
602 fmt = __sccl(ccltab, fmt);
615 case 'p': /* pointer format is like hex */
616 flags |= POINTER | PFXOK;
617 c = CT_INT; /* assumes sizeof(uintmax_t) */
618 flags |= UNSIGNED; /* >= sizeof(uintptr_t) */
623 if (flags & SUPPRESS) /* ??? */
625 if (flags & SHORTSHORT)
626 *va_arg(ap, char *) = nread;
627 else if (flags & SHORT)
628 *va_arg(ap, short *) = nread;
629 else if (flags & LONG)
630 *va_arg(ap, long *) = nread;
631 else if (flags & LONGLONG)
632 *va_arg(ap, long long *) = nread;
633 else if (flags & INTMAXT)
634 *va_arg(ap, intmax_t *) = nread;
635 else if (flags & SIZET)
636 *va_arg(ap, size_t *) = nread;
637 else if (flags & PTRDIFFT)
638 *va_arg(ap, ptrdiff_t *) = nread;
640 *va_arg(ap, int *) = nread;
647 * Disgusting backwards compatibility hack. XXX
649 case '\0': /* compat */
654 * We have a conversion that requires input.
656 if (fp->_r <= 0 && __srefill(fp))
660 * Consume leading white space, except for formats
661 * that suppress this.
663 if ((flags & NOSKIP) == 0) {
664 while (isspace(*fp->_p)) {
668 else if (__srefill(fp))
672 * Note that there is at least one character in
673 * the buffer, so conversions that do not set NOSKIP
674 * ca no longer result in an input failure.
684 /* scan arbitrary characters (sets NOSKIP) */
688 nr = convert_wchar(fp, GETARG(wchar_t *),
691 nr = convert_char(fp, GETARG(char *), width);
698 /* scan a (nonempty) character class (sets NOSKIP) */
700 width = (size_t)~0; /* `infinity' */
702 nr = convert_wccl(fp, GETARG(wchar_t *), width,
705 nr = convert_ccl(fp, GETARG(char *), width,
717 /* like CCL, but zero-length string OK, & no NOSKIP */
721 nr = convert_wstring(fp, GETARG(wchar_t *),
724 nr = convert_string(fp, GETARG(char *), width);
731 /* scan an integer as if by the conversion function */
733 if (width == 0 || width > sizeof(buf) - 1)
734 width = sizeof(buf) - 1;
736 /* size_t is unsigned, hence this optimisation */
737 if (--width > sizeof(buf) - 2)
738 width = sizeof(buf) - 2;
741 nr = parseint(fp, buf, width, base, flags);
744 if ((flags & SUPPRESS) == 0) {
748 if ((flags & UNSIGNED) == 0)
749 res = strtoimax_l(buf, (char **)NULL, base, locale);
751 res = strtoumax_l(buf, (char **)NULL, base, locale);
753 *va_arg(ap, void **) =
754 (void *)(uintptr_t)res;
755 else if (flags & SHORTSHORT)
756 *va_arg(ap, char *) = res;
757 else if (flags & SHORT)
758 *va_arg(ap, short *) = res;
759 else if (flags & LONG)
760 *va_arg(ap, long *) = res;
761 else if (flags & LONGLONG)
762 *va_arg(ap, long long *) = res;
763 else if (flags & INTMAXT)
764 *va_arg(ap, intmax_t *) = res;
765 else if (flags & PTRDIFFT)
766 *va_arg(ap, ptrdiff_t *) = res;
767 else if (flags & SIZET)
768 *va_arg(ap, size_t *) = res;
770 *va_arg(ap, int *) = res;
774 #ifndef NO_FLOATING_POINT
776 /* scan a floating point number as if by strtod */
777 if (width == 0 || width > sizeof(buf) - 1)
778 width = sizeof(buf) - 1;
779 nr = parsefloat(fp, buf, buf + width, locale);
782 if ((flags & SUPPRESS) == 0) {
783 if (flags & LONGDBL) {
784 long double res = strtold_l(buf, NULL,
786 *va_arg(ap, long double *) = res;
787 } else if (flags & LONG) {
788 double res = strtod_l(buf, NULL,
790 *va_arg(ap, double *) = res;
792 float res = strtof_l(buf, NULL, locale);
793 *va_arg(ap, float *) = res;
797 #endif /* !NO_FLOATING_POINT */
799 if (!(flags & SUPPRESS))
805 return (nconversions != 0 ? nassigned : EOF);
811 * Fill in the given table from the scanset at the given format
812 * (just after `['). Return a pointer to the character past the
813 * closing `]'. The table has a 1 wherever characters should be
814 * considered part of the scanset.
816 static const u_char *
817 __sccl(char *tab, const u_char *fmt)
820 struct xlocale_collate *table =
821 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
823 /* first `clear' the whole table */
824 c = *fmt++; /* first char hat => negated scanset */
826 v = 1; /* default => accept */
827 c = *fmt++; /* get new first char */
829 v = 0; /* default => reject */
831 /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
832 (void) memset(tab, v, 256);
835 return (fmt - 1);/* format ended before closing ] */
838 * Now set the entries corresponding to the actual scanset
839 * to the opposite of the above.
841 * The first character may be ']' (or '-') without being special;
842 * the last character may be '-'.
846 tab[c] = v; /* take character c */
848 n = *fmt++; /* and examine the next */
851 case 0: /* format ended too soon */
856 * A scanset of the form
858 * is defined as `the digit 0, the digit 1,
859 * the character +, the character -', but
860 * the effect of a scanset such as
862 * is implementation defined. The V7 Unix
863 * scanf treats `a-z' as `the letters a through
864 * z', but treats `a-a' as `the letter a, the
865 * character -, and the letter a'.
867 * For compatibility, the `-' is not considerd
868 * to define a range if the character following
869 * it is either a close bracket (required by ANSI)
870 * or is not numerically greater than the character
871 * we just stored in the table (c).
875 || (table->__collate_load_error ? n < c :
876 __collate_range_cmp (table, n, c) < 0
880 break; /* resume the for(;;) */
883 /* fill in the range */
884 if (table->__collate_load_error) {
889 for (i = 0; i < 256; i ++)
890 if ( __collate_range_cmp (table, c, i) < 0
891 && __collate_range_cmp (table, i, n) <= 0
895 #if 1 /* XXX another disgusting compatibility hack */
898 * Alas, the V7 Unix scanf also treats formats
899 * such as [a-c-e] as `the letters a through e'.
900 * This too is permitted by the standard....
912 case ']': /* end of scanset */
915 default: /* just another character */
923 #ifndef NO_FLOATING_POINT
925 parsefloat(FILE *fp, char *buf, char *end, locale_t locale)
928 int infnanpos = 0, decptpos = 0;
930 S_START, S_GOTSIGN, S_INF, S_NAN, S_DONE, S_MAYBEHEX,
931 S_DIGITS, S_DECPT, S_FRAC, S_EXP, S_EXPDIGITS
934 const char *decpt = localeconv_l(locale)->decimal_point;
935 _Bool gotmantdig = 0, ishex = 0;
938 * We set commit = p whenever the string we have read so far
939 * constitutes a valid representation of a floating point
940 * number by itself. At some point, the parse will complete
941 * or fail, and we will ungetc() back to the last commit point.
942 * To ensure that the file offset gets updated properly, it is
943 * always necessary to read at least one character that doesn't
944 * match; thus, we can't short-circuit "infinity" or "nan(...)".
947 for (p = buf; p < end; ) {
953 if (c == '-' || c == '+')
978 (c != "nfinity"[infnanpos] &&
979 c != "NFINITY"[infnanpos]))
981 if (infnanpos == 1 || infnanpos == 6)
982 commit = p; /* inf or infinity */
988 if (c != 'A' && c != 'a')
992 if (c != 'N' && c != 'n')
1005 } else if (!isalnum(c) && c != '_')
1015 if (c == 'X' || c == 'x') {
1018 } else { /* we saw a '0', but no 'x' */
1023 if ((ishex && isxdigit(c)) || isdigit(c)) {
1032 if (c == decpt[decptpos]) {
1033 if (decpt[++decptpos] == '\0') {
1034 /* We read the complete decpt seq. */
1040 } else if (!decptpos) {
1041 /* We didn't read any decpt characters. */
1046 * We read part of a multibyte decimal point,
1047 * but the rest is invalid, so bail.
1052 if (((c == 'E' || c == 'e') && !ishex) ||
1053 ((c == 'P' || c == 'p') && ishex)) {
1058 } else if ((ishex && isxdigit(c)) || isdigit(c)) {
1065 state = S_EXPDIGITS;
1066 if (c == '-' || c == '+')
1082 else if (__srefill(fp))
1087 while (commit < --p)
1088 __ungetc(*(u_char *)p, fp);
1090 return (commit - buf);