Skip to contentSkip to conversation

hw/net/rocker: Don't overflow in of_dpa_mask2prefix()

PATCH Superseded Peter Maydell 2 participants 2 messages Jul 10, 2025

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 hw/net/rocker: Don't overflow in of_dpa_mask2prefix()

In of_dpa_mask2prefix() we do "(2 << i)" for a loop where i can go up to 31. At i == 31 we shift off the top end of an integer.

Use 2ULL to avoid this overflow.

Fixes dc488f888060a ("rocker: add new rocker switch device")

Coverity: CID 1547602

---
 hw/net/rocker/rocker_of_dpa.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/net/rocker/rocker_of_dpa.c +1 -1
index 4aed1787566..9c0fc728eee 100644
@@ -202,7 +202,7 @@ static int of_dpa_mask2prefix(uint32_t mask)
     int count = 32;
 
     for (i = 0; i < 32; i++) {
-        if (!(ntohl(mask) & ((2 << i) - 1))) {
+        if (!(ntohl(mask) & ((2ULL << i) - 1))) {
             count--;
         }
     }
Signature · 1 line
2.43.0
#1 lore raw
Quoted 18 lines · Peter Maydell

In of_dpa_mask2prefix() we do "(2 << i)" for a loop where i can go up to 31. At i == 31 we shift off the top end of an integer.

Use 2ULL to avoid this overflow.

Fixes dc488f888060a ("rocker: add new rocker switch device")

Coverity: CID 1547602

---
  hw/net/rocker/rocker_of_dpa.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
hw/net/rocker/rocker_of_dpa.c +0 -0
index 4aed1787566..9c0fc728eee 100644

hw/net/rocker/rocker_of_dpa.c static int of_dpa_mask2prefix(uint32_t mask) · line 208

Quoted 8 lines
hw/net/rocker/rocker_of_dpa.c +1 -1
@@ -202,7 +202,7 @@ static int of_dpa_mask2prefix(uint32_t mask)
      int count = 32;
 
      for (i = 0; i < 32; i++) {
-        if (!(ntohl(mask) & ((2 << i) - 1))) {
+        if (!(ntohl(mask) & ((2ULL << i) - 1))) {
              count--;
          }
      }

Alternatively using ctz (untested):

-- >8 --

hw/net/rocker/rocker_of_dpa.c +2 -11
index 4aed1787566..431638dd64e 100644
@@ -198,14 +198,5 @@ typedef struct of_dpa_group {
 
-static int of_dpa_mask2prefix(uint32_t mask)
+static unsigned of_dpa_mask2prefix(uint32_t mask)
 {
-    int i;
-    int count = 32;
-
-    for (i = 0; i < 32; i++) {
-        if (!(ntohl(mask) & ((2 << i) - 1))) {
-            count--;
-        }
-    }
-
-    return count;
+    return 32 - ctz32(cpu_to_be32(mask));
 }

---