Skip to contentSkip to conversation

hw/misc: Fix arith overflow in NPCM7XX PWM module

PATCH Superseded wuhaotsh--- via 2 participants 2 messages Jan 25, 2021 – Jan 26, 2021

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 hw/misc: Fix arith overflow in NPCM7XX PWM module

There's a potential arith overflow in npcm7xx_pwm_calculate_duty. This patch fixes it.

Thanks Peter for finding this out.

---
 hw/misc/npcm7xx_pwm.c          | 4 ++--
 tests/qtest/npcm7xx_pwm-test.c | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
hw/misc/npcm7xx_pwm.c +2 -2
index e99e3cc7ef..90b4f630a0 100644
@@ -102,9 +102,9 @@ static uint32_t npcm7xx_pwm_calculate_duty(NPCM7xxPWM *p)
         if (p->cnr == 0) {
             duty = 0;
         } else if (p->cmr >= p->cnr) {
-            duty = NPCM7XX_PWM_MAX_DUTY;
+            duty = (uint64_t)NPCM7XX_PWM_MAX_DUTY;
         } else {
-            duty = NPCM7XX_PWM_MAX_DUTY * (p->cmr + 1) / (p->cnr + 1);
+            duty = (uint64_t)NPCM7XX_PWM_MAX_DUTY * (p->cmr + 1) / (p->cnr + 1);
         }
     } else {
         duty = 0;
tests/qtest/npcm7xx_pwm-test.c +1 -1
index 63557d2c06..f55571b31d 100644
@@ -280,7 +280,7 @@ static uint64_t pwm_compute_duty(uint32_t cnr, uint32_t cmr, bool inverted)
     } else if (cmr >= cnr) {
         duty = MAX_DUTY;
     } else {
-        duty = MAX_DUTY * (cmr + 1) / (cnr + 1);
+        duty = (uint64_t)MAX_DUTY * (cmr + 1) / (cnr + 1);
     }
 
     if (inverted) {
Signature · 1 line
2.30.0.280.ga3ce27912f-goog
#1 lore raw

Hi Hao Wu,

Quoted 3 lines · wuhaotsh--- via

There's a potential arith overflow in npcm7xx_pwm_calculate_duty.

This patch fixes it.

^ not very useful information ;)

What about the simplest approach Peter suggested, a 32-bit duty?

Quoted 1 line

Thanks Peter for finding this out.

Technically Coverity found this out.
Using QEMU git tags, this is:

Fixes CID 1442342
Quoted 36 lines
---
 hw/misc/npcm7xx_pwm.c          | 4 ++--
 tests/qtest/npcm7xx_pwm-test.c | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
hw/misc/npcm7xx_pwm.c +2 -2
index e99e3cc7ef..90b4f630a0 100644
@@ -102,9 +102,9 @@ static uint32_t npcm7xx_pwm_calculate_duty(NPCM7xxPWM *p)
         if (p->cnr == 0) {
             duty = 0;
         } else if (p->cmr >= p->cnr) {
-            duty = NPCM7XX_PWM_MAX_DUTY;
+            duty = (uint64_t)NPCM7XX_PWM_MAX_DUTY;
         } else {
-            duty = NPCM7XX_PWM_MAX_DUTY * (p->cmr + 1) / (p->cnr + 1);
+            duty = (uint64_t)NPCM7XX_PWM_MAX_DUTY * (p->cmr + 1) / (p->cnr + 1);
         }
     } else {
         duty = 0;
tests/qtest/npcm7xx_pwm-test.c +1 -1
index 63557d2c06..f55571b31d 100644
@@ -280,7 +280,7 @@ static uint64_t pwm_compute_duty(uint32_t cnr, uint32_t cmr, bool inverted)
     } else if (cmr >= cnr) {
         duty = MAX_DUTY;
     } else {
-        duty = MAX_DUTY * (cmr + 1) / (cnr + 1);
+        duty = (uint64_t)MAX_DUTY * (cmr + 1) / (cnr + 1);
     }
 
     if (inverted) {