[3.13] gh-128679: Fix tracemalloc.stop() race conditions (#128897)

tracemalloc_alloc(), tracemalloc_realloc(), PyTraceMalloc_Track(),
PyTraceMalloc_Untrack() and _PyTraceMalloc_TraceRef() now check
tracemalloc_config.tracing after calling TABLES_LOCK().

_PyTraceMalloc_Stop() now protects more code with TABLES_LOCK(),
especially setting tracemalloc_config.tracing to 1.

Add a test using PyTraceMalloc_Track() to test tracemalloc.stop()
race condition.

Call _PyTraceMalloc_Init() at Python startup.
This commit is contained in:
Victor Stinner 2025-01-19 00:39:07 +01:00 committed by GitHub
parent ef9961840b
commit 6b47499510
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 250 additions and 117 deletions

View file

@ -7,8 +7,9 @@ from unittest.mock import patch
from test.support.script_helper import (assert_python_ok, assert_python_failure,
interpreter_requires_environment)
from test import support
from test.support import os_helper
from test.support import force_not_colorized
from test.support import os_helper
from test.support import threading_helper
try:
import _testcapi
@ -952,7 +953,6 @@ class TestCommandLine(unittest.TestCase):
return
self.fail(f"unexpected output: {stderr!a}")
def test_env_var_invalid(self):
for nframe in INVALID_NFRAME:
with self.subTest(nframe=nframe):
@ -1101,6 +1101,14 @@ class TestCAPI(unittest.TestCase):
with self.assertRaises(RuntimeError):
self.untrack()
@unittest.skipIf(_testcapi is None, 'need _testcapi')
@threading_helper.requires_working_threading()
# gh-128679: Test crash on a debug build (especially on FreeBSD).
@unittest.skipIf(support.Py_DEBUG, 'need release build')
def test_tracemalloc_track_race(self):
# gh-128679: Test fix for tracemalloc.stop() race condition
_testcapi.tracemalloc_track_race()
if __name__ == "__main__":
unittest.main()