Skip to content

ctypes.Pointer.get_contents doesn't hold the object's lock for long enough #131974

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

Closed
Tracked by #127945
ZeroIntensity opened this issue Apr 1, 2025 · 0 comments
Closed
Tracked by #127945
Assignees
Labels
topic-ctypes topic-free-threading type-bug An unexpected behavior, bug, or error

Comments

@ZeroIntensity
Copy link
Member

ZeroIntensity commented Apr 1, 2025

Bug report

Bug description:

As @kumaraditya303 mentioned, ctypes.Pointer.get_contents has a thread safety bug that I missed when I originally fixed it.

Pointer_get_contents(PyObject *self, void *closure)
{
void *deref = locked_deref(_CDataObject_CAST(self));
if (deref == NULL) {
PyErr_SetString(PyExc_ValueError,
"NULL pointer access");
return NULL;
}
ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
StgInfo *stginfo;
if (PyStgInfo_FromObject(st, self, &stginfo) < 0) {
return NULL;
}
assert(stginfo); /* Cannot be NULL for pointer instances */
return PyCData_FromBaseObj(st, stginfo->proto, self, 0, deref);
}

Dereferencing the pointer is locked, but it's unsafe to call PyCData_FromBaseObj without holding the lock, because the pointer might be invalidated concurrently. I suspect this kind of bug exists with other uses of locked_deref too.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-ctypes topic-free-threading type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants