mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
[3.12] gh-119213: Be More Careful About _PyArg_Parser.kwtuple Across Interpreters (gh-119331) (gh-119425)
_PyArg_Parser holds static global data generated for modules by Argument Clinic. The _PyArg_Parser.kwtuple field is a tuple object, even though it's stored within a static global. In some cases the tuple is statically allocated and thus it's okay that it gets shared by multiple interpreters. However, in other cases the tuple is set lazily, allocated from the heap using the active interprepreter at the point the tuple is needed.
This is a problem once that interpreter is destroyed since _PyArg_Parser.kwtuple becomes at dangling pointer, leading to crashes. It isn't a problem if the tuple is allocated under the main interpreter, since its lifetime is bound to the lifetime of the runtime. The solution here is to temporarily switch to the main interpreter. The alternative would be to always statically allocate the tuple.
This change also fixes a bug where only the most recent parser was added to the global linked list.
(cherry picked from commit 81865002ae
)
This commit is contained in:
parent
7eb59cd95b
commit
0d5fe2c7b4
10 changed files with 1033 additions and 870 deletions
|
@ -4,6 +4,7 @@
|
|||
#include "Python.h"
|
||||
#include "pycore_tuple.h" // _PyTuple_ITEMS()
|
||||
#include "pycore_pylifecycle.h" // _PyArg_Fini
|
||||
#include "pycore_pystate.h" // _Py_IsMainInterpreter()
|
||||
|
||||
#include <ctype.h>
|
||||
#include <float.h>
|
||||
|
@ -2002,7 +2003,23 @@ _parser_init(struct _PyArg_Parser *parser)
|
|||
int owned;
|
||||
PyObject *kwtuple = parser->kwtuple;
|
||||
if (kwtuple == NULL) {
|
||||
/* We may temporarily switch to the main interpreter to avoid
|
||||
* creating a tuple that could outlive its owning interpreter. */
|
||||
PyThreadState *save_tstate = NULL;
|
||||
PyThreadState *temp_tstate = NULL;
|
||||
if (!_Py_IsMainInterpreter(PyInterpreterState_Get())) {
|
||||
temp_tstate = PyThreadState_New(_PyInterpreterState_Main());
|
||||
if (temp_tstate == NULL) {
|
||||
return -1;
|
||||
}
|
||||
save_tstate = PyThreadState_Swap(temp_tstate);
|
||||
}
|
||||
kwtuple = new_kwtuple(keywords, len, pos);
|
||||
if (temp_tstate != NULL) {
|
||||
PyThreadState_Clear(temp_tstate);
|
||||
(void)PyThreadState_Swap(save_tstate);
|
||||
PyThreadState_Delete(temp_tstate);
|
||||
}
|
||||
if (kwtuple == NULL) {
|
||||
return 0;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue