From 1e677463f278bd841d3b1e1ba0cbf13e08ca6368 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Tue, 10 Nov 2026 22:08:14 +0500 Subject: [PATCH 1/2] [mypyc] Fix unchecked results of bytes operations on overriding subclasses bytes * int, int * bytes, bytes.join() and bytes.translate() call the overriding method if the object is a bytes subclass, but the result was trusted to be bytes without a check. For example, if a bytes subclass defines __mul__ that returns an int, `r = b * 2; len(r)` with `b: bytes` would read the int object as bytes. Keep calling the override, but raise TypeError if the result is not bytes, as is already done for list and tuple operations. Also call __rmul__ instead of __mul__ for `n * b` when b is a bytes subclass. --- mypyc/lib-rt/CPy.h | 2 + mypyc/lib-rt/bytes_extra_ops.c | 3 +- mypyc/lib-rt/bytes_ops.c | 31 +++++++++++++-- mypyc/primitives/bytes_ops.py | 3 +- mypyc/test-data/irbuild-bytes.test | 2 +- mypyc/test-data/run-bytes.test | 61 ++++++++++++++++++++++++++++++ 6 files changed, 94 insertions(+), 8 deletions(-) diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index d4bd2d8938ce1..4eb54a7e23779 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1119,6 +1119,8 @@ PyObject *CPyBytes_Concat(PyObject *a, PyObject *b); PyObject *CPyBytes_Join(PyObject *sep, PyObject *iter); CPyTagged CPyBytes_Ord(PyObject *obj); PyObject *CPyBytes_Multiply(PyObject *bytes, CPyTagged count); +PyObject *CPyBytes_RMultiply(CPyTagged count, PyObject *bytes); +PyObject *CPyBytes_CheckResult(PyObject *res); int CPyBytes_Startswith(PyObject *self, PyObject *subobj); int CPyBytes_Endswith(PyObject *self, PyObject *subobj); int CPyBytes_Compare(PyObject *left, PyObject *right); diff --git a/mypyc/lib-rt/bytes_extra_ops.c b/mypyc/lib-rt/bytes_extra_ops.c index 511ac07329767..ae9e61b1cffab 100644 --- a/mypyc/lib-rt/bytes_extra_ops.c +++ b/mypyc/lib-rt/bytes_extra_ops.c @@ -41,5 +41,6 @@ PyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table) { } // Fallback to Python method call for non-exact types or non-standard tables - return PyObject_CallMethodOneArg(bytes, mypyc_interned_str.translate, table); + return CPyBytes_CheckResult( + PyObject_CallMethodOneArg(bytes, mypyc_interned_str.translate, table)); } diff --git a/mypyc/lib-rt/bytes_ops.c b/mypyc/lib-rt/bytes_ops.c index dc05131b1e5d5..9923786394f8a 100644 --- a/mypyc/lib-rt/bytes_ops.c +++ b/mypyc/lib-rt/bytes_ops.c @@ -90,13 +90,25 @@ PyObject *CPyBytes_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { return CPyObject_GetSlice(obj, start, end); } -// Like _PyBytes_Join but fallback to dynamic call if 'sep' is not bytes -// (mostly commonly, for bytearrays) +// An overriding method in a bytes subclass can return an arbitrary object. Check that +// the result is bytes, since callers rely on the result type. +PyObject *CPyBytes_CheckResult(PyObject *res) { + if (res != NULL && !PyBytes_Check(res)) { + CPy_TypeError("bytes", res); + Py_DECREF(res); + return NULL; + } + return res; +} + +// Like _PyBytes_Join but fallback to dynamic call if 'sep' is not exact bytes +// (a subclass may override join) PyObject *CPyBytes_Join(PyObject *sep, PyObject *iter) { if (PyBytes_CheckExact(sep)) { return PyBytes_Join(sep, iter); } else { - return PyObject_CallMethodOneArg(sep, mypyc_interned_str.join, iter); + return CPyBytes_CheckResult( + PyObject_CallMethodOneArg(sep, mypyc_interned_str.join, iter)); } } @@ -151,7 +163,18 @@ PyObject *CPyBytes_Multiply(PyObject *bytes, CPyTagged count) { PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG); return NULL; } - return PySequence_Repeat(bytes, temp_count); + return CPyBytes_CheckResult(PySequence_Repeat(bytes, temp_count)); +} + +PyObject *CPyBytes_RMultiply(CPyTagged count, PyObject *bytes) { + if (PyBytes_CheckExact(bytes)) { + return CPyBytes_Multiply(bytes, count); + } + // Use the generic operation so that __rmul__ is called on subclasses + PyObject *count_obj = CPyTagged_AsObject(count); + PyObject *res = PyNumber_Multiply(count_obj, bytes); + Py_DECREF(count_obj); + return CPyBytes_CheckResult(res); } int CPyBytes_Startswith(PyObject *self, PyObject *subobj) { diff --git a/mypyc/primitives/bytes_ops.py b/mypyc/primitives/bytes_ops.py index 96e8069f317ed..3b1b08613a253 100644 --- a/mypyc/primitives/bytes_ops.py +++ b/mypyc/primitives/bytes_ops.py @@ -80,9 +80,8 @@ name="*", arg_types=[int_rprimitive, bytes_rprimitive], return_type=bytes_rprimitive, - c_function_name="CPyBytes_Multiply", + c_function_name="CPyBytes_RMultiply", error_kind=ERR_MAGIC, - ordering=[1, 0], ) # bytes[begin:end] diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 9f9d14c291b15..6338840f31290 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -348,7 +348,7 @@ def i_times_b(s, n): n :: int r0 :: bytes L0: - r0 = CPyBytes_Multiply(s, n) + r0 = CPyBytes_RMultiply(n, s) return r0 [case testBytesTranslate] diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index c26ae9142bd0d..96acaa26cb146 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -744,3 +744,64 @@ def test_optional_ne() -> None: assert ne_b_b_opt(b'x', b'y') assert ne_b_b_opt(b'y', b'x') assert ne_b_b_opt(b'x', None) + +[case testBytesOpsOverridingSubclass] +from testutil import assertRaises +from bytessub import BadBytes, GoodBytes + +def mul(b: bytes, n: int) -> bytes: + return b * n + +def rmul(b: bytes, n: int) -> bytes: + return n * b + +def join(b: bytes) -> bytes: + return b.join([b'a', b'b']) + +def translate(b: bytes, table: bytes) -> bytes: + return b.translate(table) + +table = bytes(range(256)) + +def test_bad_result_type() -> None: + b: bytes = BadBytes(b'x') + with assertRaises(TypeError, "bytes object expected; got int"): + mul(b, 2) + with assertRaises(TypeError, "bytes object expected; got int"): + rmul(b, 2) + with assertRaises(TypeError, "bytes object expected; got int"): + join(b) + with assertRaises(TypeError, "bytes object expected; got int"): + translate(b, table) + +def test_overrides_called() -> None: + b: bytes = GoodBytes(b'x') + assert mul(b, 2) == b'xx!' + assert rmul(b, 2) == b'xx?' + assert type(rmul(b, 2)) is GoodBytes + assert join(b) == b'axb.' + assert translate(b, table) == b'x#' + assert rmul(b'x', 2) == b'xx' + +[file bytessub.py] +from typing import Any + +class BadBytes(bytes): + def __mul__(self, n: Any) -> Any: + return 12345678901234567890 + def __rmul__(self, n: Any) -> Any: + return 12345678901234567891 + def join(self, it: Any) -> Any: + return 12345678901234567892 + def translate(self, table: Any, delete: Any = b'') -> Any: + return 12345678901234567893 + +class GoodBytes(bytes): + def __mul__(self, n: Any) -> Any: + return bytes(self) * n + b'!' + def __rmul__(self, n: Any) -> Any: + return GoodBytes(n * bytes(self) + b'?') + def join(self, it: Any) -> Any: + return bytes(self).join(it) + b'.' + def translate(self, table: Any, delete: Any = b'') -> Any: + return bytes(self).translate(table) + b'#' From 82663371919ffccc345c2a8bfdc6349da8782ea7 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Wed, 11 Nov 2026 16:49:31 +0500 Subject: [PATCH 2/2] Check the result of bytes slicing on overriding subclasses CPyBytes_GetSlice falls back to the generic slicing operation for indices that don't fit in a short int, which calls __getitem__ on a bytes subclass. Raise TypeError if the result is not bytes. --- mypyc/lib-rt/bytes_ops.c | 2 +- mypyc/test-data/run-bytes.test | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/mypyc/lib-rt/bytes_ops.c b/mypyc/lib-rt/bytes_ops.c index 9923786394f8a..03fc41a6ad832 100644 --- a/mypyc/lib-rt/bytes_ops.c +++ b/mypyc/lib-rt/bytes_ops.c @@ -87,7 +87,7 @@ PyObject *CPyBytes_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(obj) + startn, slice_len); } } - return CPyObject_GetSlice(obj, start, end); + return CPyBytes_CheckResult(CPyObject_GetSlice(obj, start, end)); } // An overriding method in a bytes subclass can return an arbitrary object. Check that diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index 96acaa26cb146..640367b681c06 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -761,6 +761,11 @@ def join(b: bytes) -> bytes: def translate(b: bytes, table: bytes) -> bytes: return b.translate(table) +def get_slice(b: bytes, start: int, end: int) -> bytes: + return b[start:end] + +BIG = 1 << 70 + table = bytes(range(256)) def test_bad_result_type() -> None: @@ -773,6 +778,10 @@ def test_bad_result_type() -> None: join(b) with assertRaises(TypeError, "bytes object expected; got int"): translate(b, table) + with assertRaises(TypeError, "bytes object expected; got int"): + get_slice(b, 0, BIG) + with assertRaises(TypeError, "bytes object expected; got int"): + get_slice(b, -BIG, 1) def test_overrides_called() -> None: b: bytes = GoodBytes(b'x') @@ -781,6 +790,7 @@ def test_overrides_called() -> None: assert type(rmul(b, 2)) is GoodBytes assert join(b) == b'axb.' assert translate(b, table) == b'x#' + assert get_slice(b, 0, BIG) == b'x^' assert rmul(b'x', 2) == b'xx' [file bytessub.py] @@ -795,6 +805,8 @@ class BadBytes(bytes): return 12345678901234567892 def translate(self, table: Any, delete: Any = b'') -> Any: return 12345678901234567893 + def __getitem__(self, i: Any) -> Any: + return 12345678901234567894 class GoodBytes(bytes): def __mul__(self, n: Any) -> Any: @@ -805,3 +817,5 @@ class GoodBytes(bytes): return bytes(self).join(it) + b'.' def translate(self, table: Any, delete: Any = b'') -> Any: return bytes(self).translate(table) + b'#' + def __getitem__(self, i: Any) -> Any: + return bytes(self)[i] + b'^'