Repository navigation
gh-162539: Prevent ctypes.resize() from freeing memory during a store - #163148
White-Reaper0 wants to merge 5 commits into
Conversation
|
Thank you for your interest in contributing to Python. This is a community-driven project, and we want it to be a welcoming place to learn and collaborate. Contributors are responsible for reviewing and understanding what they submit, checking its claims, and being able to explain changes in their own words. This helps reviewers focus on the contribution and leaves more time to support other contributors. This contribution appears to have been authored with AI assistance. Please explain your contribution in your own words and describe how you checked its correctness. Please read our guidelines for using AI tools. |
|
📖 2 files modified Preview · build overview · cpython-previews · built Dec. 4, 2026, 3:55 p.m. UTC |
picnixz
left a comment
There was a problem hiding this comment.
I think it's just better if people don't do that. I don't see a need to really fix this part. It looks like a code.__replace__ situation where people are messing up with pointers in bad ways (concurrent mutations really looks weird IMO).
None of the tests look legitimate code, so I would first want to discuss the acceptability of such issue in the first place.
| Every _PyCData_Pin() must be balanced by exactly one _PyCData_Unpin() on | ||
| the same object, on every path including errors. */ | ||
|
|
||
| static inline CDataObject * |
There was a problem hiding this comment.
Why static inline functions in .h? why not an extern function?
There was a problem hiding this comment.
done, I will move this to _ctypes.c
|
A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated. Once you have made the requested changes, please leave a comment on this pull request containing the phrase |
…size() ctypes.resize() can move or free an object's memory block while other code still uses an address inside it. Add a pin count on the object that owns the memory, helpers to pin and unpin it (atomic on the free-threaded build), and make resize() raise BufferError while the block is pinned. This is groundwork only: nothing pins yet. Follow-up commits pin the block during stores, for sub-objects, for exported buffers and for pointers. The counter fits in existing padding, so objects do not grow on 64-bit platforms.
Storing into a structure field, an array item or the value of a simple type converts the Python value after the destination address has been computed. The conversion can run Python code (__index__, __float__, __bool__, or calling a structure type for a tuple), and if that code called ctypes.resize() on the object, the store wrote into the freed memory block. Pin the object that owns the memory for the duration of the store in PyCData_set() and in the value setter of simple types, so resize() raises BufferError instead. Writes through a sub-object pin the outer object that owns the memory.
Like realloc(), resize() may move the memory block, so pointers, byref() results and addresses taken before the call become invalid. ctypes cannot track raw addresses, so this is documented rather than enforced. Also document the BufferError raised while the buffer is in use.
Move the pin and unpin helpers from static inline functions in ctypes.h to extern functions in _ctypes.c, as suggested in review.
c8adb89 to
6f59c31
Compare
|
@ZeroIntensity That looks al ot like buffer exports, but I'm not sure we want that kind of safety on ctypes. WDYT? |
|
Fair point, nobody really writes code like the tests. What bugged me is that it's a use-after-free from plain Python: no raw pointers, just an assignment, And yes, it's basically the buffer-export idea on purpose, same as I used an AI assistant to help dig into this and draft the patch; I've checked every line. Tested with an ASan build, tests crash without the fix and pass with it, test_ctypes passes on the default and free-threaded builds. If you'd both rather not fix this, no problem, I'll close it. Maybe just the |
A sub-object such as s.field or array[i] points into its base's memory block. If ctypes.resize() moved or freed that block while the sub-object was alive, the sub-object kept using freed memory. Pin the base when such a sub-object is created and unpin it when the sub-object is cleared, so resize() raises BufferError while any sub-object of the block is alive. A sub-object whose memory is not inside its base's block, such as a pointer's .contents, does not pin.
|
This is clearly an 100% AI-generated PR. A rule of thumb if you're actually doing human review: if you don't find anything to change, especially in a PR this large, then you likely don't understand the code enough to properly review it. Rant aside, I'm going to reject this fix, as this is an extremely complicated solution for a bug that never happens in practice. I'm going to keep the issue open until I get around to properly triaging it, but it'll go under my "low priority" umbrella for ctypes. There's a long backlog of real ctypes bugs that we need to deal with before attacking artificial cases like this.
I can do you one better! |
(AI Assisted) Human Reviewed
Summary
ctypes.resize()can move an object's memory block to a new address and free the old one, likerealloc(). Nothing stopped this while other code was still using an address inside the old block, so a pure-Python program could make ctypes read and write freed memory. This PR makesresize()raiseBufferErrorwhile the block is in use.The problem
A ctypes object stores its data in a C memory block (
b_ptr). Two kinds of code keep an address inside that block:1. A store in progress (the case reported in gh-162539). For
s.val = x, ctypes computes the destination address first and convertsxafterwards. The conversion can run Python code (__index__,__float__,__bool__, or calling a structure type for a tuple):The same happens for array items,
.valueon simple types, float/bool/bit-fields, tuple-to-structure assignment and stores through a nested structure.2. A live sub-object.
inner = s.field(orarray[i]of a structure/array type) returns an object that points intos's block. Afterresize(s, ...),innerreads and writes the freed block, with no re-entrant code needed.Under AddressSanitizer every one of these is a
heap-use-after-free.The fix
b_pinscounter (it fits into existing padding, so objects do not grow on 64-bit platforms).resize()raisesBufferError: Memory cannot be resized while it is in usewhile it is non-zero. This is the same rulebytearrayapplies to buffer exports.PyCData_set()and the simple-typevaluesetter pin the object that owns the memory for the duration of the store, on success and on error. A store through a sub-object pins the outermost owner.PyCData_FromBaseObj()pins the base when it creates a sub-object whose memory lies inside the base's block, andPyCData_clear()unpins it. Each sub-object pins its immediate base, and theb_basereferences keep the whole chain pinned. A pointer's.contentsis not inside the pointer's block, so it does not pin.tp_alloc(), which can run the GC.resize()now states that, likerealloc(), it can move the buffer, so pointers,byref()andaddressof()results taken before the call become invalid (raw addresses cannot be tracked), and that it raisesBufferErrorwhile the buffer is in use.Behaviour change
resize()now raisesBufferErrorinstead of corrupting memory while a store is running or while a structure/array sub-object of the buffer is alive. Fields of simple types return Python values, not sub-objects, so they are not affected. Code that kept a sub-object across aresize()was relying on undefined behaviour.Not covered
memoryviewand other buffer exports: same problem, tracked in Data race: ctypesPyCData_NewGetBufferreadsb_ptrwithout the critical section_ctypes_resizeholds #154524. I asked there whether that fix should build on this pin count.pointer(),cast(),byref(),addressof()): documented, not enforced.Testing
Lib/test/test_ctypes/test_varsize_struct.py: 8 tests for stores that callresize()during conversion.Lib/test/test_ctypes/test_resize_pins.py: 14 tests for sub-objects (structure and union fields, nested and chained sub-objects, array items and slices, arrays of arrays, the GC clearing a cycle in either order, pointers not pinning, and concurrent sub-object use withresize()).BufferErrorafter; the new tests fail without the fix.test_ctypespasses on the default (ASan, debug) and free-threaded builds; the refleak run (-R 3:3) on the new tests is clean.Authors
Mohammed Talha (pin count, stores, documentation) and @Aaquibsz (sub-objects). An AI assistant helped with the investigation and drafting; we reviewed and tested every change ourselves.