]> 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:13:54 +0000 (21:13 +0300)
committerSerhiy Storchaka <storchaka@gmail.com>
Mon, 29 Jun 2015 18:13:54 +0000 (21:13 +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 988b931d1a803a4adad0d5262198a977408d9cca..02fba389ca730ae40cd4c21a8a997090b0b2ee04 100644 (file)
@@ -722,10 +722,27 @@ class ByteArrayTest(BaseBytesTest):
         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 92e08a9219bbd07901ac6f722b4351d5be9d19e1..e6240e2b7adf56cc1e9f35a3f76917a9872c0858 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,10 @@ What's New in Python 2.7.11?
 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 #19543: encode() and decode() methods and constructors of str,
   unicode and bytearray classes now emit deprecation warning for known
   non-text encodings when Python is ran with the -3 option.
index 5f575805d494030c041bbb6e3cce3d115c7e85b4..5276da51bdb7e4174e110e791d1422d271e48665 100644 (file)
@@ -897,8 +897,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;
         self->ob_bytes[Py_SIZE(self)-1] = value;