Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions mypyc/irbuild/vec.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,11 +367,13 @@ def vec_set_item(
item_type = vtype.item_type
item = builder.coerce(item, item_type, line)
if item_type.is_refcounted:
# Read an unborrowed reference to cause a decref to be
# generated for the old item.
# Decref the old item only after the new item has been stored, since
# the decref can run arbitrary code (such as __del__) that accesses the vec.
old_item = vec_load_mem_item(builder, item_addr, item_type, can_borrow=True)
vec_set_mem_item(builder, item_addr, item_type, item)
builder.add(DecRef(old_item))
vec_set_mem_item(builder, item_addr, item_type, item)
else:
vec_set_mem_item(builder, item_addr, item_type, item)
builder.keep_alive([base], line)


Expand Down Expand Up @@ -568,7 +570,9 @@ def vec_contains(builder: LowLevelIRBuilder, vec: Value, target: Value, line: in
for_loop = builder.begin_for(
items_start, items_end, Integer(step, c_pyssize_t_rprimitive), signed=False
)
item = vec_load_mem_item(builder, for_loop.index, item_type, can_borrow=True)
# Don't borrow the item, since the comparison can run arbitrary code that
# replaces the item in the vec
item = vec_load_mem_item(builder, for_loop.index, item_type)
comp = builder.binary_op(item, target, "==", line)
false = BasicBlock()
builder.add(Branch(comp, true, false, Branch.BOOL))
Expand Down
14 changes: 12 additions & 2 deletions mypyc/lib-rt/vecs/librt_vecs.c
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,10 @@ static PyObject *vec_class_getitem(PyObject *type, PyObject *item)
p = PyObject_GC_New(VecGenericAlias, &VecGenericAliasType);
if (p == NULL)
goto error;
Py_INCREF(item);
// Note that 'item' may be a different object than the item type (e.g. vec[t]
// alias), so incref the item type, since it will be decref'd on dealloc
if (!Vec_IsMagicItemType(item_type))
Py_INCREF(VEC_ITEM_TYPE(item_type));
p->item_type = item_type;
p->depth = depth;
PyObject_GC_Track(p);
Expand Down Expand Up @@ -494,7 +497,14 @@ PyObject *Vec_GenericRichcompare(Py_ssize_t *len, PyObject **items,
cmp = 0;
} else {
for (Py_ssize_t i = 0; i < *len && i < *other_len; i++) {
int itemcmp = PyObject_RichCompareBool(items[i], other_items[i], Py_EQ);
// The comparison can run arbitrary code that replaces the items
PyObject *x = items[i];
PyObject *y = other_items[i];
Py_INCREF(x);
Py_INCREF(y);
int itemcmp = PyObject_RichCompareBool(x, y, Py_EQ);
Py_DECREF(x);
Py_DECREF(y);
if (itemcmp < 0)
return NULL;
if (!itemcmp) {
Expand Down
17 changes: 13 additions & 4 deletions mypyc/lib-rt/vecs/vec_nested.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ static inline PyObject *box_vec_item_by_index(VecNested v, Py_ssize_t index) {
// and items. Caller *must* also call vec_track_buffer on the returned vec but only
// after initializing the items.
static VecNested vec_alloc(Py_ssize_t size, size_t item_type, size_t depth) {
if (size > VEC_MAX_BUF_ITEMS(VecNestedBufObject, sizeof(VecNestedBufItem))) {
PyErr_NoMemory();
return vec_error();
}
VecNestedBufObject *buf = PyObject_GC_NewVar(VecNestedBufObject, &VecNestedBufType, size);
if (buf == NULL)
return vec_error();
Expand Down Expand Up @@ -188,9 +192,10 @@ static int vec_ass_item(PyObject *self, Py_ssize_t i, PyObject *o) {
if (VecNested_UnboxItem(v, o, &item) < 0)
return -1;
VecNestedBufObject *v_buf = VEC_BUF(v);
VecNestedBufItem old = v.items[i];
VecNested_ItemXINCREF(v_buf, item);
VecNested_ItemXDECREF(v_buf, v.items[i]);
v.items[i] = item;
VecNested_ItemXDECREF(v_buf, old);
return 0;
} else {
PyErr_SetString(PyExc_IndexError, "index out of range");
Expand Down Expand Up @@ -269,8 +274,9 @@ VecNested VecNested_Append(VecNested vec, VecNestedBufItem x) {
VecNested_ItemXINCREF(vec_buf, x);
if (vec.len < cap) {
// Slot may have duplicate ref from prior remove/pop
VecNested_ItemXDECREF(vec_buf, vec.items[vec.len]);
VecNestedBufItem old = vec.items[vec.len];
vec.items[vec.len] = x;
VecNested_ItemXDECREF(vec_buf, old);
vec.len++;
return vec;
} else {
Expand Down Expand Up @@ -367,8 +373,9 @@ VecNested VecNested_ExtendVec(VecNested dst, VecNested src) {
VecNestedBufItem item = src.items[i];
VecNested_ItemXINCREF(src_buf, item);
// Slot may have duplicate ref from prior remove/pop
VecNested_ItemXDECREF(dst_buf, dst.items[dst.len + i]);
VecNestedBufItem old = dst.items[dst.len + i];
dst.items[dst.len + i] = item;
VecNested_ItemXDECREF(dst_buf, old);
}
dst.len = new_len;
return dst;
Expand Down Expand Up @@ -449,11 +456,13 @@ VecNested VecNested_Remove(VecNested self, VecNestedBufItem arg) {
}
if (match) {
if (i < self.len - 1) {
VecNested_ItemCLEAR(self_buf, &items[i]);
// Decref the removed item last, since it could run arbitrary code
VecNestedBufItem removed = items[i];
for (; i < self.len - 1; i++) {
items[i] = items[i + 1];
}
VecNested_ItemXINCREF(self_buf, items[self.len - 1]);
VecNested_ItemXDECREF(self_buf, removed);
}
self.len--;
Py_DECREF(boxed_arg);
Expand Down
14 changes: 12 additions & 2 deletions mypyc/lib-rt/vecs/vec_t.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ static inline VecT vec_error() {
}

static inline VecTBufObject *alloc_buf(Py_ssize_t size, size_t item_type) {
if (size > VEC_MAX_BUF_ITEMS(VecTBufObject, sizeof(PyObject *))) {
PyErr_NoMemory();
return NULL;
}
VecTBufObject *buf = PyObject_GC_NewVar(VecTBufObject, &VecTBufType, size);
if (buf == NULL)
return NULL;
Expand Down Expand Up @@ -486,7 +490,11 @@ VecT VecT_Remove(VecT v, PyObject *arg) {
if (items[i] == arg)
match = 1;
else {
int itemcmp = PyObject_RichCompareBool(items[i], arg, Py_EQ);
// The comparison can run arbitrary code that replaces the item
PyObject *item = items[i];
Py_INCREF(item);
int itemcmp = PyObject_RichCompareBool(item, arg, Py_EQ);
Py_DECREF(item);
if (itemcmp < 0) {
// The input v is being consumed/stolen by this function, so on error
// we must decref it to avoid leaking the buffer.
Expand All @@ -497,13 +505,15 @@ VecT VecT_Remove(VecT v, PyObject *arg) {
}
if (match) {
if (i < v.len - 1) {
Py_CLEAR(items[i]);
// Decref the removed item last, since it could run arbitrary code
PyObject *removed = items[i];
for (; i < v.len - 1; i++) {
items[i] = items[i + 1];
}
// Keep a duplicate item, since there could be another reference
// to the buffer with a longer length, and they expect a valid reference.
Py_XINCREF(items[v.len - 1]);
Py_XDECREF(removed);
}
v.len--;
// Return the stolen reference without INCREF
Expand Down
28 changes: 24 additions & 4 deletions mypyc/lib-rt/vecs/vec_template.c
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@ inline static VEC vec_error() {
static VEC vec_alloc(Py_ssize_t size)
{
BUF_OBJECT *buf;
/* TODO: Check for overflow */
if (size == 0) {
buf = NULL;
} else {
if (size > VEC_MAX_BUF_ITEMS(BUF_OBJECT, sizeof(ITEM_C_TYPE))) {
PyErr_NoMemory();
return vec_error();
}
buf = PyObject_NewVar(BUF_OBJECT, &BUF_TYPE, size);
if (buf == NULL)
return vec_error();
Expand Down Expand Up @@ -173,8 +176,22 @@ static inline VEC vec_from_sequence(PyObject *seq, int64_t cap, const int is_lis
// Tuples are immutable, so fall through to the shared loop below
#endif
for (Py_ssize_t i = 0; i < n; i++) {
PyObject *item = is_list ? PyList_GET_ITEM(seq, i) : PyTuple_GET_ITEM(seq, i);
ITEM_C_TYPE x = UNBOX_ITEM(item);
ITEM_C_TYPE x;
if (is_list) {
// Unboxing can run arbitrary code (such as __index__) that modifies the list,
// so recheck the size and hold a reference to the item
if (i >= PyList_GET_SIZE(seq)) {
n = i;
break;
}
PyObject *item = PyList_GET_ITEM(seq, i);
Py_INCREF(item);
x = UNBOX_ITEM(item);
Py_DECREF(item);
} else {
// Tuples are immutable, so a borrowed reference is fine
x = UNBOX_ITEM(PyTuple_GET_ITEM(seq, i));
}
if (IS_UNBOX_ERROR(x)) {
VEC_DECREF(v);
return vec_error();
Expand Down Expand Up @@ -280,7 +297,10 @@ static PyObject *vec_new(PyTypeObject *self, PyObject *args, PyObject *kw) {
return NULL;
}
if (init == NULL) {
return FUNC(Box)(FUNC(New)(0, cap));
VEC v = FUNC(New)(0, cap);
if (VEC_IS_ERROR(v))
return NULL;
return FUNC(Box)(v);
} else {
VEC v = FUNC(FromIterable)(init, cap);
if (VEC_IS_ERROR(v))
Expand Down
7 changes: 7 additions & 0 deletions mypyc/lib-rt/vecs/vecs_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,11 @@
// The base vec type
extern PyTypeObject VecType;

// Maximum number of items in a buffer object with the given struct type and item size.
// Allocating more would overflow the allocation size, so this must be checked before
// calling PyObject_NewVar or PyObject_GC_NewVar, since they don't check for overflow.
// This is a compile-time constant, so the division is free.
#define VEC_MAX_BUF_ITEMS(buf_struct, item_size) \
((PY_SSIZE_T_MAX - (Py_ssize_t)sizeof(buf_struct)) / (Py_ssize_t)(item_size))

#endif // VECS_INTERNAL_H_INCL
1 change: 1 addition & 0 deletions mypyc/test-data/fixtures/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ class UnicodeEncodeError(RuntimeError): pass
class UnicodeDecodeError(RuntimeError): pass
class NotImplementedError(RuntimeError): pass
class ReferenceError(Exception): pass
class MemoryError(Exception): pass

class StopIteration(Exception):
value: Any
Expand Down
46 changes: 45 additions & 1 deletion mypyc/test-data/refcount.test
Original file line number Diff line number Diff line change
Expand Up @@ -1795,11 +1795,55 @@ L5:
r7 = r5 * 8
r8 = r6 + r7
r9 = borrow load_mem r8 :: builtins.str*
dec_ref r9
inc_ref x
set_mem r8, x :: builtins.str*
dec_ref r9
return 1

[case testVecTContains_64bit]
from librt.vecs import vec

def f(v: vec[str], x: str) -> bool:
return x in v
[out]
def f(v, x):
v :: vec[str]
x :: str
r0 :: native_int
r1 :: ptr
r2 :: native_int
r3, r4 :: ptr
r5 :: bit
r6 :: str
r7 :: bool
r8 :: ptr
r9 :: bool
L0:
r0 = v.len
r1 = v.items
r2 = r0 * 8
r3 = r1 + r2
r4 = r1
L1:
r5 = r4 < r3 :: unsigned
if r5 goto L2 else goto L4 :: bool
L2:
r6 = load_mem r4 :: builtins.str*
r7 = CPyStr_Equal(r6, x)
dec_ref r6
if r7 goto L5 else goto L3 :: bool
L3:
r8 = r4 + 8
r4 = r8
goto L1
L4:
r9 = 0
goto L6
L5:
r9 = 1
L6:
return r9

[case testVecTConstructFromListMultiply_64bit]
from typing import Optional
from librt.vecs import vec
Expand Down
11 changes: 10 additions & 1 deletion mypyc/test-data/run-vecs-i64.test
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ from typing import Final, Any, Iterable, Tuple
from mypy_extensions import i64, i32
from librt.vecs import vec, append, extend, remove, pop

from testutil import assertRaises
from testutil import assertRaises, is_64_bit_platform

ERROR: Final = -113

Expand Down Expand Up @@ -285,6 +285,15 @@ def test_construct_from_array() -> None:
v2 = vec[i64](a2)
assert len(v2) == 0

def test_construct_with_too_large_capacity() -> None:
if not is_64_bit_platform():
return
for n in [i64(2**61), i64(2**63 - 1)]:
with assertRaises(MemoryError):
vec[i64](capacity=n)
with assertRaises(MemoryError):
vec[i64]([1], capacity=n)

def test_equality() -> None:
v0 = vec[i64]()
v0b = vec[i64]()
Expand Down
40 changes: 39 additions & 1 deletion mypyc/test-data/run-vecs-misc-interp.test
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import typing
import librt.vecs
import mypy_extensions

from testutil import assertRaises
from testutil import assertRaises, is_64_bit_platform
from helpers import ClearListOnUnbox

# Access via Any references to force generic operations
vec: Any = librt.vecs.vec
Expand Down Expand Up @@ -522,6 +523,21 @@ def test_cap_negative() -> None:
with assertRaises(ValueError):
vec[t](capacity=-1)

def test_cap_too_large() -> None:
if not is_64_bit_platform():
return
# The buffer size calculation must not overflow
for n in [2**61, 2**62, 2**63 - 1]:
for t in ITEM_TYPES + [str, vec[i64], vec[str]]:
with assertRaises(MemoryError):
vec[t](capacity=n)
with assertRaises(MemoryError):
vec[t]([], capacity=n)
with assertRaises(MemoryError):
vec[t]((), capacity=n)
with assertRaises(MemoryError):
vec[t](iter([]), capacity=n)

def test_cap_buffer_reuse() -> None:
# Verify buffer reuse within cap for each type
v = vec[float]([1.5], capacity=3)
Expand Down Expand Up @@ -567,6 +583,28 @@ def test_extend_bool() -> None:
v = extend(v, [False, True])
assert v == vec[bool]([True, False, True])

def test_construct_from_list_modified_during_unboxing() -> None:
for t in [i64, i32, i16, float]:
lst: list[Any] = []
lst.append(ClearListOnUnbox(lst))
lst.extend([7] * 100)
v = vec[t](lst)
assert v == vec[t]([1])

[file helpers.py]
class ClearListOnUnbox:
def __init__(self, lst):
self.lst = lst

def __index__(self):
self.lst.clear()
# Reuse the freed memory
junk = [bytearray(64) for _ in range(1000)]
return 1

def __float__(self):
return float(self.__index__())

[case testLibrtVecsBufferProtocol_librt]
import struct
from typing import Any
Expand Down
Loading
Loading