From e0492177808b36fc64c283c6cf0f2dbe31c33b67 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:40:04 +0500 Subject: [PATCH 1/3] [mypyc] Fix crash on generator.throw() with invalid arguments The generated throw() method passed its arguments to the generator body without validation, so throwing a non-exception (such as gen.throw(5)) segfaulted, and other invalid argument combinations raised a TypeError inside the generator, where an except clause could catch it. Check the arguments like CPython's _gen_throw does before resuming the generator: the first argument must be an exception class or instance, an exception instance may not have a separate value, and the traceback must be a traceback object or None. --- mypyc/irbuild/generator.py | 8 +++ mypyc/lib-rt/CPy.h | 1 + mypyc/lib-rt/exc_ops.c | 23 ++++++++ mypyc/primitives/exc_ops.py | 8 +++ mypyc/test-data/run-generators.test | 81 +++++++++++++++++++++++++++++ 5 files changed, 121 insertions(+) diff --git a/mypyc/irbuild/generator.py b/mypyc/irbuild/generator.py index a5b8bf4f56b11..b56decebe553e 100644 --- a/mypyc/irbuild/generator.py +++ b/mypyc/irbuild/generator.py @@ -58,6 +58,7 @@ from mypyc.irbuild.nonlocalcontrol import ExceptNonlocalControl, gen_generator_func_cleanup from mypyc.irbuild.targets import AssignmentTargetAttr from mypyc.primitives.exc_ops import ( + check_throw_args_op, error_catch_op, exc_matches_op, raise_exception_with_tb_op, @@ -332,6 +333,13 @@ def add_throw_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: builder.assign_if_null(val, lambda: none_reg, fn_info.fitem.line) builder.assign_if_null(tb, lambda: none_reg, fn_info.fitem.line) + # Reject invalid arguments before resuming the generator. + builder.call_c( + check_throw_args_op, + [builder.read(typ), builder.read(val), builder.read(tb)], + fn_info.fitem.line, + ) + # Call the helper function using the arguments passed in, and return that result. result = builder.add( Call( diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..dfd7a9ae2f76c 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1140,6 +1140,7 @@ void CPy_Raise(PyObject *exc); void CPy_RaiseFrom(PyObject *exc, PyObject *cause); void CPy_Reraise(void); void CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *traceback); +bool CPyGen_CheckThrowArgs(PyObject *type, PyObject *value, PyObject *traceback); tuple_T3OOO CPy_CatchError(void); void CPy_RestoreExcInfo(tuple_T3OOO info); bool CPy_ExceptionMatches(PyObject *type); diff --git a/mypyc/lib-rt/exc_ops.c b/mypyc/lib-rt/exc_ops.c index ea14fceb2e2f2..5dbbf79548842 100644 --- a/mypyc/lib-rt/exc_ops.c +++ b/mypyc/lib-rt/exc_ops.c @@ -96,6 +96,29 @@ void CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *tra PyErr_Restore(type, value, traceback); } +// Validate the arguments of generator.throw() before resuming the generator, like +// CPython's _gen_throw. Return false and set an error if they are invalid. +bool CPyGen_CheckThrowArgs(PyObject *type, PyObject *value, PyObject *traceback) { + if (!Py_IsNone(traceback) && !PyTraceBack_Check(traceback)) { + PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback object"); + return false; + } + if (PyExceptionClass_Check(type)) { + return true; + } + if (PyExceptionInstance_Check(type)) { + if (!Py_IsNone(value)) { + PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); + return false; + } + return true; + } + PyErr_Format(PyExc_TypeError, + "exceptions must be classes or instances deriving from BaseException, not %s", + Py_TYPE(type)->tp_name); + return false; +} + tuple_T3OOO CPy_CatchError(void) { // We need to return the existing sys.exc_info() information, so // that it can be restored when we finish handling the error we diff --git a/mypyc/primitives/exc_ops.py b/mypyc/primitives/exc_ops.py index 528a89ef23310..655cf5cc66002 100644 --- a/mypyc/primitives/exc_ops.py +++ b/mypyc/primitives/exc_ops.py @@ -40,6 +40,14 @@ error_kind=ERR_ALWAYS, ) +# Check that the (type, value, traceback) arguments of generator.throw() are valid. +check_throw_args_op = custom_op( + arg_types=[object_rprimitive, object_rprimitive, object_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyGen_CheckThrowArgs", + error_kind=ERR_FALSE, +) + # Reraise the currently raised exception. reraise_exception_op = custom_op( arg_types=[], return_type=void_rtype, c_function_name="CPy_Reraise", error_kind=ERR_ALWAYS diff --git a/mypyc/test-data/run-generators.test b/mypyc/test-data/run-generators.test index 8db09584ed612..7f4e4023a4205 100644 --- a/mypyc/test-data/run-generators.test +++ b/mypyc/test-data/run-generators.test @@ -1581,3 +1581,84 @@ g2 = gen_delegate(reenter()) box.append(g2) assert pyiter_send(g2, None) == (PYGEN_NEXT, 2) assert pyiter_send(g2, None) == (PYGEN_RETURN, None) + +[case testGeneratorThrowInvalidArguments] +from typing import Any, Generator + +from testutil import assertRaises + +def gen() -> Generator[Any, None, None]: + while True: + try: + yield 1 + except BaseException as e: + yield "caught " + type(e).__name__ + +async def coro() -> int: + return 1 + +def started() -> Any: + g = gen() + assert next(g) == 1 + return g + +def test_valid_arguments() -> None: + g = started() + assert g.throw(ValueError) == "caught ValueError" + assert next(g) == 1 + assert g.throw(ValueError, "x") == "caught ValueError" + assert next(g) == 1 + assert g.throw(ValueError("x"), None) == "caught ValueError" + assert next(g) == 1 + try: + raise KeyError + except KeyError as e: + tb = getattr(e, "__traceback__") + assert g.throw(ValueError, ValueError("x"), tb) == "caught ValueError" + assert next(g) == 1 + assert g.throw(ValueError("x"), None, None) == "caught ValueError" + +# The errors must be raised by throw() without resuming the generator, so the except +# clause in gen() doesn't see them. + +def test_invalid_traceback() -> None: + g = started() + with assertRaises(TypeError, "throw() third argument must be a traceback object"): + g.throw(ValueError, None, 42) + assert next(g) == 1 + +def test_instance_with_separate_value() -> None: + g = started() + with assertRaises(TypeError, "instance exception may not have a separate value"): + g.throw(ValueError("x"), 5) + assert next(g) == 1 + +def test_non_exception_class() -> None: + g = started() + with assertRaises( + TypeError, "exceptions must be classes or instances deriving from BaseException, not type" + ): + g.throw(int) + assert next(g) == 1 + +def test_non_exception_instance() -> None: + g = started() + msg = "exceptions must be classes or instances deriving from BaseException, not " + with assertRaises(TypeError, msg + "int"): + g.throw(5) + with assertRaises(TypeError, msg + "object"): + g.throw(object()) + assert next(g) == 1 + + # Not yet started + g2: Any = gen() + with assertRaises(TypeError, msg + "int"): + g2.throw(5) + assert next(g2) == 1 + +def test_coroutine() -> None: + c: Any = coro() + with assertRaises(TypeError, "exceptions must be classes or instances"): + c.throw(5) + with assertRaises(StopIteration): + c.send(None) From 4a8147e480324b7b8b8d6d6f003044bd6d305779 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:40:55 +0500 Subject: [PATCH 2/3] [mypyc] Fix bare raise with no active exception CPy_Reraise passed the handled exception to PyErr_Restore even when there was none. This segfaulted on Python 3.10, left the error state corrupted on 3.11 and raised "TypeError: 'NoneType' object is not callable" on 3.12+. Raise "RuntimeError: No active exception to reraise" instead, like CPython. --- mypyc/lib-rt/exc_ops.c | 7 +++++ mypyc/test-data/run-exceptions.test | 47 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/mypyc/lib-rt/exc_ops.c b/mypyc/lib-rt/exc_ops.c index 5dbbf79548842..c5ec2b6386e86 100644 --- a/mypyc/lib-rt/exc_ops.c +++ b/mypyc/lib-rt/exc_ops.c @@ -73,6 +73,13 @@ void CPy_RaiseFrom(PyObject *exc, PyObject *cause) { void CPy_Reraise(void) { PyObject *p_type, *p_value, *p_traceback; PyErr_GetExcInfo(&p_type, &p_value, &p_traceback); + if (p_value == NULL || Py_IsNone(p_value)) { + Py_XDECREF(p_type); + Py_XDECREF(p_value); + Py_XDECREF(p_traceback); + PyErr_SetString(PyExc_RuntimeError, "No active exception to reraise"); + return; + } PyErr_Restore(p_type, p_value, p_traceback); } diff --git a/mypyc/test-data/run-exceptions.test b/mypyc/test-data/run-exceptions.test index e6178876aae8b..93fa01f3bb434 100644 --- a/mypyc/test-data/run-exceptions.test +++ b/mypyc/test-data/run-exceptions.test @@ -694,3 +694,50 @@ def gen() -> Iterator[str]: def test_generator() -> None: assert list(gen()) == ["KeyError('z')"] + +[case testBareRaiseWithoutActiveException] +from testutil import assertRaises + +def reraise() -> None: + raise + +def reraise_caught() -> str: + try: + raise + except RuntimeError as e: + return str(e) + +def test_no_active_exception() -> None: + with assertRaises(RuntimeError, "No active exception to reraise"): + reraise() + assert reraise_caught() == "No active exception to reraise" + +def test_after_handled_exception() -> None: + try: + raise ValueError("x") + except ValueError: + pass + with assertRaises(RuntimeError, "No active exception to reraise"): + reraise() + +def test_active_exception() -> None: + try: + raise ValueError("x") + except ValueError: + with assertRaises(ValueError, "x"): + reraise() + +[file driver.py] +import sys +import native + +native.test_no_active_exception() +native.test_after_handled_exception() +native.test_active_exception() +assert sys.exc_info() == (None, None, None) +try: + native.reraise() +except RuntimeError as e: + assert str(e) == "No active exception to reraise" +else: + assert False From 7547d739fdbb7695cfc136e0420efb0c8e335c7d Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:42:08 +0500 Subject: [PATCH 3/3] [mypyc] Fix crash when calling an unbound async method without self Async methods and classmethods of native classes are wrapped in a CPyFunction object whose vectorcall handler takes self from the first positional argument without checking that there is one. Calling the function with no arguments, such as C.m() or C.__dict__['m'](), read past the end of the argument array and usually segfaulted. Raise a TypeError instead. tp_call also goes through the vectorcall handler, so this covers both paths. --- mypyc/lib-rt/function_wrapper.c | 8 ++++++ mypyc/test-data/run-async.test | 45 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/mypyc/lib-rt/function_wrapper.c b/mypyc/lib-rt/function_wrapper.c index 9a3a1d118d8ba..051f89ab355ec 100644 --- a/mypyc/lib-rt/function_wrapper.c +++ b/mypyc/lib-rt/function_wrapper.c @@ -198,6 +198,14 @@ static PyObject* CPyFunction_Vectorcall(PyObject *func, PyObject *const *args, s self = ((PyCFunctionObject *)f)->m_self; if (!self) { + if (unlikely(nargs < 1)) { + PyObject *name = CPyFunction_get_name(func, NULL); + if (name != NULL) { + PyErr_Format(PyExc_TypeError, "unbound method %U() needs an argument", name); + Py_DECREF(name); + } + return NULL; + } self = args[0]; args += 1; nargs -= 1; diff --git a/mypyc/test-data/run-async.test b/mypyc/test-data/run-async.test index 8973c98dbb6de..133b97d18b7ca 100644 --- a/mypyc/test-data/run-async.test +++ b/mypyc/test-data/run-async.test @@ -2957,3 +2957,48 @@ with assertRaises(MyError): pyiter_send(fails(), None) [typing fixtures/typing-full.pyi] + +[case testCallUnboundAsyncMethodWithoutSelf] +class C: + async def m(self) -> int: + return 1 + + @classmethod + async def c(cls) -> str: + return cls.__name__ + + @staticmethod + async def s() -> int: + return 2 + +[file driver.py] +from typing import Any +from native import C +from testutil import assertRaises + +def run(coro: Any) -> Any: + try: + coro.send(None) + except StopIteration as e: + return e.value + assert False + +assert run(C().m()) == 1 +assert run(C.m(C())) == 1 +assert run(C.c()) == "C" +assert run(C().c()) == "C" +assert run(C.s()) == 2 + +# Calling the underlying function without self (or cls) used to read out of bounds. +with assertRaises(TypeError, "unbound method C.m() needs an argument"): + C.m() +with assertRaises(TypeError, "unbound method C.m() needs an argument"): + C.__dict__["m"]() +with assertRaises(TypeError, "unbound method C.m() needs an argument"): + C.__dict__["m"].__call__() +with assertRaises(TypeError, "unbound method C.c() needs an argument"): + C.__dict__["c"]() +with assertRaises(TypeError, "unbound method C.c() needs an argument"): + C.__dict__["c"].__call__() +assert run(C.__dict__["m"](C())) == 1 +assert run(C.__dict__["c"](C)) == "C"