From 9602f35f122e1f832fc8aab82e9f068caee390fc Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:34:28 +0500 Subject: [PATCH 1/3] [mypyc] Fix crash when __getitem__ raises in a match sequence pattern The sequence_get_item primitive (PySequence_GetItem) used by sequence patterns in match statements was declared with ERR_NEVER, so if the subject's __getitem__ raised an exception the NULL result was used as a valid object, causing a crash. Use ERR_MAGIC so the error propagates. --- mypyc/primitives/list_ops.py | 2 +- mypyc/test-data/run-match.test | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/mypyc/primitives/list_ops.py b/mypyc/primitives/list_ops.py index f5548e88592f1..bbe33c6100cd4 100644 --- a/mypyc/primitives/list_ops.py +++ b/mypyc/primitives/list_ops.py @@ -367,7 +367,7 @@ arg_types=[object_rprimitive, c_pyssize_t_rprimitive], return_type=object_rprimitive, c_function_name="PySequence_GetItem", - error_kind=ERR_NEVER, + error_kind=ERR_MAGIC, ) sequence_get_slice = custom_op( diff --git a/mypyc/test-data/run-match.test b/mypyc/test-data/run-match.test index b24552072a655..94d1d17cf769a 100644 --- a/mypyc/test-data/run-match.test +++ b/mypyc/test-data/run-match.test @@ -302,3 +302,38 @@ f(sequence) [out] {'some': 'data'} [3] + +[case testSequencePatternGetItemRaises_python3_10] +def f(x: object) -> object: + match x: + case [a, b]: + return a + return None + +def g(x: object) -> object: + match x: + case [1, *rest, b]: + return b + return None + +[file driver.py] +from collections.abc import Sequence + +from native import f, g + +class BadSequence(Sequence): + def __len__(self) -> int: + return 2 + + def __getitem__(self, index: int) -> None: + raise RuntimeError("boom") + +for fn in (f, g): + try: + fn(BadSequence()) + except RuntimeError as e: + print(type(e).__name__, e) + +[out] +RuntimeError boom +RuntimeError boom From ee2ffe37ab3e356f9616b8692020231e8b6c393a Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:35:45 +0500 Subject: [PATCH 2/3] [mypyc] Fix use-after-free in list.count when __eq__ mutates the list On builds with the GIL, list_count passed the borrowed list item directly to PyObject_RichCompareBool. If the item's __eq__ removed it from the list (e.g. by clearing the list), the item could be freed while still in use, for example by the reflected comparison. Hold a reference to the item during the comparison, like CPython does. --- mypyc/lib-rt/pythonsupport.h | 6 +++++- mypyc/test-data/run-lists.test | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/mypyc/lib-rt/pythonsupport.h b/mypyc/lib-rt/pythonsupport.h index 2d3eef3bd740c..631d77cf33e83 100644 --- a/mypyc/lib-rt/pythonsupport.h +++ b/mypyc/lib-rt/pythonsupport.h @@ -448,7 +448,11 @@ list_count(PyListObject *self, PyObject *value) } #else for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ); + PyObject *item = self->ob_item[i]; + // The comparison may mutate the list, so keep the item alive. + Py_INCREF(item); + int cmp = PyObject_RichCompareBool(item, value, Py_EQ); + Py_DECREF(item); if (cmp > 0) count++; else if (cmp < 0) diff --git a/mypyc/test-data/run-lists.test b/mypyc/test-data/run-lists.test index ccb24de3514f9..df9e0dd37931f 100644 --- a/mypyc/test-data/run-lists.test +++ b/mypyc/test-data/run-lists.test @@ -364,6 +364,43 @@ def test_index() -> None: else: assert False +[case testListCountEqMutatesList] +from typing import Any + +from listcounthelper import X, Y + +def count(a: list[Any], x: Any) -> int: + return a.count(x) + +def test_count_eq_clears_list() -> None: + lst: list[Any] = [] + lst.append(X(lst)) + y = Y() + assert count(lst, y) == 0 + assert lst == [] + assert y.seen == ["X"] + +[file listcounthelper.py] +from typing import Any + +class X: + def __init__(self, lst: list[Any]) -> None: + self.lst = lst + + def __eq__(self, other: object) -> bool: + # Drop the list's (only) reference to self, then force the reflected + # comparison, which receives self as the argument + self.lst.clear() + return NotImplemented + +class Y: + def __init__(self) -> None: + self.seen: list[str] = [] + + def __eq__(self, other: object) -> bool: + self.seen.append(type(other).__name__) + return False + [case testListOfUserDefinedClass] class C: x: int From 2f49ed1d9fbe839bc038eef83088d8c14dddfe08 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:45:15 +0500 Subject: [PATCH 3/3] [mypyc] Fix dict.setdefault race and empty collection subclass handling CPyDict_SetDefault used PyDict_SetDefault, which returns a borrowed reference, and only increfed it after the call. On free-threaded builds another thread can remove the value from the dict in between, so the result could be freed before we took a reference. Use PyDict_SetDefaultRef instead. CPyDict_SetDefaultWithEmptyDatatype (used for d.setdefault(k, []), d.setdefault(k, {}) and d.setdefault(k, set())) did a separate get and set. This was not atomic on free-threaded builds, so concurrent calls could each insert a fresh collection and lose updates. For dict subclasses it also used __getitem__, so __missing__ was triggered (e.g. Counter returned 0 and inserted nothing) and an overridden setdefault was ignored. Now we only do a lookup as a fast path for exact dicts, and otherwise create the empty collection and call setdefault (PyDict_SetDefaultRef for exact dicts, the setdefault method for subclasses). --- mypyc/lib-rt/dict_ops.c | 55 ++++++++++++++-------------------- mypyc/test-data/run-dicts.test | 38 +++++++++++++++++++++++ 2 files changed, 61 insertions(+), 32 deletions(-) diff --git a/mypyc/lib-rt/dict_ops.c b/mypyc/lib-rt/dict_ops.c index 5c1d0c7a48e98..1ece9517f3fbd 100644 --- a/mypyc/lib-rt/dict_ops.c +++ b/mypyc/lib-rt/dict_ops.c @@ -72,8 +72,10 @@ PyObject *CPyDict_GetWithNone(PyObject *dict, PyObject *key) { PyObject *CPyDict_SetDefault(PyObject *dict, PyObject *key, PyObject *value) { if (PyDict_CheckExact(dict)) { - PyObject* ret = PyDict_SetDefault(dict, key, value); - Py_XINCREF(ret); + PyObject *ret; + if (PyDict_SetDefaultRef(dict, key, value, &ret) < 0) { + return NULL; + } return ret; } return PyObject_CallMethodObjArgs(dict, mypyc_interned_str.setdefault, key, value, NULL); @@ -85,42 +87,31 @@ PyObject *CPyDict_SetDefaultWithNone(PyObject *dict, PyObject *key) { PyObject *CPyDict_SetDefaultWithEmptyDatatype(PyObject *dict, PyObject *key, int data_type) { - PyObject *res; if (PyDict_CheckExact(dict)) { + // Fast path: avoid creating the empty collection if the key exists + PyObject *res; int found = PyDict_GetItemRef(dict, key, &res); - if (found < 0) { - return NULL; + if (found != 0) { + return res; } + } + PyObject *new_obj; + if (data_type == 1) { + new_obj = PyList_New(0); + } else if (data_type == 2) { + new_obj = PyDict_New(); + } else if (data_type == 3) { + new_obj = PySet_New(NULL); } else { - res = PyObject_GetItem(dict, key); - if (!res) { - if (!PyErr_ExceptionMatches(PyExc_KeyError)) { - return NULL; - } - PyErr_Clear(); - } + new_obj = NULL; } - if (!res) { - PyObject *new_obj; - if (data_type == 1) { - new_obj = PyList_New(0); - } else if (data_type == 2) { - new_obj = PyDict_New(); - } else if (data_type == 3) { - new_obj = PySet_New(NULL); - } else { - new_obj = NULL; - } - - if (new_obj == NULL) { - res = NULL; - } else if (CPyDict_SetItem(dict, key, new_obj) == -1) { - Py_DECREF(new_obj); - res = NULL; - } else { - res = new_obj; - } + if (new_obj == NULL) { + return NULL; } + // Use setdefault (not get + set) so that this is atomic for exact dicts + // on free-threaded builds and respects overridden methods in subclasses + PyObject *res = CPyDict_SetDefault(dict, key, new_obj); + Py_DECREF(new_obj); return res; } diff --git a/mypyc/test-data/run-dicts.test b/mypyc/test-data/run-dicts.test index 609c21bbcf21a..8d5248de7899a 100644 --- a/mypyc/test-data/run-dicts.test +++ b/mypyc/test-data/run-dicts.test @@ -365,6 +365,44 @@ def test_lookup_error_propagation() -> None: assert d == {} assert default(d, "present") is default(d, "present") +def test_empty_collection_setdefault_subclass() -> None: + from collections import Counter + from dictsubclasses import MissingDict, SetDefaultDict + + for default, empty in ((default_list, []), (default_dict, {}), (default_set, set())): + # Counter.__missing__ returns 0, but setdefault must still insert + d: Dict[Any, Any] = Counter() + assert default(d, "x") == empty + assert d == {"x": empty} + assert default(d, "x") is d["x"] + + # __missing__ isn't used by setdefault + d = MissingDict() + assert default(d, "x") == empty + assert d == {"x": empty} + + sd = SetDefaultDict() + assert default(sd, "x") == empty + assert sd.calls == [("x", empty)] + assert sd == {} + + d = defaultdict(int) + assert default(d, "x") == empty + assert d == {"x": empty} + +[file dictsubclasses.py] +class MissingDict(dict): + def __missing__(self, key): + return "missing" + +class SetDefaultDict(dict): + def __init__(self): + self.calls = [] + + def setdefault(self, key, default=None): + self.calls.append((key, default)) + return default + [case testDictToBool] from typing import Dict, List