summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Lib/test/test_re.py10
-rw-r--r--Misc/NEWS.d/next/Library/2023-07-07-17-44-03.gh-issue-106524.XkBV8h.rst1
-rw-r--r--Modules/_sre/sre.c2
3 files changed, 13 insertions, 0 deletions
diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index 11628a2..a05a1c9 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -2441,6 +2441,16 @@ class ReTests(unittest.TestCase):
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:
diff --git a/Misc/NEWS.d/next/Library/2023-07-07-17-44-03.gh-issue-106524.XkBV8h.rst b/Misc/NEWS.d/next/Library/2023-07-07-17-44-03.gh-issue-106524.XkBV8h.rst
new file mode 100644
index 0000000..f3fd070
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-07-07-17-44-03.gh-issue-106524.XkBV8h.rst
@@ -0,0 +1 @@
+Fix crash in :func:`!_sre.template` with templates containing invalid group indices.
diff --git a/Modules/_sre/sre.c b/Modules/_sre/sre.c
index f8a1a05..2f1c732 100644
--- a/Modules/_sre/sre.c
+++ b/Modules/_sre/sre.c
@@ -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;