Skip to content

PyErr_GivenExceptionMatches crashes with SIGSEGV on deeply nested tuple targets #156204

Description

@BHUVANSH855

Crash report

What happened?

Problem Description

PyErr_GivenExceptionMatches(err, exc) in Python/errors.c recursively iterates through nested tuple exception targets without guarding recursion depth via Py_EnterRecursiveCall() / Py_LeaveRecursiveCall().

When evaluating deeply nested tuple structures passed through C API extensions or dynamic tuple composition, unbounded native C call stack growth leads to stack exhaustion and an immediate SIGSEGV crash.

Steps to Reproduce

import ctypes

lib = ctypes.pythonapi
lib.PyErr_GivenExceptionMatches.argtypes = [ctypes.py_object, ctypes.py_object]
lib.PyErr_GivenExceptionMatches.restype = ctypes.c_int

# Construct deeply nested tuple target
tup = (1, ValueError)
for _ in range(1_000_000):
    tup = (1, tup)

# Trigger exception matching traversal
res = lib.PyErr_GivenExceptionMatches(TypeError(), tup)

Actual Result

Segmentation fault (core dumped)

Program received signal SIGSEGV, Segmentation fault.
PyTuple_Size (op=op@entry=0x7ffff2beda30) at Objects/tupleobject.c:100
100             return Py_SIZE(op);
#0  PyTuple_Size (op=op@entry=0x7ffff2beda30) at Objects/tupleobject.c:100
#1  0x0000555555824f63 in PyErr_GivenExceptionMatches (err=err@entry=0x7ffff78ea900, exc=0x7ffff2beda30) at Python/errors.c:339
#2  0x0000555555824fb0 in PyErr_GivenExceptionMatches (err=err@entry=0x7ffff78ea900, exc=0x7ffff2beda90) at Python/errors.c:342
#3  0x0000555555824fb0 in PyErr_GivenExceptionMatches (err=err@entry=0x7ffff78ea900, exc=0x7ffff2bedaf0) at Python/errors.c:342
#4  0x0000555555824fb0 in PyErr_GivenExceptionMatches (err=err@entry=0x7ffff78ea900, exc=0x7ffff2bedb50) at Python/errors.c:342
...
rsp             0x7fffff7ff000      0x7fffff7ff000

Expected Result

PyErr_GivenExceptionMatches should guard recursion with Py_EnterRecursiveCall() / Py_LeaveRecursiveCall(), setting a RecursionError and returning 0 safely when recursion depth is exceeded instead of crashing the interpreter.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.16.0a0 (heads/fix-err-given-exception-matches-recursion:999a046b24c, Aug 21 2026, 18:34:) [GCC 13.3.0]

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions