From 54f55260115bb91ecb973381bc1038167808e105 Mon Sep 17 00:00:00 2001 From: Javid Khan Date: Sat, 27 Jun 2026 22:52:43 +0530 Subject: [PATCH] fix signed overflow negating INT64_MIN in json_object_int_inc --- json_object.c | 6 +++--- tests/test_int_add.c | 11 +++++++++++ tests/test_int_add.expected | 1 + 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/json_object.c b/json_object.c index 0a619679..4c6db9bf 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 142feacb..be3f5c06 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 f9348d4b..34b8edfb 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 -- 2.47.3