2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #pragma clang diagnostic push
34 #pragma clang diagnostic ignored "-Wcomma"
36 #if defined(LIBC_SCCS) && !defined(lint)
37 static char sccsid
[] = "@(#)vfscanf.c 8.1 (Berkeley) 6/4/93";
38 #endif /* LIBC_SCCS and not lint */
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD: src/lib/libc/stdio/vfscanf.c,v 1.43 2009/01/19 06:19:51 das Exp $");
42 #include "xlocale_private.h"
44 #include "namespace.h"
55 #include "un-namespace.h"
58 #include "libc_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
*, locale_t
);
103 #ifndef NO_FLOATING_POINT
104 static int parsefloat(FILE *, char **, size_t, locale_t
);
107 __weak_reference(__vfscanf
, vfscanf
);
110 * __vfscanf - MT-safe version
113 __vfscanf(FILE * __restrict fp
, char const * __restrict fmt0
, va_list ap
)
118 ret
= __svfscanf_l(fp
, __current_locale(), fmt0
, ap
);
124 vfscanf_l(FILE * __restrict fp
, locale_t loc
, char const * __restrict fmt0
, va_list ap
)
128 NORMALIZE_LOCALE(loc
);
130 ret
= __svfscanf_l(fp
, loc
, fmt0
, ap
);
136 * __svfscanf - non-MT-safe version of __vfscanf
138 __private_extern__
int
139 __svfscanf_l(FILE * __restrict fp
, locale_t loc
, const char * __restrict fmt0
, va_list ap
)
141 const u_char
*fmt
= (const u_char
*)fmt0
;
142 int c
; /* character from format, or conversion */
143 size_t width
; /* field width, or 0 */
144 char *p
; /* points into all kinds of strings */
145 int n
; /* handy integer */
146 int flags
; /* flags as defined above */
147 char *p0
; /* saves original value of p when necessary */
148 int nassigned
; /* number of fields assigned */
149 int nread
; /* number of characters consumed from fp */
150 int base
; /* base argument to conversion function */
151 char ccltab
[256]; /* character class table for %[...] */
152 char buf
[BUF
]; /* buffer for numeric and mb conversions */
153 wchar_t *wcp
; /* handy wide character pointer */
154 size_t nconv
; /* length of multibyte sequence converted */
155 int index
; /* %index$, zero if unset */
156 va_list ap_orig
; /* to reset ap to first argument */
157 static const mbstate_t initial
;
161 /* `basefix' is used to avoid `if' tests in the integer scanner */
162 static const short basefix
[17] =
163 { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
165 NORMALIZE_LOCALE(loc
);
166 mb_cur_max
= MB_CUR_MAX_L(loc
);
171 va_copy(ap_orig
, ap
);
176 if (isspace_l(c
, loc
)) {
177 while ((fp
->_r
> 0 || __srefill(fp
) == 0) && isspace_l(*fp
->_p
, loc
))
178 nread
++, fp
->_r
--, fp
->_p
++;
182 if (fp
->_r
<= 0 && __srefill(fp
))
189 * switch on the format. continue if done;
190 * break once format type is derived.
195 /* Consume leading white space */
197 if (fp
->_r
<= 0 && __srefill(fp
))
199 if (!isspace_l(*fp
->_p
, loc
))
214 if (index
< 1 || index
> NL_ARGMAX
|| fmt
[-3] != '%') {
219 va_copy(ap
, ap_orig
); /* reset to %1$ */
220 for (; index
> 1; index
--) {
238 flags
|= LONGLONG
; /* not quite */
257 case '0': case '1': case '2': case '3': case '4':
258 case '5': case '6': case '7': case '8': case '9':
259 width
= width
* 10 + c
- '0';
289 flags
|= PFXOK
; /* enable 0x prefixing */
295 #ifndef NO_FLOATING_POINT
296 case 'A': case 'E': case 'F': case 'G':
297 case 'a': case 'e': case 'f': case 'g':
310 fmt
= __sccl(ccltab
, fmt
, loc
);
323 case 'p': /* pointer format is like hex */
324 flags
|= POINTER
| PFXOK
;
325 c
= CT_INT
; /* assumes sizeof(uintmax_t) */
326 flags
|= UNSIGNED
; /* >= sizeof(uintptr_t) */
332 if (flags
& SUPPRESS
) /* ??? */
334 void *ptr
= va_arg(ap
, void *);
337 else if (flags
& SHORTSHORT
)
338 *(char *)ptr
= nread
;
339 else if (flags
& SHORT
)
340 *(short *)ptr
= nread
;
341 else if (flags
& LONG
)
342 *(long *)ptr
= nread
;
343 else if (flags
& LONGLONG
)
344 *(long long *)ptr
= nread
;
345 else if (flags
& INTMAXT
)
346 *(intmax_t *)ptr
= nread
;
347 else if (flags
& SIZET
)
348 *(size_t *)ptr
= nread
;
349 else if (flags
& PTRDIFFT
)
350 *(ptrdiff_t *)ptr
= nread
;
359 * Disgusting backwards compatibility hack. XXX
361 case '\0': /* compat */
366 * We have a conversion that requires input.
368 if (fp
->_r
<= 0 && __srefill(fp
))
372 * Consume leading white space, except for formats
373 * that suppress this.
375 if ((flags
& NOSKIP
) == 0) {
376 while (isspace_l(*fp
->_p
, loc
)) {
380 else if (__srefill(fp
))
384 * Note that there is at least one character in
385 * the buffer, so conversions that do not set NOSKIP
386 * ca no longer result in an input failure.
396 /* scan arbitrary characters (sets NOSKIP) */
400 if ((flags
& SUPPRESS
) == 0)
401 wcp
= va_arg(ap
, wchar_t *);
406 if (n
== mb_cur_max
) {
407 fp
->_flags
|= __SERR
;
414 nconv
= mbrtowc_l(wcp
, buf
, n
, &mbs
, loc
);
415 if (nconv
== (size_t)-1) {
416 fp
->_flags
|= __SERR
;
419 if (nconv
== 0 && !(flags
& SUPPRESS
))
421 if (nconv
!= (size_t)-2) {
424 if (!(flags
& SUPPRESS
))
428 if (fp
->_r
<= 0 && __srefill(fp
)) {
430 fp
->_flags
|= __SERR
;
436 if (!(flags
& SUPPRESS
))
438 } else if (flags
& SUPPRESS
) {
441 if ((n
= fp
->_r
) < width
) {
459 size_t r
= __fread((void *)va_arg(ap
, char *), 1,
470 /* scan a (nonempty) character class (sets NOSKIP) */
472 width
= (size_t)~0; /* `infinity' */
473 /* take only those things in the class */
478 if ((flags
& SUPPRESS
) == 0)
479 wcp
= va_arg(ap
, wchar_t *);
485 if (n
== mb_cur_max
) {
486 fp
->_flags
|= __SERR
;
493 nconv
= mbrtowc_l(wcp
, buf
, n
, &mbs
, loc
);
494 if (nconv
== (size_t)-1) {
495 fp
->_flags
|= __SERR
;
500 if (nconv
!= (size_t)-2) {
501 if (wctob_l(*wcp
, loc
) != EOF
&&
502 !ccltab
[wctob_l(*wcp
, loc
)]) {
512 if (!(flags
& SUPPRESS
))
517 if (fp
->_r
<= 0 && __srefill(fp
)) {
519 fp
->_flags
|= __SERR
;
526 fp
->_flags
|= __SERR
;
532 if (!(flags
& SUPPRESS
)) {
536 } else if (flags
& SUPPRESS
) {
538 while (ccltab
[*fp
->_p
]) {
539 n
++, fp
->_r
--, fp
->_p
++;
542 if (fp
->_r
<= 0 && __srefill(fp
)) {
551 p0
= p
= va_arg(ap
, char *);
552 while (ccltab
[*fp
->_p
]) {
557 if (fp
->_r
<= 0 && __srefill(fp
)) {
573 /* like CCL, but zero-length string OK, & no NOSKIP */
579 if ((flags
& SUPPRESS
) == 0)
580 wcp
= va_arg(ap
, wchar_t *);
585 if (n
== mb_cur_max
) {
586 fp
->_flags
|= __SERR
;
593 nconv
= mbrtowc_l(wcp
, buf
, n
, &mbs
, loc
);
594 if (nconv
== (size_t)-1) {
595 fp
->_flags
|= __SERR
;
600 if (nconv
!= (size_t)-2) {
601 if (iswspace_l(*wcp
, loc
)) {
611 if (!(flags
& SUPPRESS
))
615 if (fp
->_r
<= 0 && __srefill(fp
)) {
617 fp
->_flags
|= __SERR
;
623 if (!(flags
& SUPPRESS
)) {
627 } else if (flags
& SUPPRESS
) {
629 while (!isspace_l(*fp
->_p
, loc
)) {
630 n
++, fp
->_r
--, fp
->_p
++;
633 if (fp
->_r
<= 0 && __srefill(fp
))
638 p0
= p
= va_arg(ap
, char *);
639 while (!isspace_l(*fp
->_p
, loc
)) {
644 if (fp
->_r
<= 0 && __srefill(fp
))
654 /* scan an integer as if by the conversion function */
656 if (width
== 0 || width
> sizeof(buf
) - 1)
657 width
= sizeof(buf
) - 1;
659 /* size_t is unsigned, hence this optimisation */
660 if (--width
> sizeof(buf
) - 2)
661 width
= sizeof(buf
) - 2;
664 flags
|= SIGNOK
| NDIGITS
| NZDIGITS
;
665 for (p
= buf
; width
; width
--) {
668 * Switch on the character; `goto ok'
669 * if we accept it as a part of number.
674 * The digit 0 is always legal, but is
675 * special. For %i conversions, if no
676 * digits (zero or nonzero) have been
677 * scanned (only signs), we will have
678 * base==0. In that case, we should set
679 * it to 8 and enable 0x prefixing.
680 * Also, if we have not scanned zero digits
681 * before this, do not turn off prefixing
682 * (someone else will turn it off if we
683 * have scanned any nonzero digits).
690 if (flags
& NZDIGITS
)
691 flags
&= ~(SIGNOK
|NZDIGITS
|NDIGITS
);
693 flags
&= ~(SIGNOK
|PFXOK
|NDIGITS
);
696 /* 1 through 7 always legal */
697 case '1': case '2': case '3':
698 case '4': case '5': case '6': case '7':
699 base
= basefix
[base
];
700 flags
&= ~(SIGNOK
| PFXOK
| NDIGITS
);
703 /* digits 8 and 9 ok iff decimal or hex */
705 base
= basefix
[base
];
707 break; /* not legal here */
708 flags
&= ~(SIGNOK
| PFXOK
| NDIGITS
);
711 /* letters ok iff hex */
712 case 'A': case 'B': case 'C':
713 case 'D': case 'E': case 'F':
714 case 'a': case 'b': case 'c':
715 case 'd': case 'e': case 'f':
716 /* no need to fix base here */
718 break; /* not legal here */
719 flags
&= ~(SIGNOK
| PFXOK
| NDIGITS
);
722 /* sign ok only as first character */
724 if (flags
& SIGNOK
) {
732 * x ok iff flag still set & 2nd char (or
733 * 3rd char if we have a sign).
736 if (flags
& PFXOK
&& p
==
737 buf
+ 1 + !!(flags
& HAVESIGN
)) {
738 base
= 16; /* if %i */
746 * If we got here, c is not a legal character
747 * for a number. Stop accumulating digits.
752 * c is legal: store it and look at the next.
757 else if (__srefill(fp
))
761 * If we had only a sign, it is no good; push
762 * back the sign. If the number ends in `x',
763 * it was [sign] '0' 'x', so push back the x
764 * and treat it as [sign] '0'.
766 if (flags
& NDIGITS
) {
768 (void) __ungetc(*(u_char
*)--p
, fp
);
771 c
= ((u_char
*)p
)[-1];
772 if (c
== 'x' || c
== 'X') {
774 (void) __ungetc(c
, fp
);
776 if ((flags
& SUPPRESS
) == 0) {
780 if ((flags
& UNSIGNED
) == 0)
781 res
= strtoimax_l(buf
, (char **)NULL
, base
, loc
);
783 res
= strtoumax_l(buf
, (char **)NULL
, base
, loc
);
785 *va_arg(ap
, void **) =
786 (void *)(uintptr_t)res
;
787 else if (flags
& SHORTSHORT
)
788 *va_arg(ap
, char *) = res
;
789 else if (flags
& SHORT
)
790 *va_arg(ap
, short *) = res
;
791 else if (flags
& LONG
)
792 *va_arg(ap
, long *) = res
;
793 else if (flags
& LONGLONG
)
794 *va_arg(ap
, long long *) = res
;
795 else if (flags
& INTMAXT
)
796 *va_arg(ap
, intmax_t *) = res
;
797 else if (flags
& PTRDIFFT
)
798 *va_arg(ap
, ptrdiff_t *) = res
;
799 else if (flags
& SIZET
)
800 *va_arg(ap
, size_t *) = res
;
802 *va_arg(ap
, int *) = res
;
808 #ifndef NO_FLOATING_POINT
812 /* scan a floating point number as if by strtod */
813 if ((width
= parsefloat(fp
, &pbuf
, width
, loc
)) == 0)
815 if ((flags
& SUPPRESS
) == 0) {
816 if (flags
& LONGDBL
) {
817 long double res
= strtold_l(pbuf
, &p
, loc
);
818 *va_arg(ap
, long double *) = res
;
819 } else if (flags
& LONG
) {
820 double res
= strtod_l(pbuf
, &p
, loc
);
821 *va_arg(ap
, double *) = res
;
823 float res
= strtof_l(pbuf
, &p
, loc
);
824 *va_arg(ap
, float *) = res
;
831 #endif /* !NO_FLOATING_POINT */
835 return (nassigned
? nassigned
: EOF
);
841 __svfscanf(FILE * __restrict fp
, const char * __restrict fmt0
, va_list ap
)
843 return __svfscanf_l(fp
, __current_locale(), fmt0
, ap
);
847 * Fill in the given table from the scanset at the given format
848 * (just after `['). Return a pointer to the character past the
849 * closing `]'. The table has a 1 wherever characters should be
850 * considered part of the scanset.
852 static const u_char
*
853 __sccl(tab
, fmt
, loc
)
860 /* first `clear' the whole table */
861 c
= *fmt
++; /* first char hat => negated scanset */
863 v
= 1; /* default => accept */
864 c
= *fmt
++; /* get new first char */
866 v
= 0; /* default => reject */
868 /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
869 (void) memset(tab
, v
, 256);
872 return (fmt
- 1);/* format ended before closing ] */
875 * Now set the entries corresponding to the actual scanset
876 * to the opposite of the above.
878 * The first character may be ']' (or '-') without being special;
879 * the last character may be '-'.
883 tab
[c
] = v
; /* take character c */
885 n
= *fmt
++; /* and examine the next */
888 case 0: /* format ended too soon */
894 * A scanset of the form
896 * is defined as `the digit 0, the digit 1,
897 * the character +, the character -', but
898 * the effect of a scanset such as
900 * is implementation defined. The V7 Unix
901 * scanf treats `a-z' as `the letters a through
902 * z', but treats `a-a' as `the letter a, the
903 * character -, and the letter a'.
905 * For compatibility, the `-' is not considerd
906 * to define a range if the character following
907 * it is either a close bracket (required by ANSI)
908 * or is not numerically greater than the character
909 * we just stored in the table (c).
913 || (loc
->__collate_load_error
? n
< c
:
914 __collate_range_cmp (n
, c
, loc
) < 0
918 break; /* resume the for(;;) */
921 /* fill in the range */
922 if (loc
->__collate_load_error
) {
927 for (i
= 0; i
< 256; i
++)
928 if ( __collate_range_cmp (c
, i
, loc
) < 0
929 && __collate_range_cmp (i
, n
, loc
) <= 0
933 #if 1 /* XXX another disgusting compatibility hack */
936 * Alas, the V7 Unix scanf also treats formats
937 * such as [a-c-e] as `the letters a through e'.
938 * This too is permitted by the standard....
950 case ']': /* end of scanset */
953 default: /* just another character */
961 #ifndef NO_FLOATING_POINT
963 * Maintain a per-thread parsefloat buffer, shared by __svfscanf_l and
966 #ifdef BUILDING_VARIANT
967 extern char *__parsefloat_buf(size_t s
);
968 #else /* !BUILDING_VARIANT */
969 __private_extern__
char *
970 __parsefloat_buf(size_t s
)
973 static pthread_key_t parsefloat_tsd_key
= (pthread_key_t
)-1;
974 static pthread_mutex_t parsefloat_tsd_lock
= PTHREAD_MUTEX_INITIALIZER
;
975 static size_t bsiz
= 0;
977 if (parsefloat_tsd_key
== (pthread_key_t
)-1) {
978 pthread_mutex_lock(&parsefloat_tsd_lock
);
979 if (parsefloat_tsd_key
== (pthread_key_t
)-1) {
980 parsefloat_tsd_key
= __LIBC_PTHREAD_KEY_PARSEFLOAT
;
981 pthread_key_init_np(parsefloat_tsd_key
, free
);
983 pthread_mutex_unlock(&parsefloat_tsd_lock
);
985 if ((b
= (char *)pthread_getspecific(parsefloat_tsd_key
)) == NULL
) {
986 bsiz
= s
> BUF
? s
: BUF
;
987 b
= (char *)malloc(bsiz
);
992 pthread_setspecific(parsefloat_tsd_key
, b
);
996 b
= (char *)reallocf(b
, s
);
997 pthread_setspecific(parsefloat_tsd_key
, b
);
1006 #endif /* BUILDING_VARIANT */
1009 parsefloat(FILE *fp
, char **buf
, size_t width
, locale_t loc
)
1012 int infnanpos
= 0, decptpos
= 0;
1014 S_START
, S_GOTSIGN
, S_INF
, S_NAN
, S_DONE
, S_MAYBEHEX
,
1015 S_DIGITS
, S_DECPT
, S_FRAC
, S_EXP
, S_EXPDIGITS
1018 const char *decpt
= localeconv_l(loc
)->decimal_point
;
1019 _Bool gotmantdig
= 0, ishex
= 0;
1024 s
= (width
== 0 ? BUF
: (width
+ 1));
1025 if ((b
= __parsefloat_buf(s
)) == NULL
) {
1031 * We set commit = p whenever the string we have read so far
1032 * constitutes a valid representation of a floating point
1033 * number by itself. At some point, the parse will complete
1034 * or fail, and we will ungetc() back to the last commit point.
1035 * To ensure that the file offset gets updated properly, it is
1036 * always necessary to read at least one character that doesn't
1037 * match; thus, we can't short-circuit "infinity" or "nan(...)".
1040 for (p
= b
; width
== 0 || p
< e
; ) {
1046 if (c
== '-' || c
== '+')
1070 if (infnanpos
> 6 ||
1071 (c
!= "nfinity"[infnanpos
] &&
1072 c
!= "NFINITY"[infnanpos
]))
1074 if (infnanpos
== 1 || infnanpos
== 6)
1075 commit
= p
; /* inf or infinity */
1079 switch (infnanpos
) {
1081 if (c
!= 'A' && c
!= 'a')
1085 if (c
!= 'N' && c
!= 'n')
1098 } else if (!isalnum_l(c
, loc
) && c
!= '_')
1108 if (c
== 'X' || c
== 'x') {
1111 } else { /* we saw a '0', but no 'x' */
1116 if ((ishex
&& isxdigit_l(c
, loc
)) || isdigit_l(c
, loc
)) {
1125 if (c
== decpt
[decptpos
]) {
1126 if (decpt
[++decptpos
] == '\0') {
1127 /* We read the complete decpt seq. */
1133 } else if (!decptpos
) {
1134 /* We didn't read any decpt characters. */
1139 * We read part of a multibyte decimal point,
1140 * but the rest is invalid, so bail.
1145 if (((c
== 'E' || c
== 'e') && !ishex
) ||
1146 ((c
== 'P' || c
== 'p') && ishex
)) {
1151 } else if ((ishex
&& isxdigit_l(c
, loc
)) || isdigit_l(c
, loc
)) {
1158 state
= S_EXPDIGITS
;
1159 if (c
== '-' || c
== '+')
1164 if (isdigit_l(c
, loc
))
1170 LIBC_ABORT("unknown state %d", state
);
1173 ssize_t diff
= (p
- b
);
1174 ssize_t com
= (commit
- b
);
1176 b
= __parsefloat_buf(s
);
1188 else if (__srefill(fp
))
1193 while (commit
< --p
)
1194 __ungetc(*(u_char
*)p
, fp
);
1197 return (commit
- b
);
1200 #pragma clang diagnostic push