Skip to content

Commit b4d1e1f

Browse files
authored
bpo-20891: Fix PyGILState_Ensure() (#4650)
When PyGILState_Ensure() is called in a non-Python thread before PyEval_InitThreads(), only call PyEval_InitThreads() after calling PyThreadState_New() to fix a crash. Add an unit test in test_embed.
1 parent 986375e commit b4d1e1f

File tree

5 files changed

+83
-8
lines changed

5 files changed

+83
-8
lines changed

Doc/c-api/init.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,9 @@ The following functions can be safely called before Python is initialized:
5858

5959
The following functions **should not be called** before
6060
:c:func:`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`,
61-
:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix` and
62-
:c:func:`Py_GetProgramFullPath` and :c:func:`Py_GetPythonHome`.
61+
:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
62+
:c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome` and
63+
:c:func:`PyEval_InitThreads`.
6364

6465

6566
.. _global-conf-vars:

Lib/test/test_embed.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,16 @@ def test_pre_initialization_api(self):
198198
self.assertEqual(out, '')
199199
self.assertEqual(err, '')
200200

201+
def test_bpo20891(self):
202+
"""
203+
bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
204+
calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
205+
call PyEval_InitThreads() for us in this case.
206+
"""
207+
out, err = self.run_embedded_interpreter("bpo20891")
208+
self.assertEqual(out, '')
209+
self.assertEqual(err, '')
210+
201211

202212
if __name__ == "__main__":
203213
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in a non-Python
2+
thread before PyEval_InitThreads(), only call PyEval_InitThreads() after
3+
calling PyThreadState_New() to fix a crash.

Programs/_testembed.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <Python.h>
2+
#include "pythread.h"
23
#include <inttypes.h>
34
#include <stdio.h>
45

@@ -147,6 +148,53 @@ static int test_pre_initialization_api(void)
147148
return 0;
148149
}
149150

151+
static void bpo20891_thread(void *lockp)
152+
{
153+
PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
154+
155+
PyGILState_STATE state = PyGILState_Ensure();
156+
if (!PyGILState_Check()) {
157+
fprintf(stderr, "PyGILState_Check failed!");
158+
abort();
159+
}
160+
161+
PyGILState_Release(state);
162+
163+
PyThread_release_lock(lock);
164+
165+
PyThread_exit_thread();
166+
}
167+
168+
static int test_bpo20891(void)
169+
{
170+
/* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
171+
calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
172+
call PyEval_InitThreads() for us in this case. */
173+
PyThread_type_lock lock = PyThread_allocate_lock();
174+
if (!lock) {
175+
fprintf(stderr, "PyThread_allocate_lock failed!");
176+
return 1;
177+
}
178+
179+
_testembed_Py_Initialize();
180+
181+
unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
182+
if (thrd == PYTHREAD_INVALID_THREAD_ID) {
183+
fprintf(stderr, "PyThread_start_new_thread failed!");
184+
return 1;
185+
}
186+
PyThread_acquire_lock(lock, WAIT_LOCK);
187+
188+
Py_BEGIN_ALLOW_THREADS
189+
/* wait until the thread exit */
190+
PyThread_acquire_lock(lock, WAIT_LOCK);
191+
Py_END_ALLOW_THREADS
192+
193+
PyThread_free_lock(lock);
194+
195+
return 0;
196+
}
197+
150198

151199
/* *********************************************************
152200
* List of test cases and the function that implements it.
@@ -170,6 +218,7 @@ static struct TestCase TestCases[] = {
170218
{ "forced_io_encoding", test_forced_io_encoding },
171219
{ "repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters },
172220
{ "pre_initialization_api", test_pre_initialization_api },
221+
{ "bpo20891", test_bpo20891 },
173222
{ NULL, NULL }
174223
};
175224

Python/pystate.c

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -922,19 +922,19 @@ PyGILState_Ensure(void)
922922
{
923923
int current;
924924
PyThreadState *tcur;
925+
int need_init_threads = 0;
926+
925927
/* Note that we do not auto-init Python here - apart from
926928
potential races with 2 threads auto-initializing, pep-311
927929
spells out other issues. Embedders are expected to have
928930
called Py_Initialize() and usually PyEval_InitThreads().
929931
*/
930932
/* Py_Initialize() hasn't been called! */
931933
assert(_PyRuntime.gilstate.autoInterpreterState);
934+
932935
tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
933936
if (tcur == NULL) {
934-
/* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
935-
called from a new thread for the first time, we need the create the
936-
GIL. */
937-
PyEval_InitThreads();
937+
need_init_threads = 1;
938938

939939
/* Create a new thread state for this thread */
940940
tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
@@ -945,16 +945,28 @@ PyGILState_Ensure(void)
945945
tcur->gilstate_counter = 0;
946946
current = 0; /* new thread state is never current */
947947
}
948-
else
948+
else {
949949
current = PyThreadState_IsCurrent(tcur);
950-
if (current == 0)
950+
}
951+
952+
if (current == 0) {
951953
PyEval_RestoreThread(tcur);
954+
}
955+
952956
/* Update our counter in the thread-state - no need for locks:
953957
- tcur will remain valid as we hold the GIL.
954958
- the counter is safe as we are the only thread "allowed"
955959
to modify this value
956960
*/
957961
++tcur->gilstate_counter;
962+
963+
if (need_init_threads) {
964+
/* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
965+
called from a new thread for the first time, we need the create the
966+
GIL. */
967+
PyEval_InitThreads();
968+
}
969+
958970
return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
959971
}
960972

0 commit comments

Comments
 (0)