Skip to contentSkip to conversation

target/i386: avoid signed overflow in IDIV helpers

PATCH New Artemii Mashanov 1 participant 1 message Nov 11 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 target/i386: avoid signed overflow in IDIV helpers

For 16/32 bit IDIV, dividing the minimum double-width signed dividend by -1 overflows host division before the quotient check. On x86 hosts this terminates QEMU with SIGFPE.

Detect these cases before dividing and raise the guest divide-error exception. Add a shared i386/x86_64 regression test checking SIGFPE with FPE_INTDIV.

Based on the diagnosis by naehrwert in issue #4687.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/4687

---
 target/i386/tcg/int_helper.c   |  4 ++--
 tests/tcg/i386/idiv-overflow.c | 42 ++++++++++++++++++++++++++++++++++
 tests/tcg/i386/meson.build     |  1 +
 tests/tcg/x86_64/meson.build   |  1 +
 4 files changed, 46 insertions(+), 2 deletions(-)
 create mode 100644 tests/tcg/i386/idiv-overflow.c
target/i386/tcg/int_helper.c +2 -2
index 772e6ad..d4fa891 100644
@@ -91,7 +91,7 @@ void HELPER(idivw_AX)(CPUX86State *env, target_ulong t0)
 
     num = (env->regs[R_EAX] & 0xffff) | ((env->regs[R_EDX] & 0xffff) << 16);
     den = (int16_t)t0;
-    if (den == 0) {
+    if (den == 0 || (num == INT32_MIN && den == -1)) {
         raise_exception_ra(env, EXCP00_DIVZ, GETPC());
     }
     q = (num / den);
@@ -130,7 +130,7 @@ void HELPER(idivl_EAX)(CPUX86State *env, target_ulong t0)
 
     num = ((uint32_t)env->regs[R_EAX]) | ((uint64_t)((uint32_t)env->regs[R_EDX]) << 32);
     den = t0;
-    if (den == 0) {
+    if (den == 0 || (num == INT64_MIN && den == -1)) {
         raise_exception_ra(env, EXCP00_DIVZ, GETPC());
     }
     q = (num / den);
tests/tcg/i386/idiv-overflow.c new file +42 -0

42 lines not on this page · raw message

tests/tcg/i386/meson.build +1 -0
index e7c3095..f1b3ac5 100644
@@ -8,6 +8,7 @@ tests += {
   'hello-i386.c': {
     'cflags': ['-ffreestanding', '-fno-stack-protector', '-nostdlib'],
   },
+  'idiv-overflow.c': {},
   'test-aes.c': {'cflags': ['-O1', '-msse2', '-maes']},
   'test-i386-adcox.c': {'cflags': ['-O2']},
   'test-i386-bmi2.c': {'cflags': ['-O2', '-fwrapv']},
tests/tcg/x86_64/meson.build +1 -0
index ad4d1f5..713dde6 100644
@@ -25,6 +25,7 @@ test_mmx_h = custom_target('test_mmx_h',
                            output: 'test-mmx.h')
 
 tests += {
+  '../i386/idiv-overflow.c': {},
   '../i386/test-i386-ssse3.c': {},
   '../i386/test-3dnow.c': {
     'cflags': ['-I', meson.current_build_dir(),
Signature · 1 line
2.56.0