gh-107915: Handle errors in C API functions PyErr_Set*() and PyErr_Format() (GH-107918)

Such C API functions as PyErr_SetString(), PyErr_Format(),
PyErr_SetFromErrnoWithFilename() and many others no longer crash or
ignore errors if it failed to format the error message or decode the
filename. Instead, they keep a corresponding error.
This commit is contained in:
Serhiy Storchaka 2023-08-19 14:51:03 +03:00 committed by GitHub
parent 79db9d9a0e
commit 633ea217a8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 218 additions and 9 deletions

View file

@ -1,6 +1,8 @@
#include "parts.h"
#include "clinic/exceptions.c.h"
#define NULLABLE(x) do { if (x == Py_None) x = NULL; } while (0);
/*[clinic input]
module _testcapi
[clinic start generated code]*/
@ -129,6 +131,43 @@ _testcapi_exc_set_object_fetch_impl(PyObject *module, PyObject *exc,
return value;
}
/*[clinic input]
_testcapi.err_setstring
exc: object
value: str(zeroes=True, accept={robuffer, str, NoneType})
/
[clinic start generated code]*/
static PyObject *
_testcapi_err_setstring_impl(PyObject *module, PyObject *exc,
const char *value, Py_ssize_t value_length)
/*[clinic end generated code: output=fba8705e5703dd3f input=e8a95fad66d9004b]*/
{
NULLABLE(exc);
PyErr_SetString(exc, value);
return NULL;
}
/*[clinic input]
_testcapi.err_setfromerrnowithfilename
error: int
exc: object
value: str(zeroes=True, accept={robuffer, str, NoneType})
/
[clinic start generated code]*/
static PyObject *
_testcapi_err_setfromerrnowithfilename_impl(PyObject *module, int error,
PyObject *exc, const char *value,
Py_ssize_t value_length)
/*[clinic end generated code: output=d02df5749a01850e input=ff7c384234bf097f]*/
{
NULLABLE(exc);
errno = error;
PyErr_SetFromErrnoWithFilename(exc, value);
return NULL;
}
/*[clinic input]
_testcapi.raise_exception
exception as exc: object
@ -338,6 +377,8 @@ static PyMethodDef test_methods[] = {
_TESTCAPI_MAKE_EXCEPTION_WITH_DOC_METHODDEF
_TESTCAPI_EXC_SET_OBJECT_METHODDEF
_TESTCAPI_EXC_SET_OBJECT_FETCH_METHODDEF
_TESTCAPI_ERR_SETSTRING_METHODDEF
_TESTCAPI_ERR_SETFROMERRNOWITHFILENAME_METHODDEF
_TESTCAPI_RAISE_EXCEPTION_METHODDEF
_TESTCAPI_RAISE_MEMORYERROR_METHODDEF
_TESTCAPI_SET_EXC_INFO_METHODDEF