X Tutup
Skip to content

Commit 501182a

Browse files
committed
just sort the items tuple directly (closes python#24094)
1 parent 51454a6 commit 501182a

File tree

3 files changed

+25
-27
lines changed

3 files changed

+25
-27
lines changed

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
@@ -19,6 +19,9 @@ Core and Builtins
1919
Library
2020
-------
2121

22+
- Issue #24094: Fix possible crash in json.encode with poorly behaved dict
23+
subclasses.
24+
2225
- Issue #23367: Fix possible overflows in the unicodedata module.
2326

2427
- Issue #23361: Fix possible overflow in Windows subprocess creation code.

Modules/_json.c

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,35 +1527,11 @@ encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc,
15271527
*/
15281528
}
15291529

1530-
if (PyObject_IsTrue(s->sort_keys)) {
1531-
/* First sort the keys then replace them with (key, value) tuples. */
1532-
Py_ssize_t i, nitems;
1533-
items = PyMapping_Keys(dct);
1534-
if (items == NULL)
1535-
goto bail;
1536-
if (!PyList_Check(items)) {
1537-
PyErr_SetString(PyExc_ValueError, "keys must return list");
1538-
goto bail;
1539-
}
1540-
if (PyList_Sort(items) < 0)
1541-
goto bail;
1542-
nitems = PyList_GET_SIZE(items);
1543-
for (i = 0; i < nitems; i++) {
1544-
PyObject *key, *value;
1545-
key = PyList_GET_ITEM(items, i);
1546-
value = PyDict_GetItem(dct, key);
1547-
item = PyTuple_Pack(2, key, value);
1548-
if (item == NULL)
1549-
goto bail;
1550-
PyList_SET_ITEM(items, i, item);
1551-
Py_DECREF(key);
1552-
}
1553-
}
1554-
else {
1555-
items = PyMapping_Items(dct);
1556-
}
1530+
items = PyMapping_Items(dct);
15571531
if (items == NULL)
15581532
goto bail;
1533+
if (PyObject_IsTrue(s->sort_keys) && PyList_Sort(items) < 0)
1534+
goto bail;
15591535
it = PyObject_GetIter(items);
15601536
Py_DECREF(items);
15611537
if (it == NULL)

0 commit comments

Comments
 (0)
X Tutup