From 7f2f62e06429e92e22892eb26f25fe17facf2728 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Sat, 14 Nov 2026 13:47:10 +0500 Subject: [PATCH] [mypyc] Fix exception chaining when adding a traceback entry fails On Python 3.12+, CPy_AddTraceback fetched the exception with PyErr_Fetch but passed only the type to _PyErr_ChainExceptions1 if creating the frame failed. The new exception then got the exception class as its context, the original exception was lost, and the value and traceback were leaked. Use PyErr_GetRaisedException/PyErr_SetRaisedException on 3.12+, so the exception instance is passed around. --- mypyc/lib-rt/exc_ops.c | 10 ++++++- mypyc/test-data/run-exceptions.test | 42 +++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/mypyc/lib-rt/exc_ops.c b/mypyc/lib-rt/exc_ops.c index c5ec2b6386e8..fb3d13668efb 100644 --- a/mypyc/lib-rt/exc_ops.c +++ b/mypyc/lib-rt/exc_ops.c @@ -292,7 +292,6 @@ void CPy_TypeError(const char *expected, PyObject *value) { // which is available in all the versions we support. // We're continuing to use this because we'll probably optimize this later. void CPy_AddTraceback(const char *filename, const char *funcname, int line, PyObject *globals) { - PyObject *exc, *val, *tb; PyThreadState *thread_state = PyThreadState_GET(); PyFrameObject *frame_obj; @@ -302,7 +301,12 @@ void CPy_AddTraceback(const char *filename, const char *funcname, int line, PyOb // needs to do it because it decodes the filename according to the // FS encoding, which could have a decoder in Python. We don't do // that so *that* doesn't apply to us.) +#if CPY_3_12_FEATURES + PyObject *exc = PyErr_GetRaisedException(); +#else + PyObject *exc, *val, *tb; PyErr_Fetch(&exc, &val, &tb); +#endif PyCodeObject *code_obj = PyCode_NewEmpty(filename, funcname, line); if (code_obj == NULL) { goto error; @@ -314,7 +318,11 @@ void CPy_AddTraceback(const char *filename, const char *funcname, int line, PyOb goto error; } frame_obj->f_lineno = line; +#if CPY_3_12_FEATURES + PyErr_SetRaisedException(exc); +#else PyErr_Restore(exc, val, tb); +#endif PyTraceBack_Here(frame_obj); Py_DECREF(code_obj); Py_DECREF(frame_obj); diff --git a/mypyc/test-data/run-exceptions.test b/mypyc/test-data/run-exceptions.test index 93fa01f3bb43..319c2b79fdb0 100644 --- a/mypyc/test-data/run-exceptions.test +++ b/mypyc/test-data/run-exceptions.test @@ -741,3 +741,45 @@ except RuntimeError as e: assert str(e) == "No active exception to reraise" else: assert False + +[case testTracebackFrameCreationError] +# Adding a traceback entry fails if looking up "__builtins__" in the module +# globals raises. The original exception must then be the context of the new one. +from typing import Any + +from traceback_helper import BadKey + +def raise_value_error() -> None: + raise ValueError("x") + +def call_with_bad_global() -> BaseException: + g: Any = globals() + key = BadKey() + g[key] = 1 + try: + raise_value_error() + except Exception as e: + return e + finally: + del g[key] + assert False + +def test_original_exception_is_context() -> None: + e = call_with_bad_global() + assert isinstance(e, RuntimeError) + chain = [] + c: BaseException | None = e + while c is not None: + chain.append(c) + c = c.__context__ + assert all(isinstance(x, BaseException) for x in chain) + assert isinstance(chain[-1], ValueError) + assert str(chain[-1]) == "x" + +[file traceback_helper.py] +class BadKey: + def __hash__(self) -> int: + return hash("__builtins__") + + def __eq__(self, other: object) -> bool: + raise RuntimeError("eq")