Commit 0b1aa087 authored by Stanislav Kinsburskiy's avatar Stanislav Kinsburskiy Committed by Andrei Vagin

util: xatol() and xatoi() helpers introduced

These helpers are safe versions of atol() and atoi() respectively.
And they check for overflow and NAN errors

v3:
1) Added string print to convertion error message in xatol_base()
2) Added check for INT range in xatoi()
Signed-off-by: 's avatarStanislav Kinsburskiy <skinsbursky@virtuozzo.com>
Signed-off-by: 's avatarAndrei Vagin <avagin@virtuozzo.com>
parent 47761827
...@@ -276,6 +276,9 @@ void tcp_cork(int sk, bool on); ...@@ -276,6 +276,9 @@ void tcp_cork(int sk, bool on);
const char *ns_to_string(unsigned int ns); const char *ns_to_string(unsigned int ns);
int xatol(const char *string, long *number);
int xatoi(const char *string, int *number);
char *xstrcat(char *str, const char *fmt, ...) char *xstrcat(char *str, const char *fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3))); __attribute__ ((__format__ (__printf__, 2, 3)));
char *xsprintf(const char *fmt, ...) char *xsprintf(const char *fmt, ...)
......
...@@ -56,6 +56,51 @@ ...@@ -56,6 +56,51 @@
#define VMA_OPT_LEN 128 #define VMA_OPT_LEN 128
static int xatol_base(const char *string, long *number, int base)
{
char *endptr;
long nr;
errno = 0;
nr = strtol(string, &endptr, base);
if ((errno == ERANGE && (nr == LONG_MAX || nr == LONG_MIN))
|| (errno != 0 && nr == 0)) {
pr_perror("failed to convert string '%s'", string);
return -EINVAL;
}
if ((endptr == string) || (*endptr != '\0')) {
pr_err("String is not a number: '%s'\n", string);
return -EINVAL;
}
*number = nr;
return 0;
}
int xatol(const char *string, long *number)
{
return xatol_base(string, number, 10);
}
int xatoi(const char *string, int *number)
{
long tmp;
int err;
err = xatol(string, &tmp);
if (err)
return err;
if (tmp > INT_MAX || tmp < INT_MIN) {
pr_err("value %#lx (%ld) is out of int range\n", tmp, tmp);
return -ERANGE;
}
*number = (int)tmp;
return 0;
}
/* /*
* This function reallocates passed str pointer. * This function reallocates passed str pointer.
* It means: * It means:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment