diff --git a/mypyc/lib-rt/exc_ops.c b/mypyc/lib-rt/exc_ops.c index 0633cf55ea47..c96411e33b1c 100644 --- a/mypyc/lib-rt/exc_ops.c +++ b/mypyc/lib-rt/exc_ops.c @@ -390,7 +390,6 @@ static PyCodeObject *get_traceback_code(const char *filename, const char *funcna // which is available in all the versions we support, except that // code objects are cached (see above). 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; @@ -400,7 +399,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 = get_traceback_code(filename, funcname, line); if (code_obj == NULL) { goto error; @@ -412,7 +416,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 aaf853ecd778..c0db9c8a3f9d 100644 --- a/mypyc/test-data/run-exceptions.test +++ b/mypyc/test-data/run-exceptions.test @@ -799,3 +799,45 @@ def test_no_garbage_code_objects() -> None: assert count_code_objects() - before < 10 finally: gc.enable() + +[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")