diff --git a/lib/libutil/expand_number.c b/lib/libutil/expand_number.c --- a/lib/libutil/expand_number.c +++ b/lib/libutil/expand_number.c @@ -76,6 +76,8 @@ shift = 10; break; case 'b': + shift = 0; + break; case '\0': /* No unit. */ *num = number; return (0); @@ -85,6 +87,16 @@ return (-1); } + /* + * endptr is the unit and there must be no + * remaining characters. + */ + endptr++; + if (*endptr != '\0') { + errno = EINVAL; + return (-1); + } + if ((number << shift) >> shift != number) { /* Overflow */ errno = ERANGE; diff --git a/lib/libutil/tests/Makefile b/lib/libutil/tests/Makefile --- a/lib/libutil/tests/Makefile +++ b/lib/libutil/tests/Makefile @@ -7,6 +7,7 @@ TAP_TESTS_C+= trimdomain_test TAP_TESTS_C+= trimdomain-nodomain_test ATF_TESTS_C+= cpuset_test +ATF_TESTS_C+= expand_number_test WARNS?= 2 LIBADD+= util diff --git a/lib/libutil/tests/expand_number_test.c b/lib/libutil/tests/expand_number_test.c new file mode 100644 --- /dev/null +++ b/lib/libutil/tests/expand_number_test.c @@ -0,0 +1,59 @@ +#include +__FBSDID("$FreeBSD$"); + +#include +#include + +#include + +ATF_TC_WITHOUT_HEAD(positivetests); +ATF_TC_BODY(positivetests, tc) +{ + int retval; + uint64_t num; + +#define positive_tc(string, value) \ + do { \ + ATF_CHECK_ERRNO(0, (retval = expand_number((string), &num)) == 0); \ + ATF_CHECK_EQ(retval, 0); \ + ATF_CHECK_EQ(num, (value)); \ + } while (0) + + positive_tc("123456", 123456); + positive_tc("123456b", 123456); + positive_tc("1k", 1024); + positive_tc("1K", 1024); + positive_tc("1m", 1048576); + positive_tc("1M", 1048576); + positive_tc("1g", 1073741824); + positive_tc("1G", 1073741824); + positive_tc("1t", 1099511627776); + positive_tc("1T", 1099511627776); + positive_tc("1p", 1125899906842624); + positive_tc("1P", 1125899906842624); + positive_tc("1e", 1152921504606846976); + positive_tc("1E", 1152921504606846976); + positive_tc("15E", 17293822569102704640ULL); +} + +ATF_TC_WITHOUT_HEAD(negativetests); +ATF_TC_BODY(negativetests, tc) +{ + int retval; + uint64_t num; + + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("", &num)); + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("x", &num)); + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("1bb", &num)); + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("1kb", &num)); + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("1x", &num)); + ATF_CHECK_ERRNO(EINVAL, retval = expand_number("1kx", &num)); + ATF_CHECK_ERRNO(ERANGE, retval = expand_number("16E", &num)); +} + +ATF_TP_ADD_TCS(tp) +{ + ATF_TP_ADD_TC(tp, positivetests); + ATF_TP_ADD_TC(tp, negativetests); + return (atf_no_error()); +}