Fix potential access-off-the-end-of-memory in varbit_out(): it fetched the
authorTom Lane <[email protected]>
Tue, 21 Aug 2007 02:40:26 +0000 (02:40 +0000)
committerTom Lane <[email protected]>
Tue, 21 Aug 2007 02:40:26 +0000 (02:40 +0000)
byte after the last full byte of the bit array, regardless of whether that
byte was part of the valid data or not.  Found by buildfarm testing.
Thanks to Stefan Kaltenbrunner for nailing down the cause.

src/backend/utils/adt/varbit.c

index 533d8bef93e5161b727100d012d28d6eccb732c8..04492d62ee40d2b74ad230c5dd2f0e3d79c99335 100644 (file)
@@ -430,8 +430,9 @@ varbit_out(PG_FUNCTION_ARGS)
        result = (char *) palloc(len + 1);
        sp = VARBITS(s);
        r = result;
-       for (i = 0; i < len - BITS_PER_BYTE; i += BITS_PER_BYTE, sp++)
+       for (i = 0; i <= len - BITS_PER_BYTE; i += BITS_PER_BYTE, sp++)
        {
+               /* print full bytes */
                x = *sp;
                for (k = 0; k < BITS_PER_BYTE; k++)
                {
@@ -439,11 +440,15 @@ varbit_out(PG_FUNCTION_ARGS)
                        x <<= 1;
                }
        }
-       x = *sp;
-       for (k = i; k < len; k++)
+       if (i < len)
        {
-               *r++ = (x & BITHIGH) ? '1' : '0';
-               x <<= 1;
+               /* print the last partial byte */
+               x = *sp;
+               for (k = i; k < len; k++)
+               {
+                       *r++ = (x & BITHIGH) ? '1' : '0';
+                       x <<= 1;
+               }
        }
        *r = '\0';