Skip to content

Commit 1f9099b

Browse files
BHUVANSH855miss-islington
authored andcommitted
gh-154871: Fix asyncio.Task.get_context() crash on uninitialized tasks (GH-154898)
(cherry picked from commit afd10f0) Co-authored-by: Bhuvansh <bhuvanshkataria@gmail.com>
1 parent 965f1f9 commit 1f9099b

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
@@ -2943,6 +2943,16 @@ async def coro():
29432943
with self.assertRaises(AttributeError):
29442944
del task._log_destroy_pending
29452945

2946+
def test_get_context_uninitialized_segfault(self):
2947+
# https://github.com/python/cpython/issues/154871
2948+
2949+
class UninitializedTask(self.Task):
2950+
def __init__(self, *args, **kwargs):
2951+
pass
2952+
2953+
task = UninitializedTask()
2954+
self.assertIsNone(task.get_context())
2955+
29462956

29472957
@unittest.skipUnless(hasattr(futures, '_CFuture') and
29482958
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
@@ -2795,7 +2795,11 @@ static PyObject *
27952795
_asyncio_Task_get_context_impl(TaskObj *self)
27962796
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
27972797
{
2798-
return Py_NewRef(self->task_context);
2798+
if (self->task_context) {
2799+
return Py_NewRef(self->task_context);
2800+
}
2801+
2802+
Py_RETURN_NONE;
27992803
}
28002804

28012805
/*[clinic input]

0 commit comments

Comments
 (0)