Skip to content

Commit 8fdb058

Browse files
[3.12] gh-106524: Fix a crash in _sre.template() (GH-106525) (GH-106544)
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. (cherry picked from commit 2ef1dc3) Co-authored-by: Radislav Chugunov <[email protected]>
1 parent 2ade2fc commit 8fdb058

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
@@ -2441,6 +2441,16 @@ def test_regression_gh94675(self):
24412441
p.terminate()
24422442
p.join()
24432443

2444+
def test_sre_template_invalid_group_index(self):
2445+
# see gh-106524
2446+
import _sre
2447+
with self.assertRaises(TypeError) as cm:
2448+
_sre.template("", ["", -1, ""])
2449+
self.assertIn("invalid template", str(cm.exception))
2450+
with self.assertRaises(TypeError) as cm:
2451+
_sre.template("", ["", (), ""])
2452+
self.assertIn("an integer is required", str(cm.exception))
2453+
24442454

24452455
def get_debug_out(pat):
24462456
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
@@ -1549,10 +1549,12 @@ _sre_template_impl(PyObject *module, PyObject *pattern, PyObject *template)
15491549
for (Py_ssize_t i = 0; i < n; i++) {
15501550
Py_ssize_t index = PyLong_AsSsize_t(PyList_GET_ITEM(template, 2*i+1));
15511551
if (index == -1 && PyErr_Occurred()) {
1552+
Py_SET_SIZE(self, i);
15521553
Py_DECREF(self);
15531554
return NULL;
15541555
}
15551556
if (index < 0) {
1557+
Py_SET_SIZE(self, i);
15561558
goto bad_template;
15571559
}
15581560
self->items[i].index = index;

0 commit comments

Comments
 (0)