Repository navigation
[mypyc] Fix memory safety bugs in librt.vecs - #22421
Conversation
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
left a comment
There was a problem hiding this comment.
Thanks for the PR! Mostly looks good, I just have a few ideas to improve performance a bit.
| // 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) { |
There was a problem hiding this comment.
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))
There was a problem hiding this comment.
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.
| } | ||
| item = PyList_GET_ITEM(seq, i); | ||
| } else { | ||
| item = PyTuple_GET_ITEM(seq, i); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
This fixes several memory safety bugs in
librt.vecs, with one commit per issue:PyObject_NewVar/PyObject_GC_NewVardon't checkbasicsize + n * itemsizefor overflow. As a result,vec[i64](capacity=2**61)allocated a tiny buffer and then wrote past its end. It now raisesMemoryError. Separately, the interpretedvec[i64](capacity=n)constructor boxed an error value, which caused aSystemError.v[i] = xdecref'd the old item before storing the new one. This affected compiled code and the interpreted setter for nested vecs. A__del__that readsv[i]saw a freed object.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__.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.==,remove()and compiledx in v, an__eq__that replaced the item in the vec caused a use-after-free.vec[A]whereA = vec[C]decremented C's refcount on every evaluation. It incref'dA, but dealloc decrefsC, so the class was eventually freed.Examples, interpreted (before this PR these segfault or read freed memory):
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-*.testfiles. Most are__del__/__eq__-based, which is deterministic under refcounting. The affected refcount IR tests were updated.