Skip to content

[mypyc] Fix exception chaining when adding a traceback entry fails - #22462

Open
Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-addtraceback-error-path
Open

Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-addtraceback-error-path

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

On Python 3.12+, CPy_AddTraceback saves the current exception with PyErr_Fetch(&exc, &val, &tb). If creating the code or frame object fails, it calls _PyErr_ChainExceptions1(exc), which expects an exception instance, but exc is the exception type. So:

  • the new exception gets the exception class as its __context__, and printing the traceback fails (TypeError: print_exception(): Exception expected for value, type found from the default hook, AttributeError: 'getset_descriptor' object has no attribute 'tb_frame' from traceback.print_exception);
  • the original exception is lost from the chain;
  • val and tb are leaked.

This PR uses PyErr_GetRaisedException/PyErr_SetRaisedException on 3.12+, so the instance is passed around in both paths. Before 3.12 nothing changes.

PyFrame_New failing usually needs an OOM, but it also fails if looking up "__builtins__" in the module globals raises. The new test uses that: it adds a key with the same hash as "__builtins__" whose __eq__ raises (defined in an interpreted module, so that __eq__ doesn't need a traceback entry itself). Then the exception chain is:

3.10, 3.11 3.12–3.14 before 3.12–3.14 after
__context__ chain RuntimeError → RuntimeError → ValueError RuntimeError → <class 'RuntimeError'> RuntimeError → RuntimeError → ValueError

The test fails without the fix. test_run and test_external pass.

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.
…k-error-path

# Conflicts:
#	mypyc/lib-rt/exc_ops.c
#	mypyc/test-data/run-exceptions.test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant