Skip to content

gh-162539: Prevent ctypes.resize() from freeing memory during a store - #163148

Closed
White-Reaper0 wants to merge 5 commits into
python:mainfrom
White-Reaper0:gh-162539-ctypes-resize
Closed

White-Reaper0 wants to merge 5 commits into
python:mainfrom
White-Reaper0:gh-162539-ctypes-resize

Conversation

@White-Reaper0

@White-Reaper0 White-Reaper0 commented Dec 4, 2026 •

Copy link
Copy Markdown

(AI Assisted) Human Reviewed

Summary

ctypes.resize() can move an object's memory block to a new address and free the old one, like realloc(). 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 makes resize() raise BufferError while 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 converts x afterwards. The conversion can run Python code (__index__, __float__, __bool__, or calling a structure type for a tuple):

class S(ctypes.Structure):
    _fields_ = [("pad", ctypes.c_char * 4080), ("val", ctypes.c_longlong)]
s = S()

class Value:
    def __index__(self):
        ctypes.resize(s, 1 << 20)   # the block moves, the old one is freed
        return 42

s.val = Value()                     # 42 is written into the freed block

The same happens for array items, .value on simple types, float/bool/bit-fields, tuple-to-structure assignment and stores through a nested structure.

2. A live sub-object. inner = s.field (or array[i] of a structure/array type) returns an object that points into s's block. After resize(s, ...), inner reads 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

  • Pin count. Each ctypes object gets a b_pins counter (it fits into existing padding, so objects do not grow on 64-bit platforms). resize() raises BufferError: Memory cannot be resized while it is in use while it is non-zero. This is the same rule bytearray applies to buffer exports.
  • Stores. PyCData_set() and the simple-type value setter 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.
  • Sub-objects. PyCData_FromBaseObj() pins the base when it creates a sub-object whose memory lies inside the base's block, and PyCData_clear() unpins it. Each sub-object pins its immediate base, and the b_base references keep the whole chain pinned. A pointer's .contents is not inside the pointer's block, so it does not pin.
  • Free-threaded build. The counter is updated atomically. Sub-objects pin before tp_alloc(), which can run the GC.
  • Documentation. resize() now states that, like realloc(), it can move the buffer, so pointers, byref() and addressof() results taken before the call become invalid (raw addresses cannot be tracked), and that it raises BufferError while the buffer is in use.

Behaviour change

resize() now raises BufferError instead 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 a resize() was relying on undefined behaviour.

Not covered

Testing

  • Lib/test/test_ctypes/test_varsize_struct.py: 8 tests for stores that call resize() 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 with resize()).
  • AddressSanitizer debug build: all reproducers were use-after-free before and raise BufferError after; the new tests fail without the fix.
  • test_ctypes passes 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.

@picnixz picnixz added the AI-needs-explanation AI-assisted work that needs further explanation and follow up from the contributor label Dec 4, 2026
@bedevere-app

bedevere-app Bot commented Dec 4, 2026

Copy link
Copy Markdown

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.

@White-Reaper0 White-Reaper0 changed the title Gh 162539 ctypes resize gh-162539: Prevent ctypes.resize() from freeing memory during a store Dec 4, 2026
@White-Reaper0
White-Reaper0 marked this pull request as draft December 4, 2026 14:58
@read-the-docs-community

read-the-docs-community Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

📖 2 files modified


Preview · build overview · cpython-previews · built Dec. 4, 2026, 3:55 p.m. UTC

@picnixz picnixz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread Modules/_ctypes/ctypes.h Outdated
Every _PyCData_Pin() must be balanced by exactly one _PyCData_Unpin() on
the same object, on every path including errors. */

static inline CDataObject *

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why static inline functions in .h? why not an extern function?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, I will move this to _ctypes.c

@bedevere-app

bedevere-app Bot commented Dec 4, 2026

Copy link
Copy Markdown

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 I have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

…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.
@White-Reaper0
White-Reaper0 force-pushed the gh-162539-ctypes-resize branch from c8adb89 to 6f59c31 Compare December 4, 2026 15:12
@picnixz

picnixz commented Dec 4, 2026

Copy link
Copy Markdown
Member

@ZeroIntensity That looks al ot like buffer exports, but I'm not sure we want that kind of safety on ctypes. WDYT?

@White-Reaper0

Copy link
Copy Markdown
Author

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, __index__ and resize(). Same thing happens for array items and .value.

And yes, it's basically the buffer-export idea on purpose, same as bytearray refusing to resize while a memoryview exists. Related: gh-154524.

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 resize() doc note then?

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.
@python-cla-bot

python-cla-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@ZeroIntensity

Copy link
Copy Markdown
Member

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.

What bugged me is that it's a use-after-free from plain Python: no raw pointers, just an assignment, index and resize()

I can do you one better! ctypes.string_at(0). If you Google "how do I crash python", you'll find that ctypes is the top result. ctypes is an interface to C dynamics from pure-Python, and that includes segfaults.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI-needs-explanation AI-assisted work that needs further explanation and follow up from the contributor awaiting changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants