2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Copyright (c) 2011 The FreeBSD Foundation
9 * Portions of this software were developed by David Chisnall
10 * under sponsorship from the FreeBSD Foundation.
12 * This code is derived from software contributed to Berkeley by
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid[] = "@(#)vfscanf.c 8.1 (Berkeley) 6/4/93";
42 #endif /* LIBC_SCCS and not lint */
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
46 #include "namespace.h"
56 #include "un-namespace.h"
59 #include "libc_private.h"
61 #include "xlocale_private.h"
63 #ifndef NO_FLOATING_POINT
67 #define BUF 513 /* Maximum length of numeric string. */
70 * Flags used during conversion.
72 #define LONG 0x01 /* l: long or double */
73 #define LONGDBL 0x02 /* L: long double */
74 #define SHORT 0x04 /* h: short */
75 #define SUPPRESS 0x08 /* *: suppress assignment */
76 #define POINTER 0x10 /* p: void * (as hex) */
77 #define NOSKIP 0x20 /* [ or c: do not skip blanks */
78 #define LONGLONG 0x400 /* ll: long long (+ deprecated q: quad) */
79 #define INTMAXT 0x800 /* j: intmax_t */
80 #define PTRDIFFT 0x1000 /* t: ptrdiff_t */
81 #define SIZET 0x2000 /* z: size_t */
82 #define SHORTSHORT 0x4000 /* hh: char */
83 #define UNSIGNED 0x8000 /* %[oupxX] conversions */
86 * The following are used in integral conversions only:
87 * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
89 #define SIGNOK 0x40 /* +/- is (still) legal */
90 #define NDIGITS 0x80 /* no digits detected */
91 #define PFXOK 0x100 /* 0x prefix is (still) legal */
92 #define NZDIGITS 0x200 /* no zero digits detected */
93 #define HAVESIGN 0x10000 /* sign detected */
98 #define CT_CHAR 0 /* %c conversion */
99 #define CT_CCL 1 /* %[...] conversion */
100 #define CT_STRING 2 /* %s conversion */
101 #define CT_INT 3 /* %[dioupxX] conversion */
102 #define CT_FLOAT 4 /* %[efgEFG] conversion */
104 static const u_char *__sccl(char *, const u_char *);
105 #ifndef NO_FLOATING_POINT
106 static int parsefloat(FILE *, char *, char *, locale_t);
109 __weak_reference(__vfscanf, vfscanf);
112 * Conversion functions are passed a pointer to this object instead of
113 * a real parameter to indicate that the assignment-suppression (*)
114 * flag was specified. We could use a NULL pointer to indicate this,
115 * but that would mask bugs in applications that call scanf() with a
118 static const int suppress;
119 #define SUPPRESS_PTR ((void *)&suppress)
121 static const mbstate_t initial_mbs;
124 * The following conversion functions return the number of characters consumed,
125 * or -1 on input failure. Character class conversion returns 0 on match
130 convert_char(FILE *fp, char * p, int width)
134 if (p == SUPPRESS_PTR) {
137 if ((n = fp->_r) < width) {
155 size_t r = __fread(p, 1, width, fp);
164 convert_wchar(FILE *fp, wchar_t *wcp, int width, locale_t locale)
172 while (width-- != 0 &&
173 (wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF) {
174 if (wcp != SUPPRESS_PTR)
175 *wcp++ = (wchar_t)wi;
184 convert_ccl(FILE *fp, char * p, int width, const char *ccltab)
189 if (p == SUPPRESS_PTR) {
191 while (ccltab[*fp->_p]) {
192 n++, fp->_r--, fp->_p++;
195 if (fp->_r <= 0 && __srefill(fp)) {
203 while (ccltab[*fp->_p]) {
208 if (fp->_r <= 0 && __srefill(fp)) {
223 convert_wccl(FILE *fp, wchar_t *wcp, int width, const char *ccltab,
232 if (wcp == SUPPRESS_PTR) {
233 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
234 width-- != 0 && ccltab[wctob(wi)])
237 __ungetwc(wi, fp, __get_locale());
239 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
240 width-- != 0 && ccltab[wctob(wi)]) {
241 *wcp++ = (wchar_t)wi;
245 __ungetwc(wi, fp, __get_locale());
254 convert_string(FILE *fp, char * p, int width)
259 if (p == SUPPRESS_PTR) {
261 while (!isspace(*fp->_p)) {
262 n++, fp->_r--, fp->_p++;
265 if (fp->_r <= 0 && __srefill(fp))
270 while (!isspace(*fp->_p)) {
275 if (fp->_r <= 0 && __srefill(fp))
285 convert_wstring(FILE *fp, wchar_t *wcp, int width, locale_t locale)
293 if (wcp == SUPPRESS_PTR) {
294 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
295 width-- != 0 && !iswspace(wi))
298 __ungetwc(wi, fp, __get_locale());
300 while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
301 width-- != 0 && !iswspace(wi)) {
302 *wcp++ = (wchar_t)wi;
306 __ungetwc(wi, fp, __get_locale());
313 * Read an integer, storing it in buf. The only relevant bit in the
314 * flags argument is PFXOK.
316 * Return 0 on a match failure, and the number of characters read
320 parseint(FILE *fp, char * __restrict buf, int width, int base, int flags)
322 /* `basefix' is used to avoid `if' tests */
323 static const short basefix[17] =
324 { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
328 flags |= SIGNOK | NDIGITS | NZDIGITS;
329 for (p = buf; width; width--) {
332 * Switch on the character; `goto ok' if we accept it
333 * as a part of number.
338 * The digit 0 is always legal, but is special. For
339 * %i conversions, if no digits (zero or nonzero) have
340 * been scanned (only signs), we will have base==0.
341 * In that case, we should set it to 8 and enable 0x
342 * prefixing. Also, if we have not scanned zero
343 * digits before this, do not turn off prefixing
344 * (someone else will turn it off if we have scanned
345 * any nonzero digits).
352 if (flags & NZDIGITS)
353 flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
355 flags &= ~(SIGNOK|PFXOK|NDIGITS);
358 /* 1 through 7 always legal */
359 case '1': case '2': case '3':
360 case '4': case '5': case '6': case '7':
361 base = basefix[base];
362 flags &= ~(SIGNOK | PFXOK | NDIGITS);
365 /* digits 8 and 9 ok iff decimal or hex */
367 base = basefix[base];
369 break; /* not legal here */
370 flags &= ~(SIGNOK | PFXOK | NDIGITS);
373 /* letters ok iff hex */
374 case 'A': case 'B': case 'C':
375 case 'D': case 'E': case 'F':
376 case 'a': case 'b': case 'c':
377 case 'd': case 'e': case 'f':
378 /* no need to fix base here */
380 break; /* not legal here */
381 flags &= ~(SIGNOK | PFXOK | NDIGITS);
384 /* sign ok only as first character */
386 if (flags & SIGNOK) {
394 * x ok iff flag still set & 2nd char (or 3rd char if
398 if (flags & PFXOK && p ==
399 buf + 1 + !!(flags & HAVESIGN)) {
400 base = 16; /* if %i */
408 * If we got here, c is not a legal character for a
409 * number. Stop accumulating digits.
414 * c is legal: store it and look at the next.
419 else if (__srefill(fp))
423 * If we had only a sign, it is no good; push back the sign.
424 * If the number ends in `x', it was [sign] '0' 'x', so push
425 * back the x and treat it as [sign] '0'.
427 if (flags & NDIGITS) {
429 (void) __ungetc(*(u_char *)--p, fp);
432 c = ((u_char *)p)[-1];
433 if (c == 'x' || c == 'X') {
435 (void) __ungetc(c, fp);
441 * __vfscanf - MT-safe version
444 __vfscanf(FILE *fp, char const *fmt0, va_list ap)
448 FLOCKFILE_CANCELSAFE(fp);
449 ret = __svfscanf(fp, __get_locale(), fmt0, ap);
450 FUNLOCKFILE_CANCELSAFE();
454 vfscanf_l(FILE *fp, locale_t locale, char const *fmt0, va_list ap)
459 FLOCKFILE_CANCELSAFE(fp);
460 ret = __svfscanf(fp, locale, fmt0, ap);
461 FUNLOCKFILE_CANCELSAFE();
466 * __svfscanf - non-MT-safe version of __vfscanf
469 __svfscanf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
471 #define GETARG(type) ((flags & SUPPRESS) ? SUPPRESS_PTR : va_arg(ap, type))
472 const u_char *fmt = (const u_char *)fmt0;
473 int c; /* character from format, or conversion */
474 size_t width; /* field width, or 0 */
475 int flags; /* flags as defined above */
476 int nassigned; /* number of fields assigned */
477 int nconversions; /* number of conversions */
478 int nr; /* characters read by the current conversion */
479 int nread; /* number of characters consumed from fp */
480 int base; /* base argument to conversion function */
481 char ccltab[256]; /* character class table for %[...] */
482 char buf[BUF]; /* buffer for numeric conversions */
494 while ((fp->_r > 0 || __srefill(fp) == 0) && isspace(*fp->_p))
495 nread++, fp->_r--, fp->_p++;
503 * switch on the format. continue if done;
504 * break once format type is derived.
510 if (fp->_r <= 0 && __srefill(fp))
532 flags |= LONGLONG; /* not quite */
551 case '0': case '1': case '2': case '3': case '4':
552 case '5': case '6': case '7': case '8': case '9':
553 width = width * 10 + c - '0';
583 flags |= PFXOK; /* enable 0x prefixing */
589 #ifndef NO_FLOATING_POINT
590 case 'A': case 'E': case 'F': case 'G':
591 case 'a': case 'e': case 'f': case 'g':
604 fmt = __sccl(ccltab, fmt);
617 case 'p': /* pointer format is like hex */
618 flags |= POINTER | PFXOK;
619 c = CT_INT; /* assumes sizeof(uintmax_t) */
620 flags |= UNSIGNED; /* >= sizeof(uintptr_t) */
625 if (flags & SUPPRESS) /* ??? */
627 if (flags & SHORTSHORT)
628 *va_arg(ap, char *) = nread;
629 else if (flags & SHORT)
630 *va_arg(ap, short *) = nread;
631 else if (flags & LONG)
632 *va_arg(ap, long *) = nread;
633 else if (flags & LONGLONG)
634 *va_arg(ap, long long *) = nread;
635 else if (flags & INTMAXT)
636 *va_arg(ap, intmax_t *) = nread;
637 else if (flags & SIZET)
638 *va_arg(ap, size_t *) = nread;
639 else if (flags & PTRDIFFT)
640 *va_arg(ap, ptrdiff_t *) = nread;
642 *va_arg(ap, int *) = nread;
649 * Disgusting backwards compatibility hack. XXX
651 case '\0': /* compat */
656 * We have a conversion that requires input.
658 if (fp->_r <= 0 && __srefill(fp))
662 * Consume leading white space, except for formats
663 * that suppress this.
665 if ((flags & NOSKIP) == 0) {
666 while (isspace(*fp->_p)) {
670 else if (__srefill(fp))
674 * Note that there is at least one character in
675 * the buffer, so conversions that do not set NOSKIP
676 * ca no longer result in an input failure.
686 /* scan arbitrary characters (sets NOSKIP) */
690 nr = convert_wchar(fp, GETARG(wchar_t *),
693 nr = convert_char(fp, GETARG(char *), width);
700 /* scan a (nonempty) character class (sets NOSKIP) */
702 width = (size_t)~0; /* `infinity' */
704 nr = convert_wccl(fp, GETARG(wchar_t *), width,
707 nr = convert_ccl(fp, GETARG(char *), width,
719 /* like CCL, but zero-length string OK, & no NOSKIP */
723 nr = convert_wstring(fp, GETARG(wchar_t *),
726 nr = convert_string(fp, GETARG(char *), width);
733 /* scan an integer as if by the conversion function */
735 if (width == 0 || width > sizeof(buf) - 1)
736 width = sizeof(buf) - 1;
738 /* size_t is unsigned, hence this optimisation */
739 if (--width > sizeof(buf) - 2)
740 width = sizeof(buf) - 2;
743 nr = parseint(fp, buf, width, base, flags);
746 if ((flags & SUPPRESS) == 0) {
750 if ((flags & UNSIGNED) == 0)
751 res = strtoimax_l(buf, (char **)NULL, base, locale);
753 res = strtoumax_l(buf, (char **)NULL, base, locale);
755 *va_arg(ap, void **) =
756 (void *)(uintptr_t)res;
757 else if (flags & SHORTSHORT)
758 *va_arg(ap, char *) = res;
759 else if (flags & SHORT)
760 *va_arg(ap, short *) = res;
761 else if (flags & LONG)
762 *va_arg(ap, long *) = res;
763 else if (flags & LONGLONG)
764 *va_arg(ap, long long *) = res;
765 else if (flags & INTMAXT)
766 *va_arg(ap, intmax_t *) = res;
767 else if (flags & PTRDIFFT)
768 *va_arg(ap, ptrdiff_t *) = res;
769 else if (flags & SIZET)
770 *va_arg(ap, size_t *) = res;
772 *va_arg(ap, int *) = res;
776 #ifndef NO_FLOATING_POINT
778 /* scan a floating point number as if by strtod */
779 if (width == 0 || width > sizeof(buf) - 1)
780 width = sizeof(buf) - 1;
781 nr = parsefloat(fp, buf, buf + width, locale);
784 if ((flags & SUPPRESS) == 0) {
785 if (flags & LONGDBL) {
786 long double res = strtold_l(buf, NULL,
788 *va_arg(ap, long double *) = res;
789 } else if (flags & LONG) {
790 double res = strtod_l(buf, NULL,
792 *va_arg(ap, double *) = res;
794 float res = strtof_l(buf, NULL, locale);
795 *va_arg(ap, float *) = res;
799 #endif /* !NO_FLOATING_POINT */
801 if (!(flags & SUPPRESS))
807 return (nconversions != 0 ? nassigned : EOF);
813 * Fill in the given table from the scanset at the given format
814 * (just after `['). Return a pointer to the character past the
815 * closing `]'. The table has a 1 wherever characters should be
816 * considered part of the scanset.
818 static const u_char *
819 __sccl(char *tab, const u_char *fmt)
822 struct xlocale_collate *table =
823 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
825 /* first `clear' the whole table */
826 c = *fmt++; /* first char hat => negated scanset */
828 v = 1; /* default => accept */
829 c = *fmt++; /* get new first char */
831 v = 0; /* default => reject */
833 /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
834 (void) memset(tab, v, 256);
837 return (fmt - 1);/* format ended before closing ] */
840 * Now set the entries corresponding to the actual scanset
841 * to the opposite of the above.
843 * The first character may be ']' (or '-') without being special;
844 * the last character may be '-'.
848 tab[c] = v; /* take character c */
850 n = *fmt++; /* and examine the next */
853 case 0: /* format ended too soon */
858 * A scanset of the form
860 * is defined as `the digit 0, the digit 1,
861 * the character +, the character -', but
862 * the effect of a scanset such as
864 * is implementation defined. The V7 Unix
865 * scanf treats `a-z' as `the letters a through
866 * z', but treats `a-a' as `the letter a, the
867 * character -, and the letter a'.
869 * For compatibility, the `-' is not considered
870 * to define a range if the character following
871 * it is either a close bracket (required by ANSI)
872 * or is not numerically greater than the character
873 * we just stored in the table (c).
877 || (table->__collate_load_error ? n < c :
878 __collate_range_cmp(n, c) < 0
882 break; /* resume the for(;;) */
885 /* fill in the range */
886 if (table->__collate_load_error) {
891 for (i = 0; i < 256; i ++)
892 if (__collate_range_cmp(c, i) <= 0 &&
893 __collate_range_cmp(i, n) <= 0
897 #if 1 /* XXX another disgusting compatibility hack */
900 * Alas, the V7 Unix scanf also treats formats
901 * such as [a-c-e] as `the letters a through e'.
902 * This too is permitted by the standard....
914 case ']': /* end of scanset */
917 default: /* just another character */
925 #ifndef NO_FLOATING_POINT
927 parsefloat(FILE *fp, char *buf, char *end, locale_t locale)
930 int infnanpos = 0, decptpos = 0;
932 S_START, S_GOTSIGN, S_INF, S_NAN, S_DONE, S_MAYBEHEX,
933 S_DIGITS, S_DECPT, S_FRAC, S_EXP, S_EXPDIGITS
936 const char *decpt = localeconv_l(locale)->decimal_point;
937 _Bool gotmantdig = 0, ishex = 0;
940 * We set commit = p whenever the string we have read so far
941 * constitutes a valid representation of a floating point
942 * number by itself. At some point, the parse will complete
943 * or fail, and we will ungetc() back to the last commit point.
944 * To ensure that the file offset gets updated properly, it is
945 * always necessary to read at least one character that doesn't
946 * match; thus, we can't short-circuit "infinity" or "nan(...)".
949 for (p = buf; p < end; ) {
955 if (c == '-' || c == '+')
980 (c != "nfinity"[infnanpos] &&
981 c != "NFINITY"[infnanpos]))
983 if (infnanpos == 1 || infnanpos == 6)
984 commit = p; /* inf or infinity */
990 if (c != 'A' && c != 'a')
994 if (c != 'N' && c != 'n')
1007 } else if (!isalnum(c) && c != '_')
1017 if (c == 'X' || c == 'x') {
1020 } else { /* we saw a '0', but no 'x' */
1025 if ((ishex && isxdigit(c)) || isdigit(c)) {
1034 if (c == decpt[decptpos]) {
1035 if (decpt[++decptpos] == '\0') {
1036 /* We read the complete decpt seq. */
1042 } else if (!decptpos) {
1043 /* We didn't read any decpt characters. */
1048 * We read part of a multibyte decimal point,
1049 * but the rest is invalid, so bail.
1054 if (((c == 'E' || c == 'e') && !ishex) ||
1055 ((c == 'P' || c == 'p') && ishex)) {
1060 } else if ((ishex && isxdigit(c)) || isdigit(c)) {
1067 state = S_EXPDIGITS;
1068 if (c == '-' || c == '+')
1084 else if (__srefill(fp))
1089 while (commit < --p)
1090 __ungetc(*(u_char *)p, fp);
1092 return (commit - buf);