lib/strutils: improve strtoul_or_err() for negative numbers

Let's use the same code for strtoul_or_err() and strtol_or_err() as we
already use for strtoxXX_or_err() functions. It resolves issue with
negative numbers.

This problem has been discovered by "./eject -x -1 -v" where -x is
based on strtoul_or_err(), but accepts negative number (-1).

Reported-by: Enze Li <lienze@kylinos.cn>
Signed-off-by: Karel Zak <kzak@redhat.com>
pull/1660/head
Karel Zak 6 months ago
parent d7c11b9339
commit 3b88857366
  1. 4
      include/strutils.h
  2. 42
      lib/strutils.c

@ -42,8 +42,8 @@ extern uint64_t str2unum_or_err(const char *str, int base, const char *errmesg,
extern double strtod_or_err(const char *str, const char *errmesg);
extern long double strtold_or_err(const char *str, const char *errmesg);
extern long strtol_or_err(const char *str, const char *errmesg);
extern unsigned long strtoul_or_err(const char *str, const char *errmesg);
#define strtol_or_err(_s, _e) (long) str2num_or_err(_s, 10, _e, LONG_MIN, LONG_MAX)
#define strtoul_or_err(_s, _e) (unsigned long) str2unum_or_err(_s, 10, _e, ULONG_MAX)
extern void strtotimeval_or_err(const char *str, struct timeval *tv,
const char *errmesg);

@ -471,48 +471,6 @@ err:
errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
}
long strtol_or_err(const char *str, const char *errmesg)
{
long num;
char *end = NULL;
errno = 0;
if (str == NULL || *str == '\0')
goto err;
num = strtol(str, &end, 10);
if (errno || str == end || (end && *end))
goto err;
return num;
err:
if (errno == ERANGE)
err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
}
unsigned long strtoul_or_err(const char *str, const char *errmesg)
{
unsigned long num;
char *end = NULL;
errno = 0;
if (str == NULL || *str == '\0')
goto err;
num = strtoul(str, &end, 10);
if (errno || str == end || (end && *end))
goto err;
return num;
err:
if (errno == ERANGE)
err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
}
uintmax_t strtosize_or_err(const char *str, const char *errmesg)
{
uintmax_t num;

Loading…
Cancel
Save