While we were matching 32-bit strtol in qemu_strtoi, our use of a
64-bit parse was leaking through for some inaccurate answers in
qemu_strtoui in comparison to a 32-bit strtoul. Fix those, and update
the testsuite now that our bounds checks are correct.
Our int wrappers would be a lot easier to write if libc had a
guaranteed 32-bit parser even on platforms with 64-bit long.
Fixes: 473a2a331e ("cutils: add qemu_strtoi & qemu_strtoui parsers for int/unsigned
int types", v2.12.0)
Signed-off-by: Eric Blake <eblake@redhat.com>
---
tests/unit/test-cutils.c | 11 +++++------
util/cutils.c | 14 ++++++++++----
2 files changed, 15 insertions(+), 10 deletions(-)
diff --git a/util/cutils.c b/util/cutils.c
index 5887e744140..997ddcd09e5 100644
--- a/util/cutils.c
+++ b/util/cutils.c
@@ -466,10 +466,16 @@ int qemu_strtoui(const char *nptr, const char **endptr,
int base,
if (errno == ERANGE) {
*result = -1;
} else {
- if (lresult > UINT_MAX) {
- *result = UINT_MAX;
- errno = ERANGE;
- } else if (lresult < INT_MIN) {
+ /*
+ * Note that platforms with 32-bit strtoul accept input in the
+ * range [-4294967295, 4294967295]; but we used 64-bit
+ * strtoull which wraps -18446744073709551615 to 1. Reject
+ * positive values that contain '-', and wrap all valid
+ * negative values.
+ */
+ if (lresult > UINT_MAX ||
+ lresult < -(long long)UINT_MAX ||
+ (lresult > 0 && memchr(nptr, '-', ep - nptr))) {
*result = UINT_MAX;
errno = ERANGE;
} else {