Skip to content

Commit

Permalink
lib/strutils: improve strtoul_or_err() for negative numbers
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
karelzak committed Apr 19, 2022
1 parent d7c11b9 commit 3b88857
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 44 deletions.
4 changes: 2 additions & 2 deletions include/strutils.h
Expand Up @@ -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);
Expand Down
42 changes: 0 additions & 42 deletions lib/strutils.c
Expand Up @@ -471,48 +471,6 @@ long double strtold_or_err(const char *str, const char *errmesg)
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;
Expand Down

0 comments on commit 3b88857

Please sign in to comment.