Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion mypyc/lib-rt/exc_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand All @@ -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);
Expand Down
42 changes: 42 additions & 0 deletions mypyc/test-data/run-exceptions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading