]> git.ipfire.org Git - thirdparty/elfutils.git/commitdiff
readelf: handle_core_item large right shift triggers undefined behaviour.
authorMark Wielaard <mjw@redhat.com>
Thu, 3 Sep 2015 08:50:58 +0000 (10:50 +0200)
committerMark Wielaard <mjw@redhat.com>
Thu, 3 Sep 2015 08:50:58 +0000 (10:50 +0200)
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

https://bugzilla.redhat.com/show_bug.cgi?id=1259259

Signed-off-by: Mark Wielaard <mjw@redhat.com>
src/ChangeLog
src/readelf.c

index 5be1075003f055fc91c65d086e4fb899f527ed87..66f7ead1a487dfa944c0c2620fd18beb6fdd25d1 100644 (file)
@@ -1,3 +1,7 @@
+2015-09-03  Mark Wielaard  <mjw@redhat.com>
+
+       * readelf.c (handle_core_item): Handle right shift >= 32 bits.
+
 2015-08-11  Mark Wielaard  <mjw@redhat.com>
 
        * elflint.c (check_sections): When gnuld and a NOBITS section falls
index d3c2b6b4a4f289094ccd05a1db1f517137ea3aef..aab8b5ccd6508baedfb11fc59649ceaee40ce120 100644 (file)
@@ -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)