// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include int errno; typedef struct ParseStatus { int negative; int overflow; } ParseStatus; // 36 terminates the scan in every supported base. static unsigned digitValue(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'Z') return c - 'A' + 10; if (c >= 'a' && c <= 'z') return c - 'a' + 10; return 36; } static unsigned long magnitude(const char *text, char **endptr, int base, int signedResult, ParseStatus *status) { const char *p = text; status->negative = 0; status->overflow = 0; if (endptr) *endptr = (char *) text; if (base != 0 && (base < 2 || base > 36)) { errno = EINVAL; return 0UL; } while (isspace((unsigned char) *p)) ++p; if (*p == '+' || *p == '-') { status->negative = (*p == '-'); ++p; } // In "0x!" the zero is a valid digit and the x ends the number. if ((base == 0 || base == 16) && *p == '0' && (p[1] == 'x' || p[1] == 'X') && digitValue(p[2]) < 16) { base = 16; p += 2; } else if (base == 0) { base = (*p == '0') ? 8 : 10; } unsigned digit = digitValue(*p); if (digit >= (unsigned) base) return 0UL; unsigned long limit = ULONG_MAX; if (signedResult) limit = (unsigned long) LONG_MAX + status->negative; unsigned long cutoff = limit / (unsigned) base; unsigned lastDigit = (unsigned) (limit - cutoff * (unsigned) base); unsigned long value = 0UL; do { if (!status->overflow) { if (value > cutoff || (value == cutoff && digit > lastDigit)) { status->overflow = 1; value = limit; errno = ERANGE; } else { value = value * (unsigned) base + digit; } } // Even after saturation, the end pointer must skip every valid digit. digit = digitValue(*++p); } while (digit < (unsigned) base); if (endptr) *endptr = (char *) p; return value; } long strtol(const char *text, char **endptr, int base) { ParseStatus status; unsigned long value = magnitude(text, endptr, base, 1, &status); if (!status.negative) return (long) value; if (value > (unsigned long) LONG_MAX) return LONG_MIN; return -(long) value; } unsigned long strtoul(const char *text, char **endptr, int base) { ParseStatus status; unsigned long value = magnitude(text, endptr, base, 0, &status); if (status.negative && !status.overflow) return 0UL - value; return value; }