[3.13] gh-143377: fix crashes in _interpreters.capture_exception (GH-143418) (#143653)

(cherry picked from commit ce6bae92da)
This commit is contained in:
Bénédikt Tran 2026-01-10 14:59:14 +01:00 committed by GitHub
parent 523d866205
commit 733a5cf51c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 62 additions and 5 deletions

View file

@ -337,7 +337,7 @@ _PyCrossInterpreterData_ReleaseAndRawFree(_PyCrossInterpreterData *data)
/* convenience utilities */
/*************************/
static const char *
static char *
_copy_string_obj_raw(PyObject *strobj, Py_ssize_t *p_size)
{
Py_ssize_t size = -1;
@ -441,11 +441,16 @@ _format_TracebackException(PyObject *tbexc)
}
Py_ssize_t size = -1;
const char *formatted = _copy_string_obj_raw(formatted_obj, &size);
char *formatted = _copy_string_obj_raw(formatted_obj, &size);
Py_DECREF(formatted_obj);
// We remove trailing the newline added by TracebackException.format().
assert(formatted[size-1] == '\n');
((char *)formatted)[size-1] = '\0';
if (formatted == NULL || size == 0) {
return formatted;
}
assert(formatted[size] == '\0');
// Remove a trailing newline if needed.
if (formatted[size-1] == '\n') {
formatted[size-1] = '\0';
}
return formatted;
}