Skip to content

Commit 946aee3

Browse files
gh-143544: Fix use-after-free in _json.raise_errmsg
1 parent 9477824 commit 946aee3

File tree

1 file changed

+6
-17
lines changed

1 file changed

+6
-17
lines changed

Modules/_json.c

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -413,33 +413,22 @@ write_escaped_unicode(PyUnicodeWriter *writer, PyObject *pystr)
413413
static void
414414
raise_errmsg(const char *msg, PyObject *s, Py_ssize_t end)
415415
{
416+
/* Use JSONDecodeError exception to raise a nice looking ValueError subclass */
416417
_Py_DECLARE_STR(json_decoder, "json.decoder");
417418

418-
PyObject *json_error =
419+
PyObject *JSONDecodeError =
419420
PyImport_ImportModuleAttr(&_Py_STR(json_decoder), &_Py_ID(JSONDecodeError));
420-
if (json_error == NULL) {
421+
if (JSONDecodeError == NULL) {
421422
return;
422423
}
423424

424-
/* Hold a strong reference across user code execution */
425-
PyObject *error_type = Py_NewRef(json_error);
426-
427-
PyObject *exc = PyObject_CallFunction(error_type, "zOn", msg, s, end);
428-
425+
PyObject *exc = PyObject_CallFunction(JSONDecodeError, "zOn", msg, s, end);
429426
if (exc != NULL) {
430-
/* Only use it if it's a valid exception type */
431-
if (PyExceptionClass_Check(error_type)) {
432-
PyErr_SetObject(error_type, exc);
433-
}
434-
else {
435-
/* Fallback: always safe */
436-
PyErr_SetString(PyExc_ValueError, msg);
437-
}
427+
PyErr_SetObject(JSONDecodeError, exc);
438428
Py_DECREF(exc);
439429
}
440430

441-
Py_DECREF(error_type);
442-
Py_DECREF(json_error);
431+
Py_DECREF(JSONDecodeError);
443432
}
444433

445434
static void

0 commit comments

Comments
 (0)