Skip to content

Commit 2ef1dc3

Browse files
authored
gh-106524: Fix a crash in _sre.template() (GH-106525)
Some items remained uninitialized if _sre.template() was called with invalid indices. Then attempt to clear them in the destructor led to dereferencing of uninitialized pointer.
1 parent 1c9e493 commit 2ef1dc3

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

Lib/test/test_re.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,6 +2418,16 @@ def test_regression_gh94675(self):
24182418
p.terminate()
24192419
p.join()
24202420

2421+
def test_sre_template_invalid_group_index(self):
2422+
# see gh-106524
2423+
import _sre
2424+
with self.assertRaises(TypeError) as cm:
2425+
_sre.template("", ["", -1, ""])
2426+
self.assertIn("invalid template", str(cm.exception))
2427+
with self.assertRaises(TypeError) as cm:
2428+
_sre.template("", ["", (), ""])
2429+
self.assertIn("an integer is required", str(cm.exception))
2430+
24212431

24222432
def get_debug_out(pat):
24232433
with captured_stdout() as out:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash in :func:`!_sre.template` with templates containing invalid group indices.

Modules/_sre/sre.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1544,10 +1544,12 @@ _sre_template_impl(PyObject *module, PyObject *pattern, PyObject *template)
15441544
for (Py_ssize_t i = 0; i < n; i++) {
15451545
Py_ssize_t index = PyLong_AsSsize_t(PyList_GET_ITEM(template, 2*i+1));
15461546
if (index == -1 && PyErr_Occurred()) {
1547+
Py_SET_SIZE(self, i);
15471548
Py_DECREF(self);
15481549
return NULL;
15491550
}
15501551
if (index < 0) {
1552+
Py_SET_SIZE(self, i);
15511553
goto bad_template;
15521554
}
15531555
self->items[i].index = index;

0 commit comments

Comments
 (0)