Skip to content

_asyncio.Task.__new__(_asyncio.Task).get_context() segfaults #154871

Description

@BHUVANSH855

Crash report

What happened?

Calling _asyncio.Task.get_context() on an uninitialized Task created via __new__() crashes the interpreter with a segmentation fault.

Minimal reproducer

import _asyncio

_asyncio.Task.__new__(_asyncio.Task).get_context()

A more realistic case is an asyncio.Task subclass that overrides __init__() without calling super().__init__().

import asyncio

class MyTask(asyncio.Task):
    def __init__(self, *args, **kwargs):
        pass

MyTask.__new__(MyTask).get_context()

Actual behavior

The interpreter crashes with a segmentation fault (exit code 139).

Expected behavior

The interpreter should not crash. Accessing get_context() on an uninitialized Task should either return a well-defined value or raise a Python exception.

Analysis

Task instances are allocated using PyType_GenericNew, so fields are initially zero-initialized. The task_context field is initialized only in _asyncio_Task___init__().

However, _asyncio_Task_get_context_impl() currently does:

return Py_NewRef(self->task_context);

without checking whether task_context has been initialized. Calling Py_NewRef(NULL) dereferences a null pointer and crashes the interpreter.

For comparison, the adjacent methods _asyncio_Task_get_coro_impl() and _asyncio_Task_get_name_impl() both guard their corresponding fields before returning them, so the same half-initialized object does not crash when calling get_coro() or get_name().

The pure Python implementation also exposes get_context() by returning self._context, so bypassing initialization would result in a normal Python exception rather than a hard interpreter crash.

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-154835-odict-desync-dirty:8b048eb35eb, Jul 28 2026, 20:03:25) [GCC 13.3.0]

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtopic-asynciotype-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions