Skip to content

Commit fc152df

Browse files
[3.15] gh-158159: Fix use-after-free in asyncio Task.get_name() (GH-158180) (#161743)
gh-158159: Fix use-after-free in asyncio Task.get_name() (GH-158180) (cherry picked from commit 7563195) Co-authored-by: Dmitry Spikhalsky <dmitry@spikhalskiy.com>
1 parent 1c6fd6b commit fc152df

3 files changed

Lines changed: 55 additions & 1 deletion

File tree

‎Lib/test/test_asyncio/test_tasks.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,52 @@ async def notmuch():
431431
self.assertEqual(t.get_name(), '123456789')
432432
self.loop.run_until_complete(t)
433433

434+
# The free-threaded GC publishes allocation counts in batches, so the
435+
# collection cannot be scheduled to run inside get_name().
436+
@support.requires_gil_enabled("needs precise GC scheduling")
437+
def test_task_get_name_reentered_during_formatting(self):
438+
# gh-158159: formatting the lazy default name can run the GC, and a
439+
# finalizer may call get_name() on the same task, replacing the name
440+
# the outer call is still formatting.
441+
loop = self.loop
442+
observed = {}
443+
keep = []
444+
task = None
445+
446+
class Reenter:
447+
def __init__(self):
448+
self.cycle = self
449+
450+
def __del__(self):
451+
observed['inner'] = task.get_name()
452+
# Reuse the memory of a counter that was freed too early.
453+
keep.extend(10**9 + i for i in range(8))
454+
455+
async def notmuch():
456+
pass
457+
458+
async def scenario():
459+
gc.collect()
460+
Reenter()
461+
old_threshold = gc.get_threshold()
462+
gc.set_threshold(1)
463+
try:
464+
scratch = [[0], [0], [0]] # schedule a collection
465+
observed['outer'] = task.get_name()
466+
finally:
467+
gc.set_threshold(*old_threshold)
468+
del scratch
469+
470+
# Names are only freeable once the counter is past the small ints.
471+
for _ in range(1100):
472+
loop.run_until_complete(self.new_task(loop, notmuch(), name=None))
473+
task = self.new_task(loop, scenario(), name=None)
474+
loop.run_until_complete(task)
475+
476+
self.assertRegex(observed['outer'], r'^Task-\d+$')
477+
self.assertEqual(observed['outer'], observed['inner'])
478+
self.assertEqual(task.get_name(), observed['outer'])
479+
434480
def test_task_repr_name_not_str(self):
435481
async def notmuch():
436482
return 123
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a use-after-free in :meth:`asyncio.Task.get_name` when formatting the
2+
default task name triggers a garbage collection whose finalizers call
3+
:meth:`~asyncio.Task.get_name` on the same task.

‎Modules/_asynciomodule.c‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2821,7 +2821,12 @@ _asyncio_Task_get_name_impl(TaskObj *self)
28212821
{
28222822
if (self->task_name) {
28232823
if (PyLong_CheckExact(self->task_name)) {
2824-
PyObject *name = PyUnicode_FromFormat("Task-%S", self->task_name);
2824+
// Formatting can run arbitrary code (e.g. a GC finalizer that logs
2825+
// and re-enters get_name()), which may replace self->task_name.
2826+
// Hold a strong reference to the counter while formatting it.
2827+
PyObject *counter = Py_NewRef(self->task_name);
2828+
PyObject *name = PyUnicode_FromFormat("Task-%S", counter);
2829+
Py_DECREF(counter);
28252830
if (name == NULL) {
28262831
return NULL;
28272832
}

0 commit comments

Comments
 (0)