Blob Blame History Raw
commit b00a4fa78779ff0f304fa6cb34d49622679c86d4
Author: Mark Wielaard <>
Date:   Thu Sep 3 10:50:58 2015 +0200

    readelf: handle_core_item large right shift triggers undefined behaviour.
    The problem is this:
      int n = ffs (w);
      w >>= n;
    The intent is to shift away up to (and including) the first least
    significant bit in w. But w is an unsigned int, so 32 bits. And the
    least significant bit could be bit 32 (ffs counts from 1). Unfortunately
    a right shift equal to (or larger than) the length in bits of the left
    hand operand is undefined behaviour. We expect w to be zero afterwards.
    Which would terminate the while loop in the function. But since it is
    undefined behaviour anything can happen. In this case, what will actually
    happen is that w is unchanged, causing an infinite loop...
    gcc -fsanitize=undefined will catch and warn about this when w = 0x80000000
    Signed-off-by: Mark Wielaard <>

diff --git a/src/readelf.c b/src/readelf.c
index d3c2b6b..aab8b5c 100644
--- a/src/readelf.c
+++ b/src/readelf.c
@@ -8474,8 +8474,16 @@ handle_core_item (Elf *core, const Ebl_Core_Item *item, const void *desc,
 	    unsigned int w = negate ? ~*i : *i;
 	    while (w != 0)
-		int n = ffs (w);
-		w >>= n;
+		/* Note that a right shift equal to (or greater than)
+		   the number of bits of w is undefined behaviour.  In
+		   particular when the least significant bit is bit 32
+		   (w = 0x8000000) then w >>= n is undefined.  So
+		   explicitly handle that case separately.  */
+		unsigned int n = ffs (w);
+		if (n < sizeof (w) * 8)
+		  w >>= n;
+		else
+		  w = 0;
 		bit += n;
 		if (lastbit != 0 && lastbit + 1 == bit)