]> granicus.if.org Git - python/commitdiff
Issue #24467: Fixed possible buffer over-read in bytearray. The bytearray
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 29 Jun 2015 18:14:06 +0000 (21:14 +0300)
committerSerhiy Storchaka <storchaka@gmail.com>
Mon, 29 Jun 2015 18:14:06 +0000 (21:14 +0300)
object now always allocates place for trailing null byte and it's buffer now
is always null-terminated.

Lib/test/test_bytes.py
Misc/NEWS
Objects/bytearrayobject.c

index 6b58e74dd81ef7810cb43772de528c073b9645e9..b00573f4e415723b8306660bd6e7800975dc0387 100644 (file)
@@ -1030,10 +1030,27 @@ class ByteArrayTest(BaseBytesTest, unittest.TestCase):
         for i in range(100):
             b += b"x"
             alloc = b.__alloc__()
-            self.assertTrue(alloc >= len(b))
+            self.assertGreater(alloc, len(b))  # including trailing null byte
             if alloc not in seq:
                 seq.append(alloc)
 
+    def test_init_alloc(self):
+        b = bytearray()
+        def g():
+            for i in range(1, 100):
+                yield i
+                a = list(b)
+                self.assertEqual(a, list(range(1, len(a)+1)))
+                self.assertEqual(len(b), len(a))
+                self.assertLessEqual(len(b), i)
+                alloc = b.__alloc__()
+                self.assertGreater(alloc, len(b))  # including trailing null byte
+        b.__init__(g())
+        self.assertEqual(list(b), list(range(1, 100)))
+        self.assertEqual(len(b), 99)
+        alloc = b.__alloc__()
+        self.assertGreater(alloc, len(b))
+
     def test_extend(self):
         orig = b'hello'
         a = bytearray(orig)
index 1e1eba6944a3eff3ba842d8e87c02230b0774486..9d8f1e8b817b255a6dbd39a9df92497b84781c61 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,10 @@ Release date: tba
 Core and Builtins
 -----------------
 
+- Issue #24467: Fixed possible buffer over-read in bytearray. The bytearray
+  object now always allocates place for trailing null byte and it's buffer now
+  is always null-terminated.
+
 - Issue #24115: Update uses of PyObject_IsTrue(), PyObject_Not(),
   PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains()
   to check for and handle errors correctly.
index 2e47a1c47c99ace925133326b460030cb0653235..15c525c44224d30cd115cbdcf3f3ba28c66154cb 100644 (file)
@@ -854,8 +854,10 @@ bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
             goto error;
 
         /* Append the byte */
-        if (Py_SIZE(self) < self->ob_alloc)
+        if (Py_SIZE(self) + 1 < self->ob_alloc) {
             Py_SIZE(self)++;
+            PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
+        }
         else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
             goto error;
         PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;