vfscanf.c revision 234836
117680Spst/*-
298527Sfenner * Copyright (c) 1990, 1993
317680Spst *	The Regents of the University of California.  All rights reserved.
417680Spst *
517680Spst * Copyright (c) 2011 The FreeBSD Foundation
617680Spst * All rights reserved.
717680Spst * Portions of this software were developed by David Chisnall
817680Spst * under sponsorship from the FreeBSD Foundation.
917680Spst *
1017680Spst * This code is derived from software contributed to Berkeley by
1117680Spst * Chris Torek.
1217680Spst *
1317680Spst * Redistribution and use in source and binary forms, with or without
1417680Spst * modification, are permitted provided that the following conditions
1517680Spst * are met:
1617680Spst * 1. Redistributions of source code must retain the above copyright
1717680Spst *    notice, this list of conditions and the following disclaimer.
1817680Spst * 2. Redistributions in binary form must reproduce the above copyright
1917680Spst *    notice, this list of conditions and the following disclaimer in the
2017680Spst *    documentation and/or other materials provided with the distribution.
21214478Srpaulo * 4. Neither the name of the University nor the names of its contributors
2217680Spst *    may be used to endorse or promote products derived from this software
2317680Spst *    without specific prior written permission.
2417680Spst *
2517680Spst * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2617680Spst * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2717680Spst * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2817680Spst * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2917680Spst * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3017680Spst * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3175118Sfenner * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3275118Sfenner * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3375118Sfenner * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3475118Sfenner * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35147904Ssam * SUCH DAMAGE.
36147904Ssam */
37147904Ssam
38147904Ssam#if defined(LIBC_SCCS) && !defined(lint)
3975118Sfennerstatic char sccsid[] = "@(#)vfscanf.c	8.1 (Berkeley) 6/4/93";
4098527Sfenner#endif /* LIBC_SCCS and not lint */
4198527Sfenner#include <sys/cdefs.h>
4275118Sfenner__FBSDID("$FreeBSD: head/lib/libc/stdio/vfscanf.c 234836 2012-04-30 11:28:17Z dumbbell $");
4375118Sfenner
4475118Sfenner#include "namespace.h"
4598527Sfenner#include <ctype.h>
4698527Sfenner#include <inttypes.h>
4775118Sfenner#include <stdio.h>
4875118Sfenner#include <stdlib.h>
4975118Sfenner#include <stddef.h>
5098527Sfenner#include <stdarg.h>
5175118Sfenner#include <string.h>
5275118Sfenner#include <wchar.h>
5398527Sfenner#include <wctype.h>
5475118Sfenner#include "un-namespace.h"
5575118Sfenner
5698527Sfenner#include "collate.h"
5798527Sfenner#include "libc_private.h"
5898527Sfenner#include "local.h"
5998527Sfenner#include "xlocale_private.h"
60127675Sbms
61127675Sbms#ifndef NO_FLOATING_POINT
62127675Sbms#include <locale.h>
63127675Sbms#endif
6417680Spst
6517680Spst#define	BUF		513	/* Maximum length of numeric string. */
6617680Spst
6717680Spst/*
6817680Spst * Flags used during conversion.
6956896Sfenner */
7075118Sfenner#define	LONG		0x01	/* l: long or double */
71127675Sbms#define	LONGDBL		0x02	/* L: long double */
72127675Sbms#define	SHORT		0x04	/* h: short */
73251158Sdelphij#define	SUPPRESS	0x08	/* *: suppress assignment */
74251158Sdelphij#define	POINTER		0x10	/* p: void * (as hex) */
75251158Sdelphij#define	NOSKIP		0x20	/* [ or c: do not skip blanks */
76251158Sdelphij#define	LONGLONG	0x400	/* ll: long long (+ deprecated q: quad) */
7717680Spst#define	INTMAXT		0x800	/* j: intmax_t */
7826180Sfenner#define	PTRDIFFT	0x1000	/* t: ptrdiff_t */
7926180Sfenner#define	SIZET		0x2000	/* z: size_t */
8026180Sfenner#define	SHORTSHORT	0x4000	/* hh: char */
8126180Sfenner#define	UNSIGNED	0x8000	/* %[oupxX] conversions */
8226180Sfenner
8326180Sfenner/*
8426180Sfenner * The following are used in integral conversions only:
8526180Sfenner * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
8626180Sfenner */
8726180Sfenner#define	SIGNOK		0x40	/* +/- is (still) legal */
8826180Sfenner#define	NDIGITS		0x80	/* no digits detected */
8926180Sfenner#define	PFXOK		0x100	/* 0x prefix is (still) legal */
9026180Sfenner#define	NZDIGITS	0x200	/* no zero digits detected */
9126180Sfenner#define	HAVESIGN	0x10000	/* sign detected */
9226180Sfenner
9326180Sfenner/*
9426180Sfenner * Conversion types.
9526180Sfenner */
96172686Smlaier#define	CT_CHAR		0	/* %c conversion */
97172686Smlaier#define	CT_CCL		1	/* %[...] conversion */
98172686Smlaier#define	CT_STRING	2	/* %s conversion */
99172686Smlaier#define	CT_INT		3	/* %[dioupxX] conversion */
10017680Spst#define	CT_FLOAT	4	/* %[efgEFG] conversion */
10117680Spst
10217680Spststatic const u_char *__sccl(char *, const u_char *);
10317680Spst#ifndef NO_FLOATING_POINT
10498348Sfennerstatic int parsefloat(FILE *, char *, char *, locale_t);
10598348Sfenner#endif
10698348Sfenner
10798348Sfenner__weak_reference(__vfscanf, vfscanf);
10898348Sfenner
10998348Sfenner/*
11098348Sfenner * Conversion functions are passed a pointer to this object instead of
11198348Sfenner * a real parameter to indicate that the assignment-suppression (*)
11298348Sfenner * flag was specified.  We could use a NULL pointer to indicate this,
11398348Sfenner * but that would mask bugs in applications that call scanf() with a
11426180Sfenner * NULL pointer.
11526180Sfenner */
11626180Sfennerstatic const int suppress;
11726180Sfenner#define	SUPPRESS_PTR	((void *)&suppress)
11826180Sfenner
11926180Sfennerstatic const mbstate_t initial_mbs;
12026180Sfenner
12126180Sfenner/*
12217680Spst * The following conversion functions return the number of characters consumed,
12317680Spst * or -1 on input failure.  Character class conversion returns 0 on match
12417680Spst * failure.
12556896Sfenner */
12617680Spst
12717680Spststatic __inline int
12817680Spstconvert_char(FILE *fp, char * p, int width)
129147904Ssam{
130127675Sbms	int n;
13198527Sfenner
13298527Sfenner	if (p == SUPPRESS_PTR) {
13317680Spst		size_t sum = 0;
13498527Sfenner		for (;;) {
13517680Spst			if ((n = fp->_r) < width) {
13675118Sfenner				sum += n;
13775118Sfenner				width -= n;
13817680Spst				fp->_p += n;
13917680Spst				if (__srefill(fp)) {
14017680Spst					if (sum == 0)
14117680Spst						return (-1);
14217680Spst					break;
14375118Sfenner				}
144172686Smlaier			} else {
14575118Sfenner				sum += width;
146146778Ssam				fp->_r -= width;
14798527Sfenner				fp->_p += width;
14898527Sfenner				break;
14998527Sfenner			}
15098527Sfenner		}
15117680Spst		return (sum);
152190207Srpaulo	} else {
153190207Srpaulo		size_t r = __fread(p, 1, width, fp);
154190207Srpaulo
155190207Srpaulo		if (r == 0)
156190207Srpaulo			return (-1);
15717680Spst		return (r);
15817680Spst	}
15998527Sfenner}
16017680Spst
161127675Sbmsstatic __inline int
162162021Ssamconvert_wchar(FILE *fp, wchar_t *wcp, int width, locale_t locale)
163162021Ssam{
164162021Ssam	mbstate_t mbs;
165162021Ssam	int n, nread;
166146778Ssam	wint_t wi;
167162021Ssam
168127675Sbms	mbs = initial_mbs;
16926180Sfenner	n = 0;
17075118Sfenner	while (width-- != 0 &&
171214478Srpaulo	    (wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF) {
17226180Sfenner		if (wcp != SUPPRESS_PTR)
173127675Sbms			*wcp++ = (wchar_t)wi;
17417680Spst		n += nread;
175127675Sbms	}
176127675Sbms	if (n == 0)
177127675Sbms		return (-1);
178147904Ssam	return (n);
179127675Sbms}
18056896Sfenner
18198527Sfennerstatic __inline int
182127675Sbmsconvert_ccl(FILE *fp, char * p, int width, const char *ccltab)
18317680Spst{
18426180Sfenner	char *p0;
18526180Sfenner	int n;
186146778Ssam
187127675Sbms	if (p == SUPPRESS_PTR) {
188127675Sbms		n = 0;
189241221Sglebius		while (ccltab[*fp->_p]) {
190127675Sbms			n++, fp->_r--, fp->_p++;
191127675Sbms			if (--width == 0)
192127675Sbms				break;
193127675Sbms			if (fp->_r <= 0 && __srefill(fp)) {
194127675Sbms				if (n == 0)
195127675Sbms					return (-1);
196127675Sbms				break;
197172686Smlaier			}
198147904Ssam		}
199162021Ssam	} else {
200190207Srpaulo		p0 = p;
201127675Sbms		while (ccltab[*fp->_p]) {
202127675Sbms			fp->_r--;
20398527Sfenner			*p++ = *fp->_p++;
204127675Sbms			if (--width == 0)
205190207Srpaulo				break;
206190207Srpaulo			if (fp->_r <= 0 && __srefill(fp)) {
20726180Sfenner				if (p == p0)
208127675Sbms					return (-1);
20998527Sfenner				break;
21026180Sfenner			}
21175118Sfenner		}
212127675Sbms		n = p - p0;
21317680Spst		if (n == 0)
214127675Sbms			return (0);
215127675Sbms		*p = 0;
216127675Sbms	}
217127675Sbms	return (n);
21898527Sfenner}
21917680Spst
22017680Spststatic __inline int
221127675Sbmsconvert_wccl(FILE *fp, wchar_t *wcp, int width, const char *ccltab,
222251158Sdelphij    locale_t locale)
22317680Spst{
224127675Sbms	mbstate_t mbs;
22517680Spst	wint_t wi;
226214478Srpaulo	int n, nread;
22756896Sfenner
22856896Sfenner	mbs = initial_mbs;
229127675Sbms	n = 0;
230127675Sbms	if (wcp == SUPPRESS_PTR) {
231190207Srpaulo		while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
232235530Sdelphij		    width-- != 0 && ccltab[wctob(wi)])
233146778Ssam			n += nread;
234146778Ssam		if (wi != WEOF)
235190207Srpaulo			__ungetwc(wi, fp, __get_locale());
236190207Srpaulo	} else {
237146778Ssam		while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
23856896Sfenner		    width-- != 0 && ccltab[wctob(wi)]) {
239214478Srpaulo			*wcp++ = (wchar_t)wi;
240127675Sbms			n += nread;
241127675Sbms		}
242127675Sbms		if (wi != WEOF)
243127675Sbms			__ungetwc(wi, fp, __get_locale());
244127675Sbms		if (n == 0)
245127675Sbms			return (0);
246127675Sbms		*wcp = 0;
247146778Ssam	}
248127675Sbms	return (n);
249190207Srpaulo}
250127675Sbms
25117680Spststatic __inline int
252127675Sbmsconvert_string(FILE *fp, char * p, int width)
253127675Sbms{
254127675Sbms	char *p0;
255127675Sbms	int n;
256127675Sbms
257127675Sbms	if (p == SUPPRESS_PTR) {
258162021Ssam		n = 0;
259146778Ssam		while (!isspace(*fp->_p)) {
260146778Ssam			n++, fp->_r--, fp->_p++;
261147904Ssam			if (--width == 0)
262146778Ssam				break;
263146778Ssam			if (fp->_r <= 0 && __srefill(fp))
264147904Ssam				break;
265147904Ssam		}
266147904Ssam	} else {
267147904Ssam		p0 = p;
268147904Ssam		while (!isspace(*fp->_p)) {
269147904Ssam			fp->_r--;
270162021Ssam			*p++ = *fp->_p++;
271162021Ssam			if (--width == 0)
272162021Ssam				break;
273162021Ssam			if (fp->_r <= 0 && __srefill(fp))
274127675Sbms				break;
27517680Spst		}
27617680Spst		*p = 0;
277146778Ssam		n = p - p0;
27875118Sfenner	}
27917680Spst	return (n);
280127675Sbms}
281190207Srpaulo
28275118Sfennerstatic __inline int
283190207Srpauloconvert_wstring(FILE *fp, wchar_t *wcp, int width, locale_t locale)
28417680Spst{
285127675Sbms	mbstate_t mbs;
286127675Sbms	wint_t wi;
28756896Sfenner	int n, nread;
28898527Sfenner
28998527Sfenner	mbs = initial_mbs;
29056896Sfenner	n = 0;
29198527Sfenner	if (wcp == SUPPRESS_PTR) {
29298527Sfenner		while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
293190207Srpaulo		    width-- != 0 && !iswspace(wi))
29456896Sfenner			n += nread;
295146778Ssam		if (wi != WEOF)
29656896Sfenner			__ungetwc(wi, fp, __get_locale());
29756896Sfenner	} else {
29898527Sfenner		while ((wi = __fgetwc_mbs(fp, &mbs, &nread, locale)) != WEOF &&
299235530Sdelphij		    width-- != 0 && !iswspace(wi)) {
300162021Ssam			*wcp++ = (wchar_t)wi;
301190207Srpaulo			n += nread;
302190207Srpaulo		}
303190207Srpaulo		if (wi != WEOF)
304147904Ssam			__ungetwc(wi, fp, __get_locale());
305127675Sbms		*wcp = '\0';
306190207Srpaulo	}
30798527Sfenner	return (n);
30875118Sfenner}
30998527Sfenner
310127675Sbms/*
311162021Ssam * Read an integer, storing it in buf.  The only relevant bit in the
31298527Sfenner * flags argument is PFXOK.
313214478Srpaulo *
31498527Sfenner * Return 0 on a match failure, and the number of characters read
315127675Sbms * otherwise.
31698527Sfenner */
317251158Sdelphijstatic __inline int
31898527Sfennerparseint(FILE *fp, char * __restrict buf, int width, int base, int flags)
319127675Sbms{
320146778Ssam	/* `basefix' is used to avoid `if' tests */
321146778Ssam	static const short basefix[17] =
322190207Srpaulo		{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
323214478Srpaulo	char *p;
324214478Srpaulo	int c;
325251158Sdelphij
326251161Sdelphij	flags |= SIGNOK | NDIGITS | NZDIGITS;
32756896Sfenner	for (p = buf; width; width--) {
328235530Sdelphij		c = *fp->_p;
32956896Sfenner		/*
33056896Sfenner		 * Switch on the character; `goto ok' if we accept it
33156896Sfenner		 * as a part of number.
33256896Sfenner		 */
33356896Sfenner		switch (c) {
334127675Sbms
33598527Sfenner		/*
33656896Sfenner		 * The digit 0 is always legal, but is special.  For
33756896Sfenner		 * %i conversions, if no digits (zero or nonzero) have
338127675Sbms		 * been scanned (only signs), we will have base==0.
339235530Sdelphij		 * In that case, we should set it to 8 and enable 0x
340214478Srpaulo		 * prefixing.  Also, if we have not scanned zero
34156896Sfenner		 * digits before this, do not turn off prefixing
342235530Sdelphij		 * (someone else will turn it off if we have scanned
343235530Sdelphij		 * any nonzero digits).
344235530Sdelphij		 */
345235530Sdelphij		case '0':
346235530Sdelphij			if (base == 0) {
347235530Sdelphij				base = 8;
348127675Sbms				flags |= PFXOK;
34998527Sfenner			}
35098527Sfenner			if (flags & NZDIGITS)
35198527Sfenner				flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
35298527Sfenner			else
353190207Srpaulo				flags &= ~(SIGNOK|PFXOK|NDIGITS);
354146778Ssam			goto ok;
35598527Sfenner
356146778Ssam		/* 1 through 7 always legal */
357146778Ssam		case '1': case '2': case '3':
358146778Ssam		case '4': case '5': case '6': case '7':
359146778Ssam			base = basefix[base];
360146778Ssam			flags &= ~(SIGNOK | PFXOK | NDIGITS);
361190207Srpaulo			goto ok;
362147904Ssam
363146778Ssam		/* digits 8 and 9 ok iff decimal or hex */
364214478Srpaulo		case '8': case '9':
365146778Ssam			base = basefix[base];
366146778Ssam			if (base <= 8)
367235530Sdelphij				break;	/* not legal here */
368190207Srpaulo			flags &= ~(SIGNOK | PFXOK | NDIGITS);
369146778Ssam			goto ok;
370146778Ssam
371146778Ssam		/* letters ok iff hex */
372146778Ssam		case 'A': case 'B': case 'C':
373146778Ssam		case 'D': case 'E': case 'F':
374146778Ssam		case 'a': case 'b': case 'c':
375146778Ssam		case 'd': case 'e': case 'f':
376146778Ssam			/* no need to fix base here */
377146778Ssam			if (base <= 10)
378146778Ssam				break;	/* not legal here */
379146778Ssam			flags &= ~(SIGNOK | PFXOK | NDIGITS);
380146778Ssam			goto ok;
381146778Ssam
382146778Ssam		/* sign ok only as first character */
383146778Ssam		case '+': case '-':
384190207Srpaulo			if (flags & SIGNOK) {
385146778Ssam				flags &= ~SIGNOK;
386190207Srpaulo				flags |= HAVESIGN;
387190207Srpaulo				goto ok;
388162021Ssam			}
389146778Ssam			break;
390214478Srpaulo
391146778Ssam		/*
392146778Ssam		 * x ok iff flag still set & 2nd char (or 3rd char if
393146778Ssam		 * we have a sign).
394190207Srpaulo		 */
395190207Srpaulo		case 'x': case 'X':
396235530Sdelphij			if (flags & PFXOK && p ==
397146778Ssam			    buf + 1 + !!(flags & HAVESIGN)) {
398146778Ssam				base = 16;	/* if %i */
399146778Ssam				flags &= ~PFXOK;
400190207Srpaulo				goto ok;
401			}
402			break;
403		}
404
405		/*
406		 * If we got here, c is not a legal character for a
407		 * number.  Stop accumulating digits.
408		 */
409		break;
410	ok:
411		/*
412		 * c is legal: store it and look at the next.
413		 */
414		*p++ = c;
415		if (--fp->_r > 0)
416			fp->_p++;
417		else if (__srefill(fp))
418			break;		/* EOF */
419	}
420	/*
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'.
424	 */
425	if (flags & NDIGITS) {
426		if (p > buf)
427			(void) __ungetc(*(u_char *)--p, fp);
428		return (0);
429	}
430	c = ((u_char *)p)[-1];
431	if (c == 'x' || c == 'X') {
432		--p;
433		(void) __ungetc(c, fp);
434	}
435	return (p - buf);
436}
437
438/*
439 * __vfscanf - MT-safe version
440 */
441int
442__vfscanf(FILE *fp, char const *fmt0, va_list ap)
443{
444	int ret;
445
446	FLOCKFILE(fp);
447	ret = __svfscanf(fp, __get_locale(), fmt0, ap);
448	FUNLOCKFILE(fp);
449	return (ret);
450}
451int
452vfscanf_l(FILE *fp, locale_t locale, char const *fmt0, va_list ap)
453{
454	int ret;
455	FIX_LOCALE(locale);
456
457	FLOCKFILE(fp);
458	ret = __svfscanf(fp, locale, fmt0, ap);
459	FUNLOCKFILE(fp);
460	return (ret);
461}
462
463/*
464 * __svfscanf - non-MT-safe version of __vfscanf
465 */
466int
467__svfscanf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
468{
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 */
481
482	ORIENT(fp, -1);
483
484	nassigned = 0;
485	nconversions = 0;
486	nread = 0;
487	for (;;) {
488		c = *fmt++;
489		if (c == 0)
490			return (nassigned);
491		if (isspace(c)) {
492			while ((fp->_r > 0 || __srefill(fp) == 0) && isspace(*fp->_p))
493				nread++, fp->_r--, fp->_p++;
494			continue;
495		}
496		if (c != '%')
497			goto literal;
498		width = 0;
499		flags = 0;
500		/*
501		 * switch on the format.  continue if done;
502		 * break once format type is derived.
503		 */
504again:		c = *fmt++;
505		switch (c) {
506		case '%':
507literal:
508			if (fp->_r <= 0 && __srefill(fp))
509				goto input_failure;
510			if (*fp->_p != c)
511				goto match_failure;
512			fp->_r--, fp->_p++;
513			nread++;
514			continue;
515
516		case '*':
517			flags |= SUPPRESS;
518			goto again;
519		case 'j':
520			flags |= INTMAXT;
521			goto again;
522		case 'l':
523			if (flags & LONG) {
524				flags &= ~LONG;
525				flags |= LONGLONG;
526			} else
527				flags |= LONG;
528			goto again;
529		case 'q':
530			flags |= LONGLONG;	/* not quite */
531			goto again;
532		case 't':
533			flags |= PTRDIFFT;
534			goto again;
535		case 'z':
536			flags |= SIZET;
537			goto again;
538		case 'L':
539			flags |= LONGDBL;
540			goto again;
541		case 'h':
542			if (flags & SHORT) {
543				flags &= ~SHORT;
544				flags |= SHORTSHORT;
545			} else
546				flags |= SHORT;
547			goto again;
548
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';
552			goto again;
553
554		/*
555		 * Conversions.
556		 */
557		case 'd':
558			c = CT_INT;
559			base = 10;
560			break;
561
562		case 'i':
563			c = CT_INT;
564			base = 0;
565			break;
566
567		case 'o':
568			c = CT_INT;
569			flags |= UNSIGNED;
570			base = 8;
571			break;
572
573		case 'u':
574			c = CT_INT;
575			flags |= UNSIGNED;
576			base = 10;
577			break;
578
579		case 'X':
580		case 'x':
581			flags |= PFXOK;	/* enable 0x prefixing */
582			c = CT_INT;
583			flags |= UNSIGNED;
584			base = 16;
585			break;
586
587#ifndef NO_FLOATING_POINT
588		case 'A': case 'E': case 'F': case 'G':
589		case 'a': case 'e': case 'f': case 'g':
590			c = CT_FLOAT;
591			break;
592#endif
593
594		case 'S':
595			flags |= LONG;
596			/* FALLTHROUGH */
597		case 's':
598			c = CT_STRING;
599			break;
600
601		case '[':
602			fmt = __sccl(ccltab, fmt);
603			flags |= NOSKIP;
604			c = CT_CCL;
605			break;
606
607		case 'C':
608			flags |= LONG;
609			/* FALLTHROUGH */
610		case 'c':
611			flags |= NOSKIP;
612			c = CT_CHAR;
613			break;
614
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) */
619			base = 16;
620			break;
621
622		case 'n':
623			if (flags & SUPPRESS)	/* ??? */
624				continue;
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;
639			else
640				*va_arg(ap, int *) = nread;
641			continue;
642
643		default:
644			goto match_failure;
645
646		/*
647		 * Disgusting backwards compatibility hack.	XXX
648		 */
649		case '\0':	/* compat */
650			return (EOF);
651		}
652
653		/*
654		 * We have a conversion that requires input.
655		 */
656		if (fp->_r <= 0 && __srefill(fp))
657			goto input_failure;
658
659		/*
660		 * Consume leading white space, except for formats
661		 * that suppress this.
662		 */
663		if ((flags & NOSKIP) == 0) {
664			while (isspace(*fp->_p)) {
665				nread++;
666				if (--fp->_r > 0)
667					fp->_p++;
668				else if (__srefill(fp))
669					goto input_failure;
670			}
671			/*
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.
675			 */
676		}
677
678		/*
679		 * Do the conversion.
680		 */
681		switch (c) {
682
683		case CT_CHAR:
684			/* scan arbitrary characters (sets NOSKIP) */
685			if (width == 0)
686				width = 1;
687			if (flags & LONG) {
688				nr = convert_wchar(fp, GETARG(wchar_t *),
689				    width, locale);
690			} else {
691				nr = convert_char(fp, GETARG(char *), width);
692			}
693			if (nr < 0)
694				goto input_failure;
695			break;
696
697		case CT_CCL:
698			/* scan a (nonempty) character class (sets NOSKIP) */
699			if (width == 0)
700				width = (size_t)~0;	/* `infinity' */
701			if (flags & LONG) {
702				nr = convert_wccl(fp, GETARG(wchar_t *), width,
703				    ccltab, locale);
704			} else {
705				nr = convert_ccl(fp, GETARG(char *), width,
706				    ccltab);
707			}
708			if (nr <= 0) {
709				if (nr < 0)
710					goto input_failure;
711				else /* nr == 0 */
712					goto match_failure;
713			}
714			break;
715
716		case CT_STRING:
717			/* like CCL, but zero-length string OK, & no NOSKIP */
718			if (width == 0)
719				width = (size_t)~0;
720			if (flags & LONG) {
721				nr = convert_wstring(fp, GETARG(wchar_t *),
722				    width, locale);
723			} else {
724				nr = convert_string(fp, GETARG(char *), width);
725			}
726			if (nr < 0)
727				goto input_failure;
728			break;
729
730		case CT_INT:
731			/* scan an integer as if by the conversion function */
732#ifdef hardway
733			if (width == 0 || width > sizeof(buf) - 1)
734				width = sizeof(buf) - 1;
735#else
736			/* size_t is unsigned, hence this optimisation */
737			if (--width > sizeof(buf) - 2)
738				width = sizeof(buf) - 2;
739			width++;
740#endif
741			nr = parseint(fp, buf, width, base, flags);
742			if (nr == 0)
743				goto match_failure;
744			if ((flags & SUPPRESS) == 0) {
745				uintmax_t res;
746
747				buf[nr] = '\0';
748				if ((flags & UNSIGNED) == 0)
749				    res = strtoimax_l(buf, (char **)NULL, base, locale);
750				else
751				    res = strtoumax_l(buf, (char **)NULL, base, locale);
752				if (flags & POINTER)
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;
769				else
770					*va_arg(ap, int *) = res;
771			}
772			break;
773
774#ifndef NO_FLOATING_POINT
775		case CT_FLOAT:
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);
780			if (nr == 0)
781				goto match_failure;
782			if ((flags & SUPPRESS) == 0) {
783				if (flags & LONGDBL) {
784					long double res = strtold_l(buf, NULL,
785					    locale);
786					*va_arg(ap, long double *) = res;
787				} else if (flags & LONG) {
788					double res = strtod_l(buf, NULL,
789					    locale);
790					*va_arg(ap, double *) = res;
791				} else {
792					float res = strtof_l(buf, NULL, locale);
793					*va_arg(ap, float *) = res;
794				}
795			}
796			break;
797#endif /* !NO_FLOATING_POINT */
798		}
799		if (!(flags & SUPPRESS))
800			nassigned++;
801		nread += nr;
802		nconversions++;
803	}
804input_failure:
805	return (nconversions != 0 ? nassigned : EOF);
806match_failure:
807	return (nassigned);
808}
809
810/*
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.
815 */
816static const u_char *
817__sccl(tab, fmt)
818	char *tab;
819	const u_char *fmt;
820{
821	int c, n, v, i;
822	struct xlocale_collate *table =
823		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
824
825	/* first `clear' the whole table */
826	c = *fmt++;		/* first char hat => negated scanset */
827	if (c == '^') {
828		v = 1;		/* default => accept */
829		c = *fmt++;	/* get new first char */
830	} else
831		v = 0;		/* default => reject */
832
833	/* XXX: Will not work if sizeof(tab*) > sizeof(char) */
834	(void) memset(tab, v, 256);
835
836	if (c == 0)
837		return (fmt - 1);/* format ended before closing ] */
838
839	/*
840	 * Now set the entries corresponding to the actual scanset
841	 * to the opposite of the above.
842	 *
843	 * The first character may be ']' (or '-') without being special;
844	 * the last character may be '-'.
845	 */
846	v = 1 - v;
847	for (;;) {
848		tab[c] = v;		/* take character c */
849doswitch:
850		n = *fmt++;		/* and examine the next */
851		switch (n) {
852
853		case 0:			/* format ended too soon */
854			return (fmt - 1);
855
856		case '-':
857			/*
858			 * A scanset of the form
859			 *	[01+-]
860			 * is defined as `the digit 0, the digit 1,
861			 * the character +, the character -', but
862			 * the effect of a scanset such as
863			 *	[a-zA-Z0-9]
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'.
868			 *
869			 * For compatibility, the `-' is not considerd
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).
874			 */
875			n = *fmt;
876			if (n == ']'
877			    || (table->__collate_load_error ? n < c :
878				__collate_range_cmp (table, n, c) < 0
879			       )
880			   ) {
881				c = '-';
882				break;	/* resume the for(;;) */
883			}
884			fmt++;
885			/* fill in the range */
886			if (table->__collate_load_error) {
887				do {
888					tab[++c] = v;
889				} while (c < n);
890			} else {
891				for (i = 0; i < 256; i ++)
892					if (   __collate_range_cmp (table, c, i) < 0
893					    && __collate_range_cmp (table, i, n) <= 0
894					   )
895						tab[i] = v;
896			}
897#if 1	/* XXX another disgusting compatibility hack */
898			c = n;
899			/*
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....
903			 */
904			goto doswitch;
905#else
906			c = *fmt++;
907			if (c == 0)
908				return (fmt - 1);
909			if (c == ']')
910				return (fmt);
911#endif
912			break;
913
914		case ']':		/* end of scanset */
915			return (fmt);
916
917		default:		/* just another character */
918			c = n;
919			break;
920		}
921	}
922	/* NOTREACHED */
923}
924
925#ifndef NO_FLOATING_POINT
926static int
927parsefloat(FILE *fp, char *buf, char *end, locale_t locale)
928{
929	char *commit, *p;
930	int infnanpos = 0, decptpos = 0;
931	enum {
932		S_START, S_GOTSIGN, S_INF, S_NAN, S_DONE, S_MAYBEHEX,
933		S_DIGITS, S_DECPT, S_FRAC, S_EXP, S_EXPDIGITS
934	} state = S_START;
935	unsigned char c;
936	const char *decpt = localeconv_l(locale)->decimal_point;
937	_Bool gotmantdig = 0, ishex = 0;
938
939	/*
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(...)".
947	 */
948	commit = buf - 1;
949	for (p = buf; p < end; ) {
950		c = *fp->_p;
951reswitch:
952		switch (state) {
953		case S_START:
954			state = S_GOTSIGN;
955			if (c == '-' || c == '+')
956				break;
957			else
958				goto reswitch;
959		case S_GOTSIGN:
960			switch (c) {
961			case '0':
962				state = S_MAYBEHEX;
963				commit = p;
964				break;
965			case 'I':
966			case 'i':
967				state = S_INF;
968				break;
969			case 'N':
970			case 'n':
971				state = S_NAN;
972				break;
973			default:
974				state = S_DIGITS;
975				goto reswitch;
976			}
977			break;
978		case S_INF:
979			if (infnanpos > 6 ||
980			    (c != "nfinity"[infnanpos] &&
981			     c != "NFINITY"[infnanpos]))
982				goto parsedone;
983			if (infnanpos == 1 || infnanpos == 6)
984				commit = p;	/* inf or infinity */
985			infnanpos++;
986			break;
987		case S_NAN:
988			switch (infnanpos) {
989			case 0:
990				if (c != 'A' && c != 'a')
991					goto parsedone;
992				break;
993			case 1:
994				if (c != 'N' && c != 'n')
995					goto parsedone;
996				else
997					commit = p;
998				break;
999			case 2:
1000				if (c != '(')
1001					goto parsedone;
1002				break;
1003			default:
1004				if (c == ')') {
1005					commit = p;
1006					state = S_DONE;
1007				} else if (!isalnum(c) && c != '_')
1008					goto parsedone;
1009				break;
1010			}
1011			infnanpos++;
1012			break;
1013		case S_DONE:
1014			goto parsedone;
1015		case S_MAYBEHEX:
1016			state = S_DIGITS;
1017			if (c == 'X' || c == 'x') {
1018				ishex = 1;
1019				break;
1020			} else {	/* we saw a '0', but no 'x' */
1021				gotmantdig = 1;
1022				goto reswitch;
1023			}
1024		case S_DIGITS:
1025			if ((ishex && isxdigit(c)) || isdigit(c)) {
1026				gotmantdig = 1;
1027				commit = p;
1028				break;
1029			} else {
1030				state = S_DECPT;
1031				goto reswitch;
1032			}
1033		case S_DECPT:
1034			if (c == decpt[decptpos]) {
1035				if (decpt[++decptpos] == '\0') {
1036					/* We read the complete decpt seq. */
1037					state = S_FRAC;
1038					if (gotmantdig)
1039						commit = p;
1040				}
1041				break;
1042			} else if (!decptpos) {
1043				/* We didn't read any decpt characters. */
1044				state = S_FRAC;
1045				goto reswitch;
1046			} else {
1047				/*
1048				 * We read part of a multibyte decimal point,
1049				 * but the rest is invalid, so bail.
1050				 */
1051				goto parsedone;
1052			}
1053		case S_FRAC:
1054			if (((c == 'E' || c == 'e') && !ishex) ||
1055			    ((c == 'P' || c == 'p') && ishex)) {
1056				if (!gotmantdig)
1057					goto parsedone;
1058				else
1059					state = S_EXP;
1060			} else if ((ishex && isxdigit(c)) || isdigit(c)) {
1061				commit = p;
1062				gotmantdig = 1;
1063			} else
1064				goto parsedone;
1065			break;
1066		case S_EXP:
1067			state = S_EXPDIGITS;
1068			if (c == '-' || c == '+')
1069				break;
1070			else
1071				goto reswitch;
1072		case S_EXPDIGITS:
1073			if (isdigit(c))
1074				commit = p;
1075			else
1076				goto parsedone;
1077			break;
1078		default:
1079			abort();
1080		}
1081		*p++ = c;
1082		if (--fp->_r > 0)
1083			fp->_p++;
1084		else if (__srefill(fp))
1085			break;	/* EOF */
1086	}
1087
1088parsedone:
1089	while (commit < --p)
1090		__ungetc(*(u_char *)p, fp);
1091	*++commit = '\0';
1092	return (commit - buf);
1093}
1094#endif
1095