Skip to content

Commit c72ffe7

Browse files
authored
gh-129813, PEP 782: Set invalid bytes in PyBytesWriter (#139054)
Initialize the buffer with 0xFF byte pattern when creating a writer object, but also when resizing/growing the writer.
1 parent 82e1920 commit c72ffe7

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

Objects/bytesobject.c

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3805,12 +3805,12 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int overallocate)
38053805
{
38063806
assert(size >= 0);
38073807

3808-
if (size <= byteswriter_allocated(writer)) {
3808+
Py_ssize_t old_allocated = byteswriter_allocated(writer);
3809+
if (size <= old_allocated) {
38093810
return 0;
38103811
}
38113812

3812-
overallocate &= writer->overallocate;
3813-
if (overallocate) {
3813+
if (overallocate & writer->overallocate) {
38143814
if (size <= (PY_SSIZE_T_MAX - size / OVERALLOCATE_FACTOR)) {
38153815
size += size / OVERALLOCATE_FACTOR;
38163816
}
@@ -3849,6 +3849,15 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int overallocate)
38493849
writer->small_buffer,
38503850
sizeof(writer->small_buffer));
38513851
}
3852+
3853+
#ifdef Py_DEBUG
3854+
Py_ssize_t allocated = byteswriter_allocated(writer);
3855+
if (overallocate && allocated > old_allocated) {
3856+
memset(byteswriter_data(writer) + old_allocated, 0xff,
3857+
allocated - old_allocated);
3858+
}
3859+
#endif
3860+
38523861
return 0;
38533862
}
38543863

@@ -3869,9 +3878,6 @@ byteswriter_create(Py_ssize_t size, int use_bytearray)
38693878
return NULL;
38703879
}
38713880
}
3872-
#ifdef Py_DEBUG
3873-
memset(writer->small_buffer, 0xff, sizeof(writer->small_buffer));
3874-
#endif
38753881
writer->obj = NULL;
38763882
writer->size = 0;
38773883
writer->use_bytearray = use_bytearray;
@@ -3884,6 +3890,9 @@ byteswriter_create(Py_ssize_t size, int use_bytearray)
38843890
}
38853891
writer->size = size;
38863892
}
3893+
#ifdef Py_DEBUG
3894+
memset(byteswriter_data(writer), 0xff, byteswriter_allocated(writer));
3895+
#endif
38873896
return writer;
38883897
}
38893898

0 commit comments

Comments
 (0)