Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 88abdef

Browse files
committed
merge 3.4 (#24094)
2 parents c9083bf + 122f4b1 commit 88abdef

3 files changed

Lines changed: 25 additions & 28 deletions

File tree

Lib/test/test_json/test_dump.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,25 @@ def crasher(obj):
2828
self.assertEqual(self.dumps(a, default=crasher),
2929
'[null, null, null, null, null]')
3030

31+
# Issue 24094
32+
def test_encode_evil_dict(self):
33+
class D(dict):
34+
def keys(self):
35+
return L
36+
37+
class X:
38+
def __hash__(self):
39+
del L[0]
40+
return 1337
41+
42+
def __lt__(self, o):
43+
return 0
44+
45+
L = [X() for i in range(1122)]
46+
d = D()
47+
d[1337] = "true.dat"
48+
self.assertEqual(self.dumps(d, sort_keys=True), '{"1337": "true.dat"}')
49+
3150

3251
class TestPyDump(TestDump, PyTest): pass
3352

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ Core and Builtins
2525
Library
2626
-------
2727

28+
- Issue #24094: Fix possible crash in json.encode with poorly behaved dict
29+
subclasses.
30+
2831
- Issue #9246: On POSIX, os.getcwd() now supports paths longer than 1025 bytes.
2932
Patch written by William Orr.
3033

Modules/_json.c

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1663,36 +1663,11 @@ encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc,
16631663
*/
16641664
}
16651665

1666-
if (PyObject_IsTrue(s->sort_keys)) {
1667-
/* First sort the keys then replace them with (key, value) tuples. */
1668-
Py_ssize_t i, nitems;
1669-
items = PyMapping_Keys(dct);
1670-
if (items == NULL)
1671-
goto bail;
1672-
if (!PyList_Check(items)) {
1673-
PyErr_SetString(PyExc_ValueError, "keys must return list");
1674-
goto bail;
1675-
}
1676-
if (PyList_Sort(items) < 0)
1677-
goto bail;
1678-
nitems = PyList_GET_SIZE(items);
1679-
for (i = 0; i < nitems; i++) {
1680-
PyObject *key, *value;
1681-
key = PyList_GET_ITEM(items, i);
1682-
value = PyDict_GetItem(dct, key);
1683-
item = PyTuple_Pack(2, key, value);
1684-
if (item == NULL)
1685-
goto bail;
1686-
PyList_SET_ITEM(items, i, item);
1687-
item = NULL;
1688-
Py_DECREF(key);
1689-
}
1690-
}
1691-
else {
1692-
items = PyMapping_Items(dct);
1693-
}
1666+
items = PyMapping_Items(dct);
16941667
if (items == NULL)
16951668
goto bail;
1669+
if (PyObject_IsTrue(s->sort_keys) && PyList_Sort(items) < 0)
1670+
goto bail;
16961671
it = PyObject_GetIter(items);
16971672
Py_DECREF(items);
16981673
if (it == NULL)

0 commit comments

Comments
 (0)