Skip to content

Commit

Permalink
pythongh-106524: Fix a crash in _sre.template() (pythonGH-106525)
Browse files Browse the repository at this point in the history
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 <52372310+chgnrdv@users.noreply.github.com>
  • Loading branch information
chgnrdv authored and miss-islington committed Jul 8, 2023
1 parent 2ade2fc commit 5f432a0
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Lib/test/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -2441,6 +2441,16 @@ def test_regression_gh94675(self):
p.terminate()
p.join()

def test_sre_template_invalid_group_index(self):
# see gh-106524
import _sre
with self.assertRaises(TypeError) as cm:
_sre.template("", ["", -1, ""])
self.assertIn("invalid template", str(cm.exception))
with self.assertRaises(TypeError) as cm:
_sre.template("", ["", (), ""])
self.assertIn("an integer is required", str(cm.exception))


def get_debug_out(pat):
with captured_stdout() as out:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix crash in :func:`!_sre.template` with templates containing invalid group indices.
2 changes: 2 additions & 0 deletions Modules/_sre/sre.c
Original file line number Diff line number Diff line change
Expand Up @@ -1549,10 +1549,12 @@ _sre_template_impl(PyObject *module, PyObject *pattern, PyObject *template)
for (Py_ssize_t i = 0; i < n; i++) {
Py_ssize_t index = PyLong_AsSsize_t(PyList_GET_ITEM(template, 2*i+1));
if (index == -1 && PyErr_Occurred()) {
Py_SET_SIZE(self, i);
Py_DECREF(self);
return NULL;
}
if (index < 0) {
Py_SET_SIZE(self, i);
goto bad_template;
}
self->items[i].index = index;
Expand Down

0 comments on commit 5f432a0

Please sign in to comment.