Skip to content
Open
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
2 changes: 1 addition & 1 deletion crates/vm/src/builtins/genericalias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ impl Py<PyGenericAlias> {
for exc in &ATTR_EXCEPTIONS {
let exc_obj = (*exc).to_pyobject(vm);
if !dir.__contains__(&exc_obj, vm)? {
dir.append((*exc).to_pyobject(vm));
dir.append(exc_obj, vm)?;
}
}
Ok(dir)
Expand Down
171 changes: 134 additions & 37 deletions crates/vm/src/builtins/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ use crate::common::lock::{
use crate::object::{Traverse, TraverseFn};
use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
builtins::{PyFloat, PyInt, PyStr, PyTuple},
builtins::{
PyDict, PyFloat, PyFrozenSet, PyInt, PySet, PyStr, PyTuple,
dict::{PyDictItems, PyDictKeys, PyDictValues},
},
class::{PyClassDef, PyClassImpl},
convert::ToPyObject,
convert::{IntoPyException, ToPyObject},
function::{Either, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, PySsize},
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
recursion::ReprGuard,
Expand All @@ -27,7 +30,7 @@ use crate::{
};
use rustpython_common::wtf8::Wtf8Buf;

use alloc::fmt;
use alloc::{collections::TryReserveError, fmt};
use core::cell::Cell;
use core::ops::DerefMut;
use core::ptr::NonNull;
Expand Down Expand Up @@ -198,8 +201,21 @@ struct PopArgs {
}

impl PyList {
pub(crate) fn append(&self, object: PyObjectRef) {
self.borrow_vec_mut().push(object);
/// Lock the list and reserve before recording a mutation. On failure the
/// guard is released before the caller drops the item being inserted.
#[inline]
fn try_grow(
&self,
additional: usize,
vm: &VirtualMachine,
) -> PyResult<PyRwLockWriteGuard<'_, Vec<PyObjectRef>>> {
let mut elements = self.elements.write();
if let Err(err) = elements.try_reserve(additional) {
drop(elements);
return Err(err.into_pyexception(vm));
}
self.mutation_counter.fetch_add(1, Ordering::Relaxed);
Ok(elements)
}

pub(crate) fn sort(&self, options: SortOptions, vm: &VirtualMachine) -> PyResult<()> {
Expand Down Expand Up @@ -230,6 +246,14 @@ impl PyList {
result
}

fn try_clone_elements(&self) -> Result<Vec<PyObjectRef>, TryReserveError> {
let source = self.borrow_vec();
let mut elements = Vec::new();
elements.try_reserve_exact(source.len())?;
elements.extend_from_slice(&source);
Ok(elements)
}

fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let other = other.downcast_ref::<Self>().ok_or_else(|| {
vm.new_type_error(format!(
Expand All @@ -238,8 +262,18 @@ impl PyList {
other.class().name()
))
})?;
let mut elements = self.borrow_vec().to_vec();
elements.extend(other.borrow_vec().iter().cloned());
let mut elements = self
.try_clone_elements()
.map_err(|err| err.into_pyexception(vm))?;
{
// Preserve the separate snapshots: no second list lock is held
// while copying self, including when the operands are identical.
let source = other.borrow_vec();
elements.try_reserve_exact(source.len()).map(|()| {
elements.extend_from_slice(&source);
})
}
.map_err(|err| err.into_pyexception(vm))?;
Ok(Self::from(elements).into_ref(&vm.ctx))
}

Expand Down Expand Up @@ -424,8 +458,52 @@ impl PyList {
)]
impl Py<PyList> {
#[pymethod]
pub(crate) fn append(&self, object: PyObjectRef) {
self.payload.append(object)
pub(crate) fn append(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut elements = self.payload.try_grow(1, vm)?;
elements.push(object);
Ok(())
}

/// Snapshot only exact native sources, without invoking their iteration
/// protocol or holding a destination lock. Subclasses use the iterator path.
fn try_extend_snapshot(
iterable: &PyObject,
vm: &VirtualMachine,
) -> PyResult<Option<Vec<PyObjectRef>>> {
let snapshot = if let Some(list) = iterable.downcast_ref_if_exact::<PyList>(vm) {
list.payload().try_clone_elements()
} else if let Some(set) = iterable.downcast_ref_if_exact::<PySet>(vm) {
set.try_elements()
} else if let Some(set) = iterable.downcast_ref_if_exact::<PyFrozenSet>(vm) {
set.try_elements()
} else if let Some(dict) = iterable.downcast_ref_if_exact::<PyDict>(vm) {
dict._as_dict_inner().try_keys()
} else if let Some(keys) = iterable.downcast_ref_if_exact::<PyDictKeys>(vm) {
keys.dict.as_dict()._as_dict_inner().try_keys()
} else if let Some(values) = iterable.downcast_ref_if_exact::<PyDictValues>(vm) {
values.dict.as_dict()._as_dict_inner().try_values()
} else if let Some(items) = iterable.downcast_ref_if_exact::<PyDictItems>(vm) {
let items = items
.dict
.as_dict()
._as_dict_inner()
.try_items()
.map_err(|err| err.into_pyexception(vm))?;
let mut tuples = Vec::new();
tuples
.try_reserve_exact(items.len())
.map_err(|err| err.into_pyexception(vm))?;
// Build Python objects only after releasing the dictionary lock.
tuples.extend(
items
.into_iter()
.map(|(key, value)| vm.new_tuple((key, value)).into()),
);
Ok(tuples)
} else {
return Ok(None);
};
snapshot.map(Some).map_err(|err| err.into_pyexception(vm))
}

#[pymethod]
Expand All @@ -436,36 +514,21 @@ impl Py<PyList> {
return self.borrow_vec_mut().imul(vm, 2);
}
if let Some(tuple) = iterable.downcast_ref_if_exact::<PyTuple>(vm) {
let mut elements = self.borrow_vec_mut();
elements
.try_reserve(tuple.len())
.map_err(|_| vm.no_memory_error())?;
elements.extend_from_slice(tuple.as_slice());
self.payload
.try_grow(tuple.len(), vm)?
.extend_from_slice(tuple.as_slice());
return Ok(());
}
let cls = iterable.class();
if cls.is(vm.ctx.types.list_type)
|| cls.is(vm.ctx.types.set_type)
|| cls.is(vm.ctx.types.frozenset_type)
|| cls.is(vm.ctx.types.dict_type)
|| cls.is(vm.ctx.types.dict_keys_type)
|| cls.is(vm.ctx.types.dict_values_type)
|| cls.is(vm.ctx.types.dict_items_type)
{
// Snapshot mutable native sources before locking the destination.
let mut new_elements =
vm.extract_elements_sized(&iterable, &|| self.borrow_vec().len(), Ok)?;
let mut elements = self.borrow_vec_mut();
elements
.try_reserve(new_elements.len())
.map_err(|_| vm.no_memory_error())?;
elements.append(&mut new_elements);
if let Some(mut new_elements) = Self::try_extend_snapshot(&iterable, vm)? {
self.payload
.try_grow(new_elements.len(), vm)?
.append(&mut new_elements);
return Ok(());
}

let iter = iterable.clone().get_iter(vm)?;
let iter = iterable.get_iter(vm)?;
// Count the destination after the hint: both calls can mutate it.
let hint = vm.length_hint_opt(iterable.clone())?.unwrap_or(8);
let hint = vm.length_hint_opt_ref(&iterable)?.unwrap_or(8);
{
let mut elements = self.borrow_vec_mut();
if elements.len() <= (isize::MAX as usize) - hint {
Expand Down Expand Up @@ -494,10 +557,16 @@ impl Py<PyList> {
}

#[pymethod]
pub(crate) fn insert(&self, index: PySsize, object: PyObjectRef) {
let mut elements = self.borrow_vec_mut();
pub(crate) fn insert(
&self,
index: PySsize,
object: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
let mut elements = self.payload.try_grow(1, vm)?;
let index = elements.saturate_index(index);
elements.insert(index, object);
Ok(())
}

#[pymethod]
Expand All @@ -507,8 +576,12 @@ impl Py<PyList> {
}

#[pymethod]
fn copy(&self, vm: &VirtualMachine) -> PyRef<PyList> {
PyList::from(self.borrow_vec().to_vec()).into_ref(&vm.ctx)
fn copy(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyList>> {
let elements = self
.payload
.try_clone_elements()
.map_err(|err| err.into_pyexception(vm))?;
Ok(PyList::from(elements).into_ref(&vm.ctx))
}

#[pymethod]
Expand Down Expand Up @@ -1252,3 +1325,27 @@ pub(crate) fn init(context: &'static Context) {
PyListIterator::extend_class(context, context.types.list_iterator_type);
PyListReverseIterator::extend_class(context, context.types.list_reverseiterator_type);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn list_reserve_failure_keeps_contents_and_mutation_counter() {
crate::Interpreter::without_stdlib(Default::default()).enter(|vm| {
let value: PyObjectRef = vm.ctx.new_int(1).into();
let list = PyList::from(vec![value.clone()]);
let before = list.mutation_counter.load(Ordering::Relaxed);
// This overflows the Vec capacity calculation without requesting memory.
let err = match list.try_grow(usize::MAX, vm) {
Ok(_) => panic!("overflowing capacity was accepted"),
Err(err) => err,
};
assert!(err.class().is(vm.ctx.exceptions.memory_error));
assert_eq!(list.mutation_counter.load(Ordering::Relaxed), before);
let elements = list.borrow_vec();
assert_eq!(elements.len(), 1);
assert!(elements[0].is(&value));
});
}
}
12 changes: 12 additions & 0 deletions crates/vm/src/builtins/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ impl PySet {
self.inner.elements()
}

pub(crate) fn try_elements(
&self,
) -> Result<Vec<PyObjectRef>, alloc::collections::TryReserveError> {
self.inner.content.try_keys()
}

fn union_multi(
&self,
others: impl core::iter::Iterator<Item = PyObjectRef>,
Expand Down Expand Up @@ -154,6 +160,12 @@ impl PyFrozenSet {
self.inner.elements()
}

pub(crate) fn try_elements(
&self,
) -> Result<Vec<PyObjectRef>, alloc::collections::TryReserveError> {
self.inner.content.try_keys()
}

fn union_multi(
&self,
others: impl core::iter::Iterator<Item = PyObjectRef>,
Expand Down
48 changes: 46 additions & 2 deletions crates/vm/src/bytes_inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
},
literal::escape::Escape,
protocol::{BufferFlags, PyBuffer},
sequence::{SequenceExt, SequenceMutExt},
sequence::SequenceExt,
types::PyComparisonOp,
};
/// How a source object that is neither a size nor a string is turned into
Expand Down Expand Up @@ -1273,7 +1273,28 @@ impl PyBytesInner {
}

pub fn imul(&mut self, n: isize, vm: &VirtualMachine) -> PyResult<()> {
self.elements.imul(vm, n)
let bytes = &mut self.elements;
let len = bytes.len();
let n = vm.check_repeat_or_overflow_error(len, n)?;
if n == 0 {
bytes.clear();
} else if len != 0 && n > 1 {
let total = len * n;
bytes
.try_reserve_exact(total - len)
.map_err(|_| vm.no_memory_error())?;
if len == 1 {
bytes.resize(total, bytes[0]);
} else {
// As in CPython's _PyBytes_Repeat, copy from the entire
// initialized prefix instead of copying the seed n - 1 times.
while bytes.len() < total {
let copied = bytes.len().min(total - bytes.len());
bytes.extend_from_within(..copied);
}
}
}
Ok(())
}

pub fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
Expand Down Expand Up @@ -1591,3 +1612,26 @@ pub(crate) fn swapcase_ascii(bytes: &[u8]) -> Vec<u8> {
.map(|&b| if b.is_ascii_alphabetic() { b ^ 0x20 } else { b })
.collect()
}

#[cfg(test)]
mod repeat_tests {
use super::*;

#[test]
fn fallible_in_place_byte_repetition() {
crate::Interpreter::without_stdlib(Default::default()).enter(|vm| {
for len in [0, 1, 2, 3, 8, 65, 1024] {
let seed: Vec<_> = (0..len).map(|i| (i % 251) as u8).collect();
for n in [-1, 0, 1, 2, 3, 7, 16, 17, 64, 65] {
let mut bytes = PyBytesInner::from(seed.clone());
bytes.imul(n, vm).unwrap();
assert_eq!(bytes.as_bytes(), seed.repeat(n.max(0) as usize));
}
}
let mut bytes = PyBytesInner::from(vec![1, 2]);
let err = bytes.imul(isize::MAX, vm).unwrap_err();
assert!(err.class().is(vm.ctx.exceptions.memory_error));
assert_eq!(bytes.as_bytes(), [1, 2]);
});
}
}
Loading
Loading