Skip to content

Commit ee59ca6

Browse files
committed
Be immune to mutation while iterating dict
Refs #609 consider PyDict_Next
1 parent 17c19e1 commit ee59ca6

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

src/jsonb.c

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -879,15 +879,29 @@ jsonb_encode_internal_actual(struct JSONBuffer *buf, PyObject *obj)
879879
/* the expected code path */
880880
Py_ssize_t pos = 0;
881881
PyObject *key, *value;
882-
while (PyDict_Next(obj, &pos, &key, &value))
882+
883+
/* take a copy of the dict to avoid mutation crashes possible
884+
when doing encoding */
885+
PyObject *copy = PyDict_Copy(obj);
886+
if (!copy)
887+
goto error;
888+
889+
while (PyDict_Next(copy, &pos, &key, &value))
883890
{
884891
size_t offset = buf->size;
885892

886893
if (jsonb_encode_object_key(buf, key))
894+
{
895+
Py_DECREF(copy);
887896
goto error;
897+
}
888898
if (buf->size != offset && jsonb_encode_internal(buf, value))
899+
{
900+
Py_DECREF(copy);
889901
goto error;
902+
}
890903
}
904+
Py_DECREF(copy);
891905
}
892906
else
893907
{

0 commit comments

Comments
 (0)