1 // SPDX-License-Identifier: BSD-3-Clause
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Copyright (c) 2011 The FreeBSD Foundation
10 * All rights reserved.
11 * Portions of this software were developed by David Chisnall
12 * under sponsorship from the FreeBSD Foundation.
18 #if !defined HAVE_LIBC
21 #include <linux/kernel.h>
22 #include <linux/ctype.h>
24 #include <linux/string.h>
26 #define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
29 * struct str_info - Input string parameters
30 * @neg: negative number or not
33 * @any: set any if any `digits' consumed; make it negative to indicate
35 * @acc: accumulated value
43 * str_to_int_convert() - Write string data to structure
44 * @nptr: pointer to string
45 * @base: number's base
46 * @unsign: describes what integer is expected
50 * Ignores `locale' stuff. Assumes that the upper and lower case
51 * alphabets and digits are each contiguous.
53 * Return: struct str_info *, which contains string data to future process
55 static struct str_info *
56 str_to_int_convert(const char **nptr, int base, unsigned int unsign)
58 const char *s = *nptr;
64 struct str_info *info;
67 * Skip white space and pick up leading +/- sign if any.
68 * If base is 0, allow 0x for hex and 0 for octal, else
69 * assume decimal; if base is already 16, allow 0x.
71 info = (struct str_info *)malloc(sizeof(struct str_info));
86 if ((base == 0 || base == 16) &&
87 c == '0' && (*s == 'x' || *s == 'X')) {
93 base = c == '0' ? 8 : 10;
96 * Compute the cutoff value between legal numbers and illegal
97 * numbers. That is the largest legal value, divided by the
98 * base. An input number that is greater than this value, if
99 * followed by a legal input character, is too big. One that
100 * is equal to this value may be valid or not; the limit
101 * between valid and invalid numbers is then based on the last
102 * digit. For instance, if the range for quads is
103 * [-9223372036854775808..9223372036854775807] and the input base
104 * is 10, cutoff will be set to 922337203685477580 and cutlim to
105 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
106 * accumulated a value > 922337203685477580, or equal but the
107 * next digit is > 7 (or 8), the number is too big, and we will
108 * return a range error.
110 * Set any if any `digits' consumed; make it negative to indicate
113 qbase = (unsigned int)base;
116 cutoff = neg ? (u64)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX : LLONG_MAX;
117 cutlim = cutoff % qbase;
120 cutoff = (u64)ULLONG_MAX / qbase;
121 cutlim = (u64)ULLONG_MAX % qbase;
124 for (acc = 0, any = 0;; c = *s++) {
130 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
135 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) {
154 * strtoq() - Convert a string to a quad integer
155 * @nptr: pointer to string
156 * @endptr: pointer to number's end in the string
157 * @base: number's base
159 * Return: s64 quad integer number converted from input string
162 strtoq(const char *nptr, char **endptr, int base)
164 const char *s = nptr;
167 struct str_info *info;
169 info = str_to_int_convert(&s, base, unsign);
176 acc = info->neg ? LLONG_MIN : LLONG_MAX;
180 *endptr = __DECONST(char *, info->any ? s - 1 : nptr);
188 * strtouq() - Convert a string to an unsigned quad integer
189 * @nptr: pointer to string
190 * @endptr: pointer to number's end in the string
191 * @base: number's base
193 * Return: s64 unsigned quad integer number converted from
197 strtouq(const char *nptr, char **endptr, int base)
199 const char *s = nptr;
202 struct str_info *info;
204 info = str_to_int_convert(&s, base, unsign);
215 *endptr = __DECONST(char *, info->any ? s - 1 : nptr);
223 * __sccl() - Fill in the given table from the scanset at the given format
225 * @tab: table to fill in
226 * @fmt: format of buffer
228 * The table has a 1 wherever characters should be considered part of the
231 * Return: pointer to the character past the closing `]'
233 static const u_char *
234 __sccl(char *tab, const u_char *fmt)
238 /* first `clear' the whole table */
239 c = *fmt++; /* first char hat => negated scanset */
241 v = 1; /* default => accept */
242 c = *fmt++; /* get new first char */
244 v = 0; /* default => reject */
247 /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
248 for (n = 0; n < 256; n++)
249 tab[n] = v; /* memset(tab, v, 256) */
252 return (fmt - 1);/* format ended before closing ] */
255 * Now set the entries corresponding to the actual scanset
256 * to the opposite of the above.
258 * The first character may be ']' (or '-') without being special;
259 * the last character may be '-'.
263 tab[c] = v; /* take character c */
265 n = *fmt++; /* and examine the next */
267 case 0: /* format ended too soon */
272 * A scanset of the form
274 * is defined as `the digit 0, the digit 1,
275 * the character +, the character -', but
276 * the effect of a scanset such as
278 * is implementation defined. The V7 Unix
279 * scanf treats `a-z' as `the letters a through
280 * z', but treats `a-a' as `the letter a, the
281 * character -, and the letter a'.
283 * For compatibility, the `-' is not considerd
284 * to define a range if the character following
285 * it is either a close bracket (required by ANSI)
286 * or is not numerically greater than the character
287 * we just stored in the table (c).
290 if (n == ']' || n < c) {
292 break; /* resume the for(;;) */
295 /* fill in the range */
301 * Alas, the V7 Unix scanf also treats formats
302 * such as [a-c-e] as `the letters a through e'.
303 * This too is permitted by the standard....
308 case ']': /* end of scanset */
311 default: /* just another character */
320 * vsscanf - Unformat a buffer into a list of arguments
322 * @fmt: format of buffer
325 #define BUF 32 /* Maximum length of numeric string. */
328 * Flags used during conversion.
330 #define LONG 0x01 /* l: long or double */
331 #define SHORT 0x04 /* h: short */
332 #define SUPPRESS 0x08 /* suppress assignment */
333 #define POINTER 0x10 /* weird %p pointer (`fake hex') */
334 #define NOSKIP 0x20 /* do not skip blanks */
336 #define SHORTSHORT 0x4000 /** hh: char */
339 * The following are used in numeric conversions only:
340 * SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point;
341 * SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral.
343 #define SIGNOK 0x40 /* +/- is (still) legal */
344 #define NDIGITS 0x80 /* no digits detected */
346 #define DPTOK 0x100 /* (float) decimal point is still legal */
347 #define EXPOK 0x200 /* (float) exponent (e+3, etc) still legal */
349 #define PFXOK 0x100 /* 0x prefix is (still) legal */
350 #define NZDIGITS 0x200 /* no zero digits detected */
355 #define CT_CHAR 0 /* %c conversion */
356 #define CT_CCL 1 /* %[...] conversion */
357 #define CT_STRING 2 /* %s conversion */
358 #define CT_INT 3 /* integer, i.e., strtoq or strtouq */
359 typedef u64 (*ccfntype)(const char *, char **, int);
362 vsscanf(const char *inp, char const *fmt0, va_list ap)
365 const u_char *fmt = (const u_char *)fmt0;
366 int c; /* character from format, or conversion */
367 size_t width; /* field width, or 0 */
368 char *p; /* points into all kinds of strings */
369 int n; /* handy integer */
370 int flags; /* flags as defined above */
371 char *p0; /* saves original value of p when necessary */
372 int nassigned; /* number of fields assigned */
373 int nconversions; /* number of conversions */
374 int nread; /* number of characters consumed from fp */
375 int base; /* base argument to strtoq/strtouq */
376 ccfntype ccfn; /* conversion function (strtoq/strtouq) */
377 char ccltab[256]; /* character class table for %[...] */
378 char buf[BUF]; /* buffer for numeric conversions */
380 /* `basefix' is used to avoid `if' tests in the integer scanner */
381 static short basefix[17] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
382 12, 13, 14, 15, 16 };
389 base = 0; /* XXX just to keep gcc happy */
390 ccfn = NULL; /* XXX just to keep gcc happy */
396 while (inr > 0 && isspace(*inp))
397 nread++, inr--, inp++;
405 * switch on the format. continue if done;
406 * break once format type is derived.
443 case '0': case '1': case '2': case '3': case '4':
444 case '5': case '6': case '7': case '8': case '9':
445 width = width * 10 + c - '0';
454 ccfn = (ccfntype)strtoq;
460 ccfn = (ccfntype)strtoq;
477 flags |= PFXOK; /* enable 0x prefixing */
488 fmt = __sccl(ccltab, fmt);
498 case 'p': /* pointer format is like hex */
499 flags |= POINTER | PFXOK;
507 if (flags & SUPPRESS) /* ??? */
509 if (flags & SHORTSHORT)
510 *va_arg(ap, char *) = nread;
511 else if (flags & SHORT)
512 *va_arg(ap, short *) = nread;
513 else if (flags & LONG)
514 *va_arg(ap, long *) = nread;
515 else if (flags & QUAD)
516 *va_arg(ap, s64 *) = nread;
518 *va_arg(ap, int *) = nread;
523 * We have a conversion that requires input.
529 * Consume leading white space, except for formats
530 * that suppress this.
532 if ((flags & NOSKIP) == 0) {
533 while (isspace(*inp)) {
541 * Note that there is at least one character in
542 * the buffer, so conversions that do not set NOSKIP
543 * can no longer result in an input failure.
552 /* scan arbitrary characters (sets NOSKIP) */
555 if (flags & SUPPRESS) {
558 if ((n = inr) < width) {
571 memcpy(va_arg(ap, char *), inp, width);
581 /* scan a (nonempty) character class (sets NOSKIP) */
583 width = (size_t)~0; /* `infinity' */
584 /* take only those things in the class */
585 if (flags & SUPPRESS) {
587 while (ccltab[(unsigned char)*inp]) {
600 p = va_arg(ap, char *);
602 while (ccltab[(unsigned char)*inp]) {
624 /* like CCL, but zero-length string OK, & no NOSKIP */
627 if (flags & SUPPRESS) {
629 while (!isspace(*inp)) {
638 p = va_arg(ap, char *);
640 while (!isspace(*inp)) {
656 /* scan an integer as if by strtoq/strtouq */
658 if (width == 0 || width > sizeof(buf) - 1)
659 width = sizeof(buf) - 1;
661 /* size_t is unsigned, hence this optimisation */
662 if (--width > sizeof(buf) - 2)
663 width = sizeof(buf) - 2;
666 flags |= SIGNOK | NDIGITS | NZDIGITS;
667 for (p = buf; width; width--) {
670 * Switch on the character; `goto ok'
671 * if we accept it as a part of number.
675 * The digit 0 is always legal, but is
676 * special. For %i conversions, if no
677 * digits (zero or nonzero) have been
678 * scanned (only signs), we will have
679 * base==0. In that case, we should set
680 * it to 8 and enable 0x prefixing.
681 * Also, if we have not scanned zero digits
682 * before this, do not turn off prefixing
683 * (someone else will turn it off if we
684 * have scanned any nonzero digits).
691 if (flags & NZDIGITS)
692 flags &= ~(SIGNOK | NZDIGITS | NDIGITS);
694 flags &= ~(SIGNOK | PFXOK | NDIGITS);
697 /* 1 through 7 always legal */
698 case '1': case '2': case '3':
699 case '4': case '5': case '6': case '7':
700 base = basefix[base];
701 flags &= ~(SIGNOK | PFXOK | NDIGITS);
704 /* digits 8 and 9 ok iff decimal or hex */
706 base = basefix[base];
708 break; /* not legal here */
709 flags &= ~(SIGNOK | PFXOK | NDIGITS);
712 /* letters ok iff hex */
713 case 'A': case 'B': case 'C':
714 case 'D': case 'E': case 'F':
715 case 'a': case 'b': case 'c':
716 case 'd': case 'e': case 'f':
717 /* no need to fix base here */
719 break; /* not legal here */
720 flags &= ~(SIGNOK | PFXOK | NDIGITS);
723 /* sign ok only as first character */
725 if (flags & SIGNOK) {
731 /* x ok iff flag still set & 2nd char */
733 if (flags & PFXOK && p == buf + 1) {
734 base = 16; /* if %i */
742 * If we got here, c is not a legal character
743 * for a number. Stop accumulating digits.
748 * c is legal: store it and look at the next.
754 break; /* end of input */
757 * If we had only a sign, it is no good; push
758 * back the sign. If the number ends in `x',
759 * it was [sign] '' 'x', so push back the x
760 * and treat it as [sign] ''.
762 if (flags & NDIGITS) {
769 c = ((u_char *)p)[-1];
770 if (c == 'x' || c == 'X') {
775 if ((flags & SUPPRESS) == 0) {
779 res = (*ccfn)(buf, (char **)NULL, base);
781 *va_arg(ap, void **) =
782 (void *)(uintptr_t)res;
783 else if (flags & SHORTSHORT)
784 *va_arg(ap, char *) = res;
785 else if (flags & SHORT)
786 *va_arg(ap, short *) = res;
787 else if (flags & LONG)
788 *va_arg(ap, long *) = res;
789 else if (flags & QUAD)
790 *va_arg(ap, s64 *) = res;
792 *va_arg(ap, int *) = res;
801 return (nconversions != 0 ? nassigned : -1);
807 * sscanf - Unformat a buffer into a list of arguments
809 * @fmt: formatting of buffer
810 * @...: resulting arguments
812 int sscanf(const char *buf, const char *fmt, ...)
818 i = vsscanf(buf, fmt, args);