diff -r 50a5e271edf9 Lib/json/tests/test_recursion.py --- a/Lib/json/tests/test_recursion.py Tue May 10 00:39:02 2011 -0700 +++ b/Lib/json/tests/test_recursion.py Tue May 10 22:08:35 2011 +0300 @@ -16,6 +16,11 @@ return 'JSONTestObject' return json.JSONEncoder.default(o) +class EndlessJSONEncoder(json.JSONEncoder): + def default(self, o): + """If check_circular is False, this will keep adding another list.""" + return [o] + class TestRecursion(TestCase): def test_listrecursion(self): @@ -67,7 +72,7 @@ self.fail("didn't raise ValueError on default recursion") - def test_highly_nested_objects(self): + def test_highly_nested_objects_decoding(self): # test that loading highly-nested objects doesn't segfault when C # accelerations are used. See #12017 # str @@ -84,3 +89,18 @@ json.loads(u'{"a":' * 100000 + u'[1]' + u'}' * 100000) with self.assertRaises(RuntimeError): json.loads(u'[' * 100000 + u'1' + u']' * 100000) + + def test_highly_nested_objects_encoding(self): + # See #12051 + l, d = [], {} + for x in xrange(100000): + l, d = [l], {'k':d} + with self.assertRaises(RuntimeError): + json.dumps(l) + with self.assertRaises(RuntimeError): + json.dumps(d) + + def test_endless_recursion(self): + # See #12051 + with self.assertRaises(RuntimeError): + EndlessJSONEncoder(check_circular=False).encode(5j) diff -r 50a5e271edf9 Modules/_json.c --- a/Modules/_json.c Tue May 10 00:39:02 2011 -0700 +++ b/Modules/_json.c Tue May 10 22:08:35 2011 +0300 @@ -1999,10 +1999,18 @@ return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { - return encoder_listencode_list(s, rval, obj, indent_level); + if (Py_EnterRecursiveCall(" while encoding a JSON object")) + return -1; + rv = encoder_listencode_list(s, rval, obj, indent_level); + Py_LeaveRecursiveCall(); + return rv; } else if (PyDict_Check(obj)) { - return encoder_listencode_dict(s, rval, obj, indent_level); + if (Py_EnterRecursiveCall(" while encoding a JSON object")) + return -1; + rv = encoder_listencode_dict(s, rval, obj, indent_level); + Py_LeaveRecursiveCall(); + return rv; } else { PyObject *ident = NULL; @@ -2028,7 +2036,12 @@ Py_XDECREF(ident); return -1; } + + if (Py_EnterRecursiveCall(" while encoding a JSON object")) + return -1; rv = encoder_listencode_obj(s, rval, newobj, indent_level); + Py_LeaveRecursiveCall(); + Py_DECREF(newobj); if (rv) { Py_XDECREF(ident);