8000 [3.13] GH-132417: ctypes: Fix potential `Py_DECREF(NULL)` when handling functions returning `PyObject *` (GH-132418) by miss-islington · Pull Request #132425 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[3.13] GH-132417: ctypes: Fix potential Py_DECREF(NULL) when handling functions returning PyObject * (GH-132418) #132425

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 1 commit into from
Apr 12, 2025
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
15 changes: 15 additions & 0 deletions Lib/test/test_ctypes/test_refcounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,20 @@ def test_finalize(self):
script_helper.assert_python_ok("-c", script)


class PyObjectRestypeTest(unittest.TestCase):
def test_restype_py_object_with_null_return(self):
# Test that a function which returns a NULL PyObject *
# without setting an exception does not crash.
PyErr_Occurred = ctypes.pythonapi.PyErr_Occurred
PyErr_Occurred.argtypes = []
PyErr_Occurred.restype = ctypes.py_object

# At this point, there's no exception set, so PyErr_Occurred
# returns NULL. Given the restype is py_object, the
# ctypes machinery will raise a custom error.
with self.assertRaisesRegex(ValueError, "PyObject is NULL"):
PyErr_Occurred()


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a ``NULL`` pointer dereference when a C function called using
:mod:`ctypes` with ``restype`` :class:`~ctypes.py_object` returns
``NULL``.
7 changes: 4 additions & 3 deletions Modules/_ctypes/callproc.c
< 5B31 td id="diff-4e23b3237d0aa08bf4c434d75fab19200a80837bd147051fefccd98b7f2480faR1022" data-line-number="1022" class="blob-num blob-num-context js-linkable-line-number js-blob-rnum">
Original file line number Diff line number Diff line change
Expand Up @@ -1016,11 +1016,12 @@ static PyObject *GetResult(ctypes_state *st,
if (info->getfunc && !_ctypes_simple_instance(st, restype)) {
retval = info->getfunc(result, info->size);
/* If restype is py_object (detected by comparing getfunc with
O_get), we have to call Py_DECREF because O_get has already
called Py_INCREF.
O_get), we have to call Py_XDECREF because O_get has already
called Py_INCREF, unless the result was NULL, in which case
an error is set (by the called function, or by O_get).
*/
if (info->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
Py_DECREF(retval);
Py_XDECREF(retval);
}
}
else {
Expand Down
Loading
0