Skip to content

Starting new thread during finalization leads to call to PyMem_Free without holding the GIL #109795

Description

@chgnrdv

Crash report

What happened?

Since #109135, thread_run checks if it is called during finalization, and in this case it frees thread bootstate in thread_bootstate_free and returns. The problem is that PyMem_Free shouldn't be called if GIL is not held.

Repro and error message (just in case):

importosimportrandomimportsignalimportsubprocessimportsysimporttimescript="""import threadingwhile True: t = threading.Thread() t.start() t.join()"""whileTrue:
p=subprocess.Popen([sys.executable, '-c', script], stderr=subprocess.PIPE)
time.sleep(random.random())
os.kill(p.pid, signal.SIGINT)
_, err=p.communicate()
ifp.returncode==-signal.SIGABRT:
print(err.decode('utf-8'))
break
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "/home/radislav/projects/cpython/Lib/threading.py", line 983, in start
self._started.wait()
File "/home/radislav/projects/cpython/Lib/threading.py", line 641, in wait
signaled = self._cond.wait(timeout)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/radislav/projects/cpython/Lib/threading.py", line 341, in wait
waiter.acquire()
KeyboardInterrupt
Fatal Python error: _PyMem_DebugFree: Python memory allocator called without holding the GIL
Python runtime state: finalizing (tstate=0x0000561b61b67338)
Thread 0x00007f8f890b8280 (most recent call first):
<no Python frame>

cc @vstinner

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.13.0a0 (heads/main:3e8fcb7df7, Sep 23 2023, 01:43:45) [GCC 10.2.1 20210110]

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions