From 2da01c607f6341a18dcd726b46f3e7a4a2c49211 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 19 Nov 2025 15:34:32 +0900 Subject: [PATCH] mruby-pack: avoid integer overflow in pack_hex buffer calculation rewrite ceiling division to avoid signed overflow. the expression (count + 1) / 2 triggers undefined behavior when count == INT_MAX. use count / 2 + (count & 1) instead, which computes the same result without intermediate overflow. Co-authored-by: Claude --- mrbgems/mruby-pack/src/pack.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mrbgems/mruby-pack/src/pack.c b/mrbgems/mruby-pack/src/pack.c index 09f5084d6..4342c87d4 100644 --- a/mrbgems/mruby-pack/src/pack.c +++ b/mrbgems/mruby-pack/src/pack.c @@ -1009,7 +1009,8 @@ pack_hex(mrb_state *mrb, mrb_value src, mrb_value dst, mrb_int didx, int count, } /* calculate output buffer size needed - one byte per two hex chars */ - int output_bytes = (count + 1) / 2; + /* use count/2 + (count&1) to avoid overflow when count == INT_MAX */ + int output_bytes = count / 2 + (count & 1); dst = str_len_ensure(mrb, dst, didx + output_bytes); char *dptr = RSTRING_PTR(dst) + didx; char *dptr0 = dptr;