Skip to content

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

Closed

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

Activity

  1. sergey-miryanov commented on Mar 17, 2025

    @sergey-miryanov
    ContributorAuthor

    Related to gh-127945

  2. added a commit that references this issue on Apr 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions