Skip to content

gh-159090: Handle deleted StopIteration values in generators - #159107

Open
Shoryamishra61 wants to merge 1 commit into
python:mainfrom
Shoryamishra61:gh-159090-fix-stopiteration-null-value
Open

Shoryamishra61 wants to merge 1 commit into
python:mainfrom
Shoryamishra61:gh-159090-fix-stopiteration-null-value

Conversation

@Shoryamishra61

Copy link
Copy Markdown

Closes gh-159090

Summary

Fixes a crash when a generator or yield from expression receives a StopIteration instance whose value attribute was deleted.

Root cause

When del exc.value is executed on a StopIteration instance, _Py_T_OBJECT member handling clears the C field ((PyStopIterationObject *)exc)->value to NULL. Python attribute lookup exc.value substitutes None, but two internal C consumers dereferenced the field unconditionally:

  1. _PyGen_FetchStopIterationValue in Objects/genobject.c called Py_NewRef(NULL) before reaching the if (value == NULL) fallback.
  2. CLEANUP_THROW in Python/bytecodes.c called PyStackRef_FromPyObjectNew(NULL).

Fix

  • In _PyGen_FetchStopIterationValue (Objects/genobject.c), use Py_XNewRef(...) so that a NULL field returns NULL and triggers the existing fallback if (value == NULL) value = Py_NewRef(Py_None).
  • In CLEANUP_THROW (Python/bytecodes.c), check if exc_value->value is non-NULL before creating a stack reference; if NULL, use PyStackRef_None.
  • Regenerated bytecode cases via make regen-cases.
  • Added user-facing NEWS entry.

Tests

  • Added regression tests to Lib/test/test_yield_from.py covering yield from iteration and throw() handling with deleted StopIteration.value, including custom StopIteration subclasses.
  • Ran test suites: test_yield_from, test_generators, test_exceptions, and test_coroutines (322 tests passing).
  • Ran reference-leak checks on test_yield_from and test_generators with -R 3:3 (0 leaks).
  • Ran Tools/patchcheck/patchcheck.py.

Authored with AI assistance and reviewed by human contributor Shoryamishra61.

Safely handle cases where StopIteration.value is deleted or NULL in _PyGen_FetchStopIterationValue and the CLEANUP_THROW bytecode instruction.
Copilot AI balanced review requested due to automatic review settings October 10, 2026 09:59
@python-cla-bot

python-cla-bot Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

del StopIteration.value stores NULL in C field, crashing generators (SIGSEGV)

2 participants