Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

48 changes: 19 additions & 29 deletions Modules/_pickle.c
Original file line number Diff line number Diff line change
Expand Up @@ -3351,12 +3351,9 @@ batch_dict(PickleState *state, PicklerObject *self, PyObject *iter, PyObject *or
* Returns 0 on success, -1 on error.
*
* Note that this currently doesn't work for protocol 0.

* gh-146452: Wrap the dict iteration in a critical sections to prevent
* concurrent mutation from invalidating PyDict_Next() iteration state.
*/
static int
batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)
batch_dict_exact_impl(PickleState *state, PicklerObject *self, PyObject *obj)
{
PyObject *key = NULL, *value = NULL;
int i;
Expand All @@ -3373,19 +3370,9 @@ batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)

/* Special-case len(d) == 1 to save space. */
if (dict_size == 1) {
int next;
Py_BEGIN_CRITICAL_SECTION(obj);
next = PyDict_Next(obj, &ppos, &key, &value);
if (next) {
Py_INCREF(key);
Py_INCREF(value);
}
Py_END_CRITICAL_SECTION();
if (!next) {
PyErr_SetString(PyExc_RuntimeError,
"dictionary changed size during iteration");
goto error;
}
PyDict_Next(obj, &ppos, &key, &value);
Py_INCREF(key);
Py_INCREF(value);
if (save(state, self, key, 0) < 0) {
goto error;
}
Expand All @@ -3405,18 +3392,9 @@ batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)
i = 0;
if (_Pickler_Write(self, &mark_op, 1) < 0)
return -1;
int next;
while (1) {
Py_BEGIN_CRITICAL_SECTION(obj);
next = PyDict_Next(obj, &ppos, &key, &value);
if (next) {
Py_INCREF(key);
Py_INCREF(value);
}
Py_END_CRITICAL_SECTION();
if (!next) {
break;
}
while (PyDict_Next(obj, &ppos, &key, &value)) {
Py_INCREF(key);
Py_INCREF(value);
if (save(state, self, key, 0) < 0) {
goto error;
}
Expand Down Expand Up @@ -3446,6 +3424,18 @@ batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)
return -1;
}

/* gh-146452: Wrap the dict iteration in a critical section to prevent
concurrent mutation from invalidating PyDict_Next() iteration state. */
static int
batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)
{
int ret;
Py_BEGIN_CRITICAL_SECTION(obj);
ret = batch_dict_exact_impl(state, self, obj);
Py_END_CRITICAL_SECTION();
return ret;
}

static int
save_dict(PickleState *state, PicklerObject *self, PyObject *obj)
{
Expand Down
Loading