[3.13] gh-119213: Be More Careful About _PyArg_Parser.kwtuple Across Interpreters (gh-119331) (gh-119410)

_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)

Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
This commit is contained in:
Miss Islington (bot) 2024-05-22 20:09:48 +02:00 committed by GitHub
parent a463cd8e45
commit bfd9c3ea53
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 144 additions and 3 deletions

View file

@ -7,6 +7,7 @@
#include "pycore_dict.h" // _PyDict_HasOnlyStringKeys()
#include "pycore_modsupport.h" // export _PyArg_NoKeywords()
#include "pycore_pylifecycle.h" // _PyArg_Fini
#include "pycore_pystate.h" // _Py_IsMainInterpreter()
#include "pycore_tuple.h" // _PyTuple_ITEMS()
#include "pycore_pyerrors.h" // _Py_CalculateSuggestions()
@ -1947,7 +1948,23 @@ _parser_init(void *arg)
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 -1;
}
@ -1969,8 +1986,8 @@ _parser_init(void *arg)
parser->next = _Py_atomic_load_ptr(&_PyRuntime.getargs.static_parsers);
do {
// compare-exchange updates parser->next on failure
} while (_Py_atomic_compare_exchange_ptr(&_PyRuntime.getargs.static_parsers,
&parser->next, parser));
} while (!_Py_atomic_compare_exchange_ptr(&_PyRuntime.getargs.static_parsers,
&parser->next, parser));
return 0;
}