Skip to content

[mypyc] Fix memory safety bugs in librt.vecs - #22421

Merged
JukkaL merged 7 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-vecs-memory-safety
Nov 10, 2026
Merged

JukkaL merged 7 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-vecs-memory-safety

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

This fixes several memory safety bugs in librt.vecs, with one commit per issue:

  1. Allocation size overflow. PyObject_NewVar/PyObject_GC_NewVar don't check basicsize + n * itemsize for overflow. As a result, vec[i64](capacity=2**61) allocated a tiny buffer and then wrote past its end. It now raises MemoryError. Separately, the interpreted vec[i64](capacity=n) constructor boxed an error value, which caused a SystemError.
  2. v[i] = x decref'd the old item before storing the new one. This affected compiled code and the interpreted setter for nested vecs. A __del__ that reads v[i] saw a freed object.
  3. remove() left NULL in a live slot while decref'ing the removed item. Another reference to the same buffer could read the NULL slot from __del__.
  4. vec[i64](lst) read freed list storage. This happened on GIL builds, also for i32, i16 and float, if an item's __index__/__float__ modified the list. Free-threaded builds already handled this case.
  5. Item comparisons used borrowed references. In ==, remove() and compiled x in v, an __eq__ that replaced the item in the vec caused a use-after-free.
  6. vec[A] where A = vec[C] decremented C's refcount on every evaluation. It incref'd A, but dealloc decrefs C, so the class was eventually freed.

Examples, interpreted (before this PR these segfault or read freed memory):

from librt.vecs import vec
from mypy_extensions import i64

vec[i64](capacity=2**61)  # now MemoryError

class C: pass
A = vec[C]
for i in range(1000):
    vec[A]  # C's refcount dropped by 1 each time
C()

The fixes follow the usual CPython pattern: store the new value first and decref the old value last, and hold strong references across calls that can run arbitrary code. Each fix has regression tests in the run-vecs-*.test files. Most are __del__/__eq__-based, which is deterministic under refcounting. The affected refcount IR tests were updated.

PyObject_NewVar and PyObject_GC_NewVar don't check that
basicsize + nitems * itemsize fits in Py_ssize_t. A huge vec capacity,
such as vec[i64](capacity=2**61), wrapped around to a small allocation
and then the buffer was written past its end.

Check the size before allocating every vec buffer, and raise
MemoryError if it's too large. Also don't box an error value in the
interpreted vec[T](capacity=n) constructor for specialized item types,
which caused a SystemError instead of propagating the exception.
Compiled v[i] = x on a vec with reference counted items decref'd the
old item before storing the new one. The decref can run arbitrary code,
such as __del__, which could then read the freed old item through the
vec. The interpreted setter for nested vecs had the same issue, as did
nested vec append and extend when overwriting a stale slot.

Store the new item first, and only then decref the old item, like
vec[t] already does.
remove() on a vec with reference counted items cleared the removed
slot (leaving NULL in it) and decref'd the item before shifting the
remaining items. The decref can run arbitrary code, such as __del__,
which could read the NULL slot through another reference to the same
buffer.

Shift the items first, and decref the removed item last.
Constructing a vec[i64], vec[i32], vec[i16] or vec[float] from a list
cached the list length and used borrowed references to the items, but
unboxing an item can call __index__ or __float__, which can modify the
list. This could read freed list storage. Free-threaded builds already
handled this.

Check the list size on every iteration and hold a reference to the item
while unboxing it.
vec equality, remove() and compiled "x in v" compared items using
borrowed references to the vec items. The comparison can run arbitrary
code, such as __eq__, that replaces the item in the vec and frees it
while it's still being used.

Hold a reference to the items while comparing them.
When evaluating vec[A] where A = vec[C] in interpreted code, the
resulting alias object stored C as its item type, but it incref'd A
instead of C. Since dealloc decrefs the item type, each evaluation
decremented the refcount of C, and C could eventually be freed while
still in use. This also leaked a reference to A, and a reference to the
vec type in vec[vec[i64]] and similar.

Incref the item type that is actually stored, unless it's a magic
value for a value item type.

@JukkaL JukkaL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR! Mostly looks good, I just have a few ideas to improve performance a bit.

Comment thread mypyc/lib-rt/vecs/vecs_internal.h Outdated
// overflow. Otherwise set MemoryError and return -1. This must be checked before
// calling PyObject_NewVar or PyObject_GC_NewVar, since they don't check for overflow.
static inline int Vec_CheckBufSize(PyTypeObject *type, Py_ssize_t size) {
if (size > (PY_SSIZE_T_MAX - type->tp_basicsize) / type->tp_itemsize) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The division can slow things down on some architecture. I think we can avoid it by defining a macro to calculate this without using the type object, e.g. something like this:

// vecs_internal.h
#define VEC_MAX_BUF_ITEMS(buf_struct, item_size) \
    ((PY_SSIZE_T_MAX - (Py_ssize_t)sizeof(buf_struct)) / (Py_ssize_t)(item_size))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in fc1457b. I replaced Vec_CheckBufSize with your VEC_MAX_BUF_ITEMS(buf_struct, item_size) macro and use it in vec_template.c, vec_t.c and vec_nested.c, so the limit is now a compile-time constant. sizeof(buf_struct) already includes one item, so the limit is one item stricter than necessary, which is fine.

Comment thread mypyc/lib-rt/vecs/vec_template.c Outdated
}
item = PyList_GET_ITEM(seq, i);
} else {
item = PyTuple_GET_ITEM(seq, i);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think the incref/decref are unnecessary for tuples, since they are immutable. Can you modify the loop to avoid the refcount traffic when targeting a tuple?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in fc1457b. Tuple items are now unboxed through a borrowed reference with no incref/decref. The list path still increfs the item and rechecks the size, because __index__/__float__ can modify the list.

Compute the maximum number of buffer items from the struct size and item
size, so that it's a compile-time constant and no division is needed at
runtime.

Don't incref/decref tuple items when constructing a vec from a tuple,
since tuples are immutable.

@JukkaL JukkaL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the updates!

@JukkaL
JukkaL merged commit fed26e0 into python:master Nov 10, 2026
18 checks passed
@Jahongir-Qurbonov
Jahongir-Qurbonov deleted the mypyc-vecs-memory-safety branch November 14, 2026 22:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants