]> git.ipfire.org Git - thirdparty/qemu.git/commitdiff
hw/net/rocker: Don't overflow in of_dpa_mask2prefix()
authorPeter Maydell <peter.maydell@linaro.org>
Thu, 16 Oct 2025 14:54:07 +0000 (15:54 +0100)
committerPeter Maydell <peter.maydell@linaro.org>
Thu, 23 Oct 2025 13:13:38 +0000 (14:13 +0100)
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.  This
doesn't actually calculate the wrong value in practice, because we
calculate 0 - 1 which is the 0xffffffff mask we wanted (and for QEMU
shifting off the top of a signed integer is not UB); but it makes
Coverity complain.

We could fix this simply by using "2ULL" (where the "(2ULL << i) - 1"
expression also evaluates to 0xffffffff for i == 31), but in fact
this function is a slow looping implementation of counting the number
of trailing zeroes in the (network-order) input mask:

 0bxxxxxxxxx1 => 32
 0bxxxxxxxx10 => 31
 0bxxxxxxx100 => 30
 ...
 0bx100000000 => 2
 0b1000000000 => 1
 0b0000000000 => 0

Replace the implementation with 32 - ctz32().

Coverity: CID 1547602
Suggested-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Message-id: 20251016145407.781978-1-peter.maydell@linaro.org

hw/net/rocker/rocker_of_dpa.c

index 4aed17875666987a7eb988072458951a55583de9..16b9bc7a4b8f54494273a5c7a517531abb5b9c7e 100644 (file)
@@ -198,16 +198,7 @@ typedef struct of_dpa_group {
 
 static int 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(ntohl(mask));
 }
 
 #if defined(DEBUG_ROCKER)