Skip to content

ctypes resize and byref/addressof is not thread-safe under free-threaded build #131336

Closed
@sergey-miryanov

Description

@sergey-miryanov

Bug report

Bug description:

I'm reviewing the https://github.com/python/cpython/blob/main/Modules/_ctypes/callproc.c. I believe I found a possible UB if resize and byref/addressof are used from different threads without any locking (AFAIU it is valid for free-threaded build and not for GIL-enabled).

resize does realloc -

void * ptr = PyMem_Realloc(obj->b_ptr, size);
if (ptr == NULL)
return PyErr_NoMemory();
obj->b_ptr = ptr;
obj->b_size = size;

After realloc the old value of obj->b_ptr is no longer valid, and any access to it is UB. If another thread calls addressof

return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
or byref
parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
, it may potentially get UB under heavy contention (I believe it is zero or less real cases so far).

Should we protect them with LOCK_PTR?

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions