Skip to content
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

ctypes pointer writes are not thread safe #128182

Open
Tracked by #127945
ZeroIntensity opened this issue Dec 22, 2024 · 0 comments
Open
Tracked by #127945

ctypes pointer writes are not thread safe #128182

ZeroIntensity opened this issue Dec 22, 2024 · 0 comments
Labels
3.13 bugs and security fixes 3.14 new features, bugs and security fixes extension-modules C modules in the Modules dir topic-ctypes topic-free-threading type-bug An unexpected behavior, bug, or error

Comments

@ZeroIntensity
Copy link
Member

ZeroIntensity commented Dec 22, 2024

Bug report

Bug description:

Part of #127945.

ctypes C data objects have an internal pointer for what they're looking at (b_ptr). This field itself is generally fine to read non-atomically, because ctypes objects don't tend to overwrite the pointer that they're pointing to, but reading and writing the pointer's contents (such as via memcpy) isn't thread safe. This can be seen primarily with arrays:

from threading import Thread
import ctypes

buffer = (ctypes.c_char_p * 10)()

def main():
    for i in range(100):
        buffer.value = b"hello"
        buffer[1] = b"j"

threads = [Thread(target=main) for _ in range(100)]
for thread in threads:
    thread.start()

There's really only two options here, because the lockless _Py_atomic APIs can't be used for allocations of arbitrary sizes: add a critical section around all functions touching b_ptr, or just add a PyMutex around it.

I think that a mutex is the right way to go here:

  • There's no chance of re-entrancy with memcpy.
  • AC doesn't work for some type slots (e.g. __call__), so they can't get wrapped with @critical_section. We'd need ugly wrapper functions.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

@ZeroIntensity ZeroIntensity added type-bug An unexpected behavior, bug, or error topic-ctypes extension-modules C modules in the Modules dir 3.13 bugs and security fixes topic-free-threading 3.14 new features, bugs and security fixes labels Dec 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.13 bugs and security fixes 3.14 new features, bugs and security fixes extension-modules C modules in the Modules dir topic-ctypes topic-free-threading type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

1 participant