From: Javid Khan Date: Sat, 27 Jun 2026 17:22:43 +0000 (+0530) Subject: fix signed overflow negating INT64_MIN in json_object_int_inc X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=54f55260115bb91ecb973381bc1038167808e105;p=thirdparty%2Fjson-c.git fix signed overflow negating INT64_MIN in json_object_int_inc --- diff --git a/json_object.c b/json_object.c index 0a61967..4c6db9b 100644 --- a/json_object.c +++ b/json_object.c @@ -1113,14 +1113,14 @@ int json_object_int_inc(struct json_object *jso, int64_t val) { jsoint->cint.c_uint64 = UINT64_MAX; } - else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val)) + else if (val < 0 && jsoint->cint.c_uint64 < (0 - (uint64_t)val)) { jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val; jsoint->cint_type = json_object_int_type_int64; } - else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val)) + else if (val < 0 && jsoint->cint.c_uint64 >= (0 - (uint64_t)val)) { - jsoint->cint.c_uint64 -= (uint64_t)(-val); + jsoint->cint.c_uint64 -= (0 - (uint64_t)val); } else { diff --git a/tests/test_int_add.c b/tests/test_int_add.c index 142feac..be3f5c0 100644 --- a/tests/test_int_add.c +++ b/tests/test_int_add.c @@ -68,6 +68,17 @@ int main(int argc, char **argv) assert(json_object_get_uint64(tmp) == 0); json_object_put(tmp); printf("UINT64 ADD UNDERFLOW PASSED\n"); + // Decrement by INT64_MIN: -val would overflow int64_t, so the magnitude + // has to be taken in unsigned space. + tmp = json_object_new_uint64(100); + json_object_int_inc(tmp, INT64_MIN); + assert(json_object_get_int64(tmp) == INT64_MIN + 100); + json_object_put(tmp); + tmp = json_object_new_uint64(UINT64_MAX); + json_object_int_inc(tmp, INT64_MIN); + assert(json_object_get_uint64(tmp) == (uint64_t)INT64_MAX); + json_object_put(tmp); + printf("UINT64 ADD INT64_MIN PASSED\n"); printf("PASSED\n"); return 0; diff --git a/tests/test_int_add.expected b/tests/test_int_add.expected index f9348d4..34b8edf 100644 --- a/tests/test_int_add.expected +++ b/tests/test_int_add.expected @@ -7,4 +7,5 @@ INT64 ADD UNDERFLOW PASSED UINT64 ADD PASSED UINT64 ADD OVERFLOW PASSED UINT64 ADD UNDERFLOW PASSED +UINT64 ADD INT64_MIN PASSED PASSED