Skip to content

Commit 5ff5edf

Browse files
authored
[3.8] bpo-35714: Reject null characters in struct format strings (GH-16928) (GH-20419)
struct.error is now raised if there is a null character in a struct format string. (cherry picked from commit 3f59b55)
1 parent c2a177a commit 5ff5edf

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

Lib/test/test_struct.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,13 @@ def test_format_attr(self):
652652
s2 = struct.Struct(s.format.encode())
653653
self.assertEqual(s2.format, s.format)
654654

655+
def test_issue35714(self):
656+
# Embedded null characters should not be allowed in format strings.
657+
for s in '\0', '2\0i', b'\0':
658+
with self.assertRaisesRegex(struct.error,
659+
'embedded null character'):
660+
struct.calcsize(s)
661+
655662

656663
class UnpackIteratorTest(unittest.TestCase):
657664
"""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:exc:`struct.error` is now raised if there is a null character in a
2+
:mod:`struct` format string.

Modules/_struct.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,10 @@ prepare_s(PyStructObject *self)
12851285
size_t ncodes;
12861286

12871287
fmt = PyBytes_AS_STRING(self->s_format);
1288+
if (strlen(fmt) != (size_t)PyBytes_GET_SIZE(self->s_format)) {
1289+
PyErr_SetString(StructError, "embedded null character");
1290+
return -1;
1291+
}
12881292

12891293
f = whichtable(&fmt);
12901294

0 commit comments

Comments
 (0)