From 16b33e6649425fcdce095f262da98b539d2f7448 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Fri, 19 Jul 2024 10:39:58 -0700 Subject: [PATCH] xstrtol: be more robust against odd failures MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * lib/xstrtol.c (__xstrtol): Don’t update *endptr if strtol doesn’t. Also, if the underlying strtol gives an unusual error number and sets *endpnr = nptr, assume that’s an error not a missing number. Problems reported by Alejandro Colomar in: https://lists.gnu.org/r/bug-gnulib/2024-07/msg00175.html https://lists.gnu.org/r/bug-gnulib/2024-07/msg00176.html * modules/xstrtol (Depends-on): Add nullptr. --- ChangeLog | 11 +++++++++++ lib/xstrtol.c | 15 ++++++++++----- modules/xstrtol | 1 + 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/ChangeLog b/ChangeLog index 072a28855d..4e88d446a1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,14 @@ +2024-07-19 Paul Eggert + + xstrtol: be more robust against odd failures + * lib/xstrtol.c (__xstrtol): Don’t update *endptr if strtol doesn’t. + Also, if the underlying strtol gives an unusual error number and + sets *endpnr = nptr, assume that’s an error not a missing number. + Problems reported by Alejandro Colomar in: + https://lists.gnu.org/r/bug-gnulib/2024-07/msg00175.html + https://lists.gnu.org/r/bug-gnulib/2024-07/msg00176.html + * modules/xstrtol (Depends-on): Add nullptr. + 2024-07-19 Bruno Haible doc: Mention function that were added in ISO C23. diff --git a/lib/xstrtol.c b/lib/xstrtol.c index c3145171f3..797d3e4dee 100644 --- a/lib/xstrtol.c +++ b/lib/xstrtol.c @@ -71,9 +71,8 @@ strtol_error __xstrtol (char const *nptr, char **endptr, int base, __strtol_t *val, char const *valid_suffixes) { - char *t_ptr; + char *t_ptr = nullptr; char **p = endptr ? endptr : &t_ptr; - *p = (char *) nptr; if (! TYPE_SIGNED (__strtol_t)) { @@ -82,14 +81,20 @@ __xstrtol (char const *nptr, char **endptr, int base, while (isspace (ch)) ch = *++q; if (ch == '-') - return LONGINT_INVALID; + { + *p = (char *) nptr; + return LONGINT_INVALID; + } } errno = 0; - __strtol_t tmp = __strtol (nptr, p, base); + __strtol_t tmp = __strtol (nptr, &t_ptr, base); + if (!t_ptr) + return LONGINT_INVALID; + *p = t_ptr; strtol_error err = LONGINT_OK; - if (*p == nptr) + if (*p == nptr && (errno == 0 || errno == EINVAL)) { /* If there is no number but there is a valid suffix, assume the number is 1. The string is invalid otherwise. */ diff --git a/modules/xstrtol b/modules/xstrtol index ef49dfc357..1f8a28fa6c 100644 --- a/modules/xstrtol +++ b/modules/xstrtol @@ -9,6 +9,7 @@ m4/xstrtol.m4 Depends-on: intprops +nullptr stdckdint stdint -- 2.39.5