Skip to content

Commit 362b951

Browse files
committed
#12017: Fix segfault in json.loads() while decoding highly-nested objects using the C accelerations.
1 parent 7420b70 commit 362b951

3 files changed

Lines changed: 28 additions & 2 deletions

File tree

‎Lib/json/tests/test_recursion.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,15 @@ def test_defaultrecursion(self):
6565
pass
6666
else:
6767
self.fail("didn't raise ValueError on default recursion")
68+
69+
70+
def test_highly_nested_objects(self):
71+
# test that loading highly-nested objects doesn't segfault when C
72+
# accelerations are used. See #12017
73+
with self.assertRaises(RuntimeError):
74+
json.loads('{"a":' * 100000 + '1' + '}' * 100000)
75+
with self.assertRaises(RuntimeError):
76+
json.loads('{"a":' * 100000 + '[1]' + '}' * 100000)
77+
with self.assertRaises(RuntimeError):
78+
json.loads('[' * 100000 + '1' + ']' * 100000)
79+

‎Misc/NEWS‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,9 @@ Library
314314
Extensions
315315
----------
316316

317+
- Issue #12017: Fix segfault in json.loads() while decoding highly-nested
318+
objects using the C accelerations.
319+
317320
- Issue #1838: Prevent segfault in ctypes, when _as_parameter_ on a class is set
318321
to an instance of the class.
319322

‎Modules/_json.c‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,7 @@ scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_
899899
900900
Returns a new PyObject representation of the term.
901901
*/
902+
PyObject *res;
902903
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
903904
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
904905
if (idx >= length) {
@@ -913,10 +914,20 @@ scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_
913914
next_idx_ptr);
914915
case '{':
915916
/* object */
916-
return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
917+
if (Py_EnterRecursiveCall(" while decoding a JSON object "
918+
"from a unicode string"))
919+
return NULL;
920+
res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
921+
Py_LeaveRecursiveCall();
922+
return res;
917923
case '[':
918924
/* array */
919-
return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
925+
if (Py_EnterRecursiveCall(" while decoding a JSON array "
926+
"from a unicode string"))
927+
return NULL;
928+
res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
929+
Py_LeaveRecursiveCall();
930+
return res;
920931
case 'n':
921932
/* null */
922933
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {

0 commit comments

Comments
 (0)