From 8295a5eaec579bfdb6129edbb0afe6c661da0c3d Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 16:04:46 +0500 Subject: [PATCH] [mypyc] Fix unchecked results of operations on overriding subclasses Several primitives declare an exact return type (str, list, tuple or dict), but can call a method overridden in a Python subclass, and the result was trusted without a type check. For example, if a list subclass defines __add__ that returns an int, `c = a + b; c[0]` with `a: list[int]` would crash. For list and tuple +, +=, *, *= and list.copy(), and dict.copy(), keep calling the override but raise TypeError if the result has the wrong type. Also call __rmul__ instead of __mul__ for `n * seq` when seq is a list or tuple subclass. For str * int and str.lower()/str.upper() (non-ASCII, Python 3.13+), always use the str implementation, so the result is an exact str. This matches how other str primitives such as str + str already work. --- mypyc/lib-rt/CPy.h | 2 + mypyc/lib-rt/dict_ops.c | 9 +++- mypyc/lib-rt/list_ops.c | 47 +++++++++++++++-- mypyc/lib-rt/str_ops.c | 8 ++- mypyc/primitives/list_ops.py | 4 +- mypyc/primitives/tuple_ops.py | 2 +- mypyc/test-data/irbuild-lists.test | 4 +- mypyc/test-data/irbuild-tuple.test | 6 +-- mypyc/test-data/run-dicts.test | 29 +++++++++++ mypyc/test-data/run-lists.test | 83 ++++++++++++++++++++++++++++++ mypyc/test-data/run-strings.test | 48 +++++++++++++++++ mypyc/test-data/run-tuples.test | 50 ++++++++++++++++++ 12 files changed, 277 insertions(+), 15 deletions(-) diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..eeb0867515e51 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -939,6 +939,8 @@ PyObject *CPyList_Extend(PyObject *o1, PyObject *o2); int CPyList_Remove(PyObject *list, PyObject *obj); CPyTagged CPyList_Index(PyObject *list, PyObject *obj); PyObject *CPySequence_Sort(PyObject *seq); +PyObject *CPySequence_Concat(PyObject *seq, PyObject *other); +PyObject *CPySequence_InPlaceConcat(PyObject *seq, PyObject *other); PyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size); PyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq); PyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size); diff --git a/mypyc/lib-rt/dict_ops.c b/mypyc/lib-rt/dict_ops.c index 5c1d0c7a48e98..bac5e179fcc9f 100644 --- a/mypyc/lib-rt/dict_ops.c +++ b/mypyc/lib-rt/dict_ops.c @@ -281,7 +281,14 @@ PyObject *CPyDict_Copy(PyObject *dict) { if (PyDict_CheckExact(dict)) { return PyDict_Copy(dict); } - return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.copy); + PyObject *res = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.copy); + // An overriding method in a subclass can return an arbitrary object + if (res != NULL && !PyDict_Check(res)) { + CPy_TypeError("dict", res); + Py_DECREF(res); + return NULL; + } + return res; } PyObject *CPyDict_GetKeysIter(PyObject *dict) { diff --git a/mypyc/lib-rt/list_ops.c b/mypyc/lib-rt/list_ops.c index 9e4a64d48064f..27f57d1008621 100644 --- a/mypyc/lib-rt/list_ops.c +++ b/mypyc/lib-rt/list_ops.c @@ -48,11 +48,35 @@ char CPyList_Clear(PyObject *list) { return 1; } +// Operations on list and tuple subclasses may call an overriding method that returns an +// arbitrary object. Check that the result is a list if seq is a list, or a tuple otherwise +// (only lists and tuples are supported), since callers rely on the result type. +static PyObject *CPySequence_CheckResult(PyObject *seq, PyObject *res) { + if (res == NULL) { + return NULL; + } + const char *expected; + if (PyList_Check(seq)) { + if (PyList_Check(res)) { + return res; + } + expected = "list"; + } else { + if (PyTuple_Check(res)) { + return res; + } + expected = "tuple"; + } + CPy_TypeError(expected, res); + Py_DECREF(res); + return NULL; +} + PyObject *CPyList_Copy(PyObject *list) { if(PyList_CheckExact(list)) { return PyList_GetSlice(list, 0, PyList_GET_SIZE(list)); } - return PyObject_CallMethodNoArgs(list, mypyc_interned_str.copy); + return CPySequence_CheckResult(list, PyObject_CallMethodNoArgs(list, mypyc_interned_str.copy)); } #ifndef Py_GIL_DISABLED @@ -424,16 +448,31 @@ PyObject *CPySequence_Sort(PyObject *seq) { return newlist; } +PyObject *CPySequence_Concat(PyObject *seq, PyObject *other) { + return CPySequence_CheckResult(seq, PySequence_Concat(seq, other)); +} + +PyObject *CPySequence_InPlaceConcat(PyObject *seq, PyObject *other) { + return CPySequence_CheckResult(seq, PySequence_InPlaceConcat(seq, other)); +} + PyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size) { Py_ssize_t size = CPyTagged_AsSsize_t(t_size); if (size == -1 && PyErr_Occurred()) { return NULL; } - return PySequence_Repeat(seq, size); + return CPySequence_CheckResult(seq, PySequence_Repeat(seq, size)); } PyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq) { - return CPySequence_Multiply(seq, t_size); + if (PyList_CheckExact(seq) || PyTuple_CheckExact(seq)) { + return CPySequence_Multiply(seq, t_size); + } + // Use the generic operation so that __rmul__ is called on subclasses + PyObject *size = CPyTagged_AsObject(t_size); + PyObject *res = PyNumber_Multiply(size, seq); + Py_DECREF(size); + return CPySequence_CheckResult(seq, res); } PyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size) { @@ -441,7 +480,7 @@ PyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size) { if (size == -1 && PyErr_Occurred()) { return NULL; } - return PySequence_InPlaceRepeat(seq, size); + return CPySequence_CheckResult(seq, PySequence_InPlaceRepeat(seq, size)); } PyObject *CPyList_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { diff --git a/mypyc/lib-rt/str_ops.c b/mypyc/lib-rt/str_ops.c index 9e3d494868017..e5d284314b3f3 100644 --- a/mypyc/lib-rt/str_ops.c +++ b/mypyc/lib-rt/str_ops.c @@ -646,7 +646,9 @@ PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) { PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG); return NULL; } - return PySequence_Repeat(str, temp_count); + // Use the str implementation directly (like PyUnicode_Concat does for str + str), so + // that the result is always an exact str even if a subclass overrides __mul__. + return PyUnicode_Type.tp_as_sequence->sq_repeat(str, temp_count); } @@ -728,7 +730,9 @@ static inline PyObject *CPyStr_ChangeCase(PyObject *self, #if CPY_3_13_FEATURES // On 3.13+, _PyUnicode_ToLowerFull/ToUpperFull are no longer exported, // so fall back to CPython's method implementation for non-ASCII strings. - return PyObject_CallMethodNoArgs(self, method_name); + // The method is looked up on str (not on the type of self), so that the + // result is always an exact str even if a subclass overrides it. + return PyObject_CallMethodOneArg((PyObject *)&PyUnicode_Type, method_name, self); #else // General Unicode: unicode_func handles 1-to-N expansion. // Worst case: each codepoint expands to 3 (per Unicode standard). diff --git a/mypyc/primitives/list_ops.py b/mypyc/primitives/list_ops.py index f5548e88592f1..3f9e1a8b82643 100644 --- a/mypyc/primitives/list_ops.py +++ b/mypyc/primitives/list_ops.py @@ -308,7 +308,7 @@ name="+", arg_types=[list_rprimitive, list_rprimitive], return_type=list_rprimitive, - c_function_name="PySequence_Concat", + c_function_name="CPySequence_Concat", error_kind=ERR_MAGIC, ) @@ -317,7 +317,7 @@ name="+=", arg_types=[list_rprimitive, object_rprimitive], return_type=list_rprimitive, - c_function_name="PySequence_InPlaceConcat", + c_function_name="CPySequence_InPlaceConcat", error_kind=ERR_MAGIC, ) diff --git a/mypyc/primitives/tuple_ops.py b/mypyc/primitives/tuple_ops.py index ab23f8c441f5b..09daf5396bf0c 100644 --- a/mypyc/primitives/tuple_ops.py +++ b/mypyc/primitives/tuple_ops.py @@ -105,7 +105,7 @@ name="+", arg_types=[tuple_rprimitive, tuple_rprimitive], return_type=tuple_rprimitive, - c_function_name="PySequence_Concat", + c_function_name="CPySequence_Concat", error_kind=ERR_MAGIC, ) diff --git a/mypyc/test-data/irbuild-lists.test b/mypyc/test-data/irbuild-lists.test index 44ce501756308..9587ae1c41e6a 100644 --- a/mypyc/test-data/irbuild-lists.test +++ b/mypyc/test-data/irbuild-lists.test @@ -171,7 +171,7 @@ def f(a: List[int], b: List[int]) -> None: def f(a, b): a, b, r0, c :: list L0: - r0 = PySequence_Concat(a, b) + r0 = CPySequence_Concat(a, b) c = r0 return 1 @@ -185,7 +185,7 @@ def f(a, b): b :: object r0 :: list L0: - r0 = PySequence_InPlaceConcat(a, b) + r0 = CPySequence_InPlaceConcat(a, b) a = r0 return 1 diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index 2cb6fac30b22e..56a57b04a6b07 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -1101,11 +1101,11 @@ def f(a, b): r2 :: object r3, d :: tuple L0: - r0 = PySequence_Concat(a, b) + r0 = CPySequence_Concat(a, b) c = r0 r1 = (2, 4) r2 = box(tuple[int, int], r1) - r3 = PySequence_Concat(a, r2) + r3 = CPySequence_Concat(a, r2) d = r3 return 1 def g(a, b): @@ -1116,7 +1116,7 @@ def g(a, b): L0: r0 = box(tuple[int, int], a) r1 = box(tuple[int, int], b) - r2 = PySequence_Concat(r0, r1) + r2 = CPySequence_Concat(r0, r1) r3 = unbox(tuple[int, int, int, int], r2) c = r3 return 1 diff --git a/mypyc/test-data/run-dicts.test b/mypyc/test-data/run-dicts.test index 609c21bbcf21a..c817bb8e9f4b3 100644 --- a/mypyc/test-data/run-dicts.test +++ b/mypyc/test-data/run-dicts.test @@ -630,3 +630,32 @@ for convert in (keys, values, items): gc.collect() assert all(ref() is None for ref in refs) assert convert(CustomDict(iter([1, 2]))) == [1, 2] + +[case testDictCopyOverridingSubclass] +from typing import Dict +from testutil import assertRaises +from dictsub import BadDict, GoodDict + +def copy(d: Dict[int, int]) -> Dict[int, int]: + return d.copy() + +def test_bad_result_type() -> None: + d: Dict[int, int] = BadDict({1: 2}) + with assertRaises(TypeError, "dict object expected; got int"): + copy(d) + +def test_override_called() -> None: + d: Dict[int, int] = GoodDict({1: 2}) + assert copy(d) == {1: 2, 3: 4} + assert type(copy(d)) is GoodDict + +[file dictsub.py] +from typing import Any + +class BadDict(dict): + def copy(self) -> Any: + return 1 + +class GoodDict(dict): + def copy(self) -> Any: + return GoodDict({**self, 3: 4}) diff --git a/mypyc/test-data/run-lists.test b/mypyc/test-data/run-lists.test index ccb24de3514f9..623244f6f9852 100644 --- a/mypyc/test-data/run-lists.test +++ b/mypyc/test-data/run-lists.test @@ -731,3 +731,86 @@ for index in (0, -1): items = [Reentrant()] assign(items, index, None) assert items == [] + +[case testListOpsOverridingSubclass] +from typing import List +from testutil import assertRaises +from listsub import BadList, GoodList + +def add(a: List[int], b: List[int]) -> List[int]: + return a + b + +def iadd(a: List[int], b: List[int]) -> List[int]: + a += b + return a + +def mul(a: List[int], n: int) -> List[int]: + return a * n + +def rmul(a: List[int], n: int) -> List[int]: + return n * a + +def imul(a: List[int], n: int) -> List[int]: + a *= n + return a + +def copy(a: List[int]) -> List[int]: + return a.copy() + +def test_bad_result_type() -> None: + a: List[int] = BadList([1]) + with assertRaises(TypeError, "list object expected; got int"): + add(a, [2]) + with assertRaises(TypeError, "list object expected; got int"): + iadd(a, [2]) + with assertRaises(TypeError, "list object expected; got int"): + mul(a, 2) + with assertRaises(TypeError, "list object expected; got int"): + rmul(a, 2) + with assertRaises(TypeError, "list object expected; got int"): + imul(a, 2) + with assertRaises(TypeError, "list object expected; got int"): + copy(a) + +def test_overrides_called() -> None: + a: List[int] = GoodList([1]) + assert add(a, [2]) == [1, 2, 0] + assert iadd(a, [2]) == [1, 2, 1] + assert mul(a, 2) == [1, 1, 2] + assert rmul(a, 2) == [1, 1, 3] + assert imul(a, 2) == [1, 1, 4] + assert copy(a) == [1, 5] + assert type(copy(a)) is GoodList + assert a == [1] + assert rmul([1], 2) == [1, 1] + +[file listsub.py] +from typing import Any + +class BadList(list): + def __add__(self, other: Any) -> Any: + return 1 + def __iadd__(self, other: Any) -> Any: + return 2 + def __mul__(self, n: Any) -> Any: + return 3 + def __rmul__(self, n: Any) -> Any: + return 4 + def __imul__(self, n: Any) -> Any: + return 5 + def copy(self) -> Any: + return 6 + +class GoodList(list): + def __add__(self, other: Any) -> Any: + return GoodList(list(self) + other + [0]) + def __iadd__(self, other: Any) -> Any: + return GoodList(list(self) + other + [1]) + def __mul__(self, n: Any) -> Any: + return GoodList(list(self) * n + [2]) + def __rmul__(self, n: Any) -> Any: + return GoodList(list(self) * n + [3]) + def __imul__(self, n: Any) -> Any: + return GoodList(list(self) * n + [4]) + def copy(self) -> Any: + return GoodList(list(self) + [5]) diff --git a/mypyc/test-data/run-strings.test b/mypyc/test-data/run-strings.test index f26b160d816c1..4b75aa695fa5d 100644 --- a/mypyc/test-data/run-strings.test +++ b/mypyc/test-data/run-strings.test @@ -1470,3 +1470,51 @@ def test_out_of_range_raises_indexerror() -> None: eq_comma(s, 3) with assertRaises(IndexError): eq_comma(s, -4) + +[case testStrOpsOverridingSubclass] +from strsub import StrOverride + +def mul(s: str, n: int) -> str: + return s * n + +def rmul(s: str, n: int) -> str: + return n * s + +def lower(s: str) -> str: + return s.lower() + +def upper(s: str) -> str: + return s.upper() + +def test_multiply() -> None: + # Overrides aren't used, and the result is always an exact str + for s in ["", "a", "ab\xe9"]: + sub: str = StrOverride(s) + for n in [-1, 0, 1, 3]: + for res in [mul(sub, n), rmul(sub, n)]: + assert type(res) is str + assert res == s * n + assert len(res) == len(s * n) + +def test_lower_upper() -> None: + for s in ["Hello", "\xc9cole Σ", "İ", "\xdf"]: + sub: str = StrOverride(s) + assert type(lower(sub)) is str + assert lower(sub) == s.lower() + assert len(lower(sub)) == len(s.lower()) + assert type(upper(sub)) is str + assert upper(sub) == s.upper() + assert len(upper(sub)) == len(s.upper()) + +[file strsub.py] +from typing import Any + +class StrOverride(str): + def __mul__(self, n: Any) -> Any: + return 12345678901234567890 + def __rmul__(self, n: Any) -> Any: + return 12345678901234567891 + def lower(self) -> Any: + return 12345678901234567892 + def upper(self) -> Any: + return 12345678901234567893 diff --git a/mypyc/test-data/run-tuples.test b/mypyc/test-data/run-tuples.test index e7ab8ee09b174..a04b89a5070d3 100644 --- a/mypyc/test-data/run-tuples.test +++ b/mypyc/test-data/run-tuples.test @@ -467,3 +467,53 @@ class subc(tuple[Any, ...]): [file userdefinedtuple.py] class tuple: pass + +[case testTupleOpsOverridingSubclass] +from typing import Tuple +from testutil import assertRaises +from tuplesub import BadTuple, GoodTuple + +def add(a: Tuple[int, ...], b: Tuple[int, ...]) -> Tuple[int, ...]: + return a + b + +def mul(a: Tuple[int, ...], n: int) -> Tuple[int, ...]: + return a * n + +def rmul(a: Tuple[int, ...], n: int) -> Tuple[int, ...]: + return n * a + +def test_bad_result_type() -> None: + a: Tuple[int, ...] = BadTuple((1,)) + with assertRaises(TypeError, "tuple object expected; got int"): + add(a, (2,)) + with assertRaises(TypeError, "tuple object expected; got int"): + mul(a, 2) + with assertRaises(TypeError, "tuple object expected; got int"): + rmul(a, 2) + +def test_overrides_called() -> None: + a: Tuple[int, ...] = GoodTuple((1,)) + assert add(a, (2,)) == (1, 2, 0) + assert mul(a, 2) == (1, 1, 2) + assert rmul(a, 2) == (1, 1, 3) + assert type(rmul(a, 2)) is GoodTuple + assert rmul((1,), 2) == (1, 1) + +[file tuplesub.py] +from typing import Any + +class BadTuple(tuple): + def __add__(self, other: Any) -> Any: + return 1 + def __mul__(self, n: Any) -> Any: + return 2 + def __rmul__(self, n: Any) -> Any: + return 3 + +class GoodTuple(tuple): + def __add__(self, other: Any) -> Any: + return GoodTuple(tuple(self) + other + (0,)) + def __mul__(self, n: Any) -> Any: + return GoodTuple(tuple(self) * n + (2,)) + def __rmul__(self, n: Any) -> Any: + return GoodTuple(tuple(self) * n + (3,))