Skip to content

Commit afd10f0

Browse files
authored
gh-154871: Fix asyncio.Task.get_context() crash on uninitialized tasks (#154898)
1 parent 534b6b0 commit afd10f0

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

Lib/test/test_asyncio/test_tasks.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2924,6 +2924,16 @@ async def coro():
29242924
with self.assertRaises(AttributeError):
29252925
del task._log_destroy_pending
29262926

2927+
def test_get_context_uninitialized_segfault(self):
2928+
# https://github.com/python/cpython/issues/154871
2929+
2930+
class UninitializedTask(self.Task):
2931+
def __init__(self, *args, **kwargs):
2932+
pass
2933+
2934+
task = UninitializedTask()
2935+
self.assertIsNone(task.get_context())
2936+
29272937

29282938
@unittest.skipUnless(hasattr(futures, '_CFuture') and
29292939
hasattr(tasks, '_CTask'),
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a crash in :meth:`asyncio.Task.get_context`
2+
when called on an uninitialized task.

Modules/_asynciomodule.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2786,7 +2786,11 @@ static PyObject *
27862786
_asyncio_Task_get_context_impl(TaskObj *self)
27872787
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
27882788
{
2789-
return Py_NewRef(self->task_context);
2789+
if (self->task_context) {
2790+
return Py_NewRef(self->task_context);
2791+
}
2792+
2793+
Py_RETURN_NONE;
27902794
}
27912795

27922796
/*[clinic input]

0 commit comments

Comments
 (0)