Skip to content

[3.12] gh-107915: Handle errors in C API functions PyErr_Set*() and PyErr_Format() (GH-107918) #108134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions Lib/test/test_capi/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import errno
import os
import re
import sys
import unittest

from test import support
from test.support import import_helper
from test.support.os_helper import TESTFN, TESTFN_UNDECODABLE
from test.support.script_helper import assert_python_failure
from test.support.testcase import ExceptionIsLikeMixin

Expand All @@ -12,6 +15,8 @@
# Skip this test if the _testcapi module isn't available.
_testcapi = import_helper.import_module('_testcapi')

NULL = None

class Test_Exceptions(unittest.TestCase):

def test_exception(self):
Expand Down Expand Up @@ -189,6 +194,82 @@ def __repr__(self):
self.assertEqual(exc.__notes__[0],
'Normalization failed: type=Broken args=<unknown>')

def test_set_string(self):
"""Test PyErr_SetString()"""
setstring = _testcapi.err_setstring
with self.assertRaises(ZeroDivisionError) as e:
setstring(ZeroDivisionError, b'error')
self.assertEqual(e.exception.args, ('error',))
with self.assertRaises(ZeroDivisionError) as e:
setstring(ZeroDivisionError, 'помилка'.encode())
self.assertEqual(e.exception.args, ('помилка',))

with self.assertRaises(UnicodeDecodeError):
setstring(ZeroDivisionError, b'\xff')
self.assertRaises(SystemError, setstring, list, b'error')
# CRASHES setstring(ZeroDivisionError, NULL)
# CRASHES setstring(NULL, b'error')

def test_format(self):
"""Test PyErr_Format()"""
import_helper.import_module('ctypes')
from ctypes import pythonapi, py_object, c_char_p, c_int
name = "PyErr_Format"
PyErr_Format = getattr(pythonapi, name)
PyErr_Format.argtypes = (py_object, c_char_p,)
PyErr_Format.restype = py_object
with self.assertRaises(ZeroDivisionError) as e:
PyErr_Format(ZeroDivisionError, b'%s %d', b'error', c_int(42))
self.assertEqual(e.exception.args, ('error 42',))
with self.assertRaises(ZeroDivisionError) as e:
PyErr_Format(ZeroDivisionError, b'%s', 'помилка'.encode())
self.assertEqual(e.exception.args, ('помилка',))

with self.assertRaisesRegex(OverflowError, 'not in range'):
PyErr_Format(ZeroDivisionError, b'%c', c_int(-1))
with self.assertRaisesRegex(ValueError, 'format string'):
PyErr_Format(ZeroDivisionError, b'\xff')
self.assertRaises(SystemError, PyErr_Format, list, b'error')
# CRASHES PyErr_Format(ZeroDivisionError, NULL)
# CRASHES PyErr_Format(py_object(), b'error')

def test_setfromerrnowithfilename(self):
"""Test PyErr_SetFromErrnoWithFilename()"""
setfromerrnowithfilename = _testcapi.err_setfromerrnowithfilename
ENOENT = errno.ENOENT
with self.assertRaises(FileNotFoundError) as e:
setfromerrnowithfilename(ENOENT, OSError, b'file')
self.assertEqual(e.exception.args,
(ENOENT, 'No such file or directory'))
self.assertEqual(e.exception.errno, ENOENT)
self.assertEqual(e.exception.filename, 'file')

with self.assertRaises(FileNotFoundError) as e:
setfromerrnowithfilename(ENOENT, OSError, os.fsencode(TESTFN))
self.assertEqual(e.exception.filename, TESTFN)

if TESTFN_UNDECODABLE:
with self.assertRaises(FileNotFoundError) as e:
setfromerrnowithfilename(ENOENT, OSError, TESTFN_UNDECODABLE)
self.assertEqual(e.exception.filename,
os.fsdecode(TESTFN_UNDECODABLE))

with self.assertRaises(FileNotFoundError) as e:
setfromerrnowithfilename(ENOENT, OSError, NULL)
self.assertIsNone(e.exception.filename)

with self.assertRaises(OSError) as e:
setfromerrnowithfilename(0, OSError, b'file')
self.assertEqual(e.exception.args, (0, 'Error'))
self.assertEqual(e.exception.errno, 0)
self.assertEqual(e.exception.filename, 'file')

with self.assertRaises(ZeroDivisionError) as e:
setfromerrnowithfilename(ENOENT, ZeroDivisionError, b'file')
self.assertEqual(e.exception.args,
(ENOENT, 'No such file or directory', 'file'))
# CRASHES setfromerrnowithfilename(ENOENT, NULL, b'error')


class Test_PyUnstable_Exc_PrepReraiseStar(ExceptionIsLikeMixin, unittest.TestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
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.
64 changes: 63 additions & 1 deletion Modules/_testcapi/clinic/exceptions.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 42 additions & 0 deletions Modules/_testcapi/exceptions.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#define PY_SSIZE_T_CLEAN
#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]*/
Expand Down Expand Up @@ -129,6 +132,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
Expand Down Expand Up @@ -338,6 +378,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
Expand Down
37 changes: 29 additions & 8 deletions Python/errors.c
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,10 @@ _PyErr_SetString(PyThreadState *tstate, PyObject *exception,
const char *string)
{
PyObject *value = PyUnicode_FromString(string);
_PyErr_SetObject(tstate, exception, value);
Py_XDECREF(value);
if (value != NULL) {
_PyErr_SetObject(tstate, exception, value);
Py_DECREF(value);
}
}

void
Expand Down Expand Up @@ -915,7 +917,13 @@ PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, P
PyObject *
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
{
PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
PyObject *name = NULL;
if (filename) {
name = PyUnicode_DecodeFSDefault(filename);
if (name == NULL) {
return NULL;
}
}
PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Py_XDECREF(name);
return result;
Expand Down Expand Up @@ -1012,7 +1020,13 @@ PyObject *PyErr_SetExcFromWindowsErrWithFilename(
int ierr,
const char *filename)
{
PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
PyObject *name = NULL;
if (filename) {
name = PyUnicode_DecodeFSDefault(filename);
if (name == NULL) {
return NULL;
}
}
PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
ierr,
name,
Expand All @@ -1036,7 +1050,13 @@ PyObject *PyErr_SetFromWindowsErrWithFilename(
int ierr,
const char *filename)
{
PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
PyObject *name = NULL;
if (filename) {
name = PyUnicode_DecodeFSDefault(filename);
if (name == NULL) {
return NULL;
}
}
PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
PyExc_OSError,
ierr, name, NULL);
Expand Down Expand Up @@ -1161,9 +1181,10 @@ _PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
_PyErr_Clear(tstate);

string = PyUnicode_FromFormatV(format, vargs);

_PyErr_SetObject(tstate, exception, string);
Py_XDECREF(string);
if (string != NULL) {
_PyErr_SetObject(tstate, exception, string);
Py_DECREF(string);
}
return NULL;
}

Expand Down