summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoritchyny <itchyny@cybozu.co.jp>2023-06-27 07:23:41 +0900
committerGitHub <noreply@github.com>2023-06-27 07:23:41 +0900
commitfac5553b22be521b424723c2d508f37831a3db16 (patch)
tree7188b03157ab08797f8ad29fe30a9372601bfc6c
parent6864aa8630237836f31c99a2bc47ca99fdec3f56 (diff)
Fix overflow exception of the modulo operator (fix #1176) (#2629)
-rw-r--r--src/builtin.c6
-rw-r--r--tests/jq.test4
2 files changed, 8 insertions, 2 deletions
diff --git a/src/builtin.c b/src/builtin.c
index 6fa1c52f..649dec3a 100644
--- a/src/builtin.c
+++ b/src/builtin.c
@@ -396,9 +396,11 @@ static jv f_divide(jq_state *jq, jv input, jv a, jv b) {
static jv f_mod(jq_state *jq, jv input, jv a, jv b) {
jv_free(input);
if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {
- if ((intmax_t)jv_number_value(b) == 0)
+ intmax_t bi = (intmax_t)jv_number_value(b);
+ if (bi == 0)
return type_error2(a, b, "cannot be divided (remainder) because the divisor is zero");
- jv r = jv_number((intmax_t)jv_number_value(a) % (intmax_t)jv_number_value(b));
+ // Check if the divisor is -1 to avoid overflow when the dividend is INTMAX_MIN.
+ jv r = jv_number(bi == -1 ? 0 : (intmax_t)jv_number_value(a) % bi);
jv_free(a);
jv_free(b);
return r;
diff --git a/tests/jq.test b/tests/jq.test
index 9aa435a2..86239fa5 100644
--- a/tests/jq.test
+++ b/tests/jq.test
@@ -540,6 +540,10 @@ null
null
172
+[(infinite, -infinite) % (1, -1)]
+null
+[0,0,0,0]
+
1 + tonumber + ("10" | tonumber)
4
15