Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0e732d0

Browse files
authored
gh-112625: Protect bytearray from being freed by misbehaving iterator inside bytearray.join (GH-112626)
1 parent 23e001f commit 0e732d0

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/test/test_builtin.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2039,6 +2039,23 @@ def test_bytearray_extend_error(self):
20392039
bad_iter = map(int, "X")
20402040
self.assertRaises(ValueError, array.extend, bad_iter)
20412041

2042+
def test_bytearray_join_with_misbehaving_iterator(self):
2043+
# Issue #112625
2044+
array = bytearray(b',')
2045+
def iterator():
2046+
array.clear()
2047+
yield b'A'
2048+
yield b'B'
2049+
self.assertRaises(BufferError, array.join, iterator())
2050+
2051+
def test_bytearray_join_with_custom_iterator(self):
2052+
# Issue #112625
2053+
array = bytearray(b',')
2054+
def iterator():
2055+
yield b'A'
2056+
yield b'B'
2057+
self.assertEqual(bytearray(b'A,B'), array.join(iterator()))
2058+
20422059
def test_construct_singletons(self):
20432060
for const in None, Ellipsis, NotImplemented:
20442061
tp = type(const)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixes a bug where a bytearray object could be cleared while iterating over an argument in the ``bytearray.join()`` method that could result in reading memory after it was freed.

Objects/bytearrayobject.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2007,7 +2007,10 @@ static PyObject *
20072007
bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
20082008
/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
20092009
{
2010-
return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
2010+
self->ob_exports++; // this protects `self` from being cleared/resized if `iterable_of_bytes` is a custom iterator
2011+
PyObject* ret = stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
2012+
self->ob_exports--; // unexport `self`
2013+
return ret;
20112014
}
20122015

20132016
/*[clinic input]

0 commit comments

Comments
 (0)