Skip to content

Commit 67f8600

Browse files
committed
WIP: Add dynamic borrow checking for dereferencing NumPy arrays.
1 parent 61882e3 commit 67f8600

File tree

7 files changed

+292
-363
lines changed

7 files changed

+292
-363
lines changed

examples/simple-extension/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use numpy::ndarray::{ArrayD, ArrayViewD, ArrayViewMutD};
2-
use numpy::{Complex64, IntoPyArray, PyArray1, PyArrayDyn, PyReadonlyArrayDyn};
2+
use numpy::{
3+
Complex64, IntoPyArray, PyArray1, PyArrayDyn, PyReadonlyArrayDyn, PyReadwriteArrayDyn,
4+
};
35
use pyo3::{
46
pymodule,
57
types::{PyDict, PyModule},
@@ -41,8 +43,8 @@ fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
4143
// wrapper of `mult`
4244
#[pyfn(m)]
4345
#[pyo3(name = "mult")]
44-
fn mult_py(a: f64, x: &PyArrayDyn<f64>) {
45-
let x = unsafe { x.as_array_mut() };
46+
fn mult_py(a: f64, mut x: PyReadwriteArrayDyn<f64>) {
47+
let x = x.as_array_mut();
4648
mult(a, x);
4749
}
4850

src/array.rs

Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use pyo3::{
1818
Python, ToPyObject,
1919
};
2020

21+
use crate::borrow::{PyReadonlyArray, PyReadwriteArray};
2122
use crate::convert::{ArrayExt, IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
2223
use crate::dtype::Element;
2324
use crate::error::{DimensionalityError, FromVecError, NotContiguousError, TypeError};
@@ -190,18 +191,8 @@ impl<T, D> PyArray<T, D> {
190191
}
191192

192193
#[inline(always)]
193-
fn check_flag(&self, flag: c_int) -> bool {
194-
unsafe { *self.as_array_ptr() }.flags & flag == flag
195-
}
196-
197-
#[inline(always)]
198-
pub(crate) fn get_flag(&self) -> c_int {
199-
unsafe { *self.as_array_ptr() }.flags
200-
}
201-
202-
/// Returns a temporally unwriteable reference of the array.
203-
pub fn readonly(&self) -> crate::PyReadonlyArray<T, D> {
204-
self.into()
194+
fn check_flags(&self, flags: c_int) -> bool {
195+
unsafe { *self.as_array_ptr() }.flags & flags != 0
205196
}
206197

207198
/// Returns `true` if the internal data of the array is C-style contiguous
@@ -223,18 +214,17 @@ impl<T, D> PyArray<T, D> {
223214
/// });
224215
/// ```
225216
pub fn is_contiguous(&self) -> bool {
226-
self.check_flag(npyffi::NPY_ARRAY_C_CONTIGUOUS)
227-
| self.check_flag(npyffi::NPY_ARRAY_F_CONTIGUOUS)
217+
self.check_flags(npyffi::NPY_ARRAY_C_CONTIGUOUS | npyffi::NPY_ARRAY_F_CONTIGUOUS)
228218
}
229219

230220
/// Returns `true` if the internal data of the array is Fortran-style contiguous.
231221
pub fn is_fortran_contiguous(&self) -> bool {
232-
self.check_flag(npyffi::NPY_ARRAY_F_CONTIGUOUS)
222+
self.check_flags(npyffi::NPY_ARRAY_F_CONTIGUOUS)
233223
}
234224

235225
/// Returns `true` if the internal data of the array is C-style contiguous.
236226
pub fn is_c_contiguous(&self) -> bool {
237-
self.check_flag(npyffi::NPY_ARRAY_C_CONTIGUOUS)
227+
self.check_flags(npyffi::NPY_ARRAY_C_CONTIGUOUS)
238228
}
239229

240230
/// Get `Py<PyArray>` from `&PyArray`, which is the owned wrapper of PyObject.
@@ -823,28 +813,37 @@ impl<T: Element, D: Dimension> PyArray<T, D> {
823813
ToPyArray::to_pyarray(arr, py)
824814
}
825815

826-
/// Get the immutable view of the internal data of `PyArray`, as
827-
/// [`ndarray::ArrayView`](https://docs.rs/ndarray/latest/ndarray/type.ArrayView.html).
816+
/// Get an immutable borrow of the NumPy array
817+
pub fn readonly(&self) -> PyReadonlyArray<'_, T, D> {
818+
PyReadonlyArray::try_new(self).expect("NumPy array already borrowed")
819+
}
820+
821+
/// Get a mutable borrow of the NumPy array
822+
pub fn readwrite(&self) -> PyReadwriteArray<'_, T, D> {
823+
PyReadwriteArray::try_new(self).expect("NumPy array already borrowed")
824+
}
825+
826+
/// Returns the internal array as [`ArrayView`].
828827
///
829-
/// Please consider the use of safe alternatives
830-
/// ([`PyReadonlyArray::as_array`](../struct.PyReadonlyArray.html#method.as_array)
831-
/// or [`to_array`](#method.to_array)) instead of this.
828+
/// See also [`PyArrayRef::as_array`].
832829
///
833830
/// # Safety
834-
/// If the internal array is not readonly and can be mutated from Python code,
835-
/// holding the `ArrayView` might cause undefined behavior.
831+
///
832+
/// The existence of an exclusive reference to the internal data, e.g. `&mut [T]` or `ArrayViewMut`, implies undefined behavior.
836833
pub unsafe fn as_array(&self) -> ArrayView<'_, T, D> {
837834
let (shape, ptr, inverted_axes) = self.ndarray_shape_ptr();
838835
let mut res = ArrayView::from_shape_ptr(shape, ptr);
839836
inverted_axes.invert(&mut res);
840837
res
841838
}
842839

843-
/// Returns the internal array as [`ArrayViewMut`]. See also [`as_array`](#method.as_array).
840+
/// Returns the internal array as [`ArrayViewMut`].
841+
///
842+
/// See also [`PyArrayRefMut::as_array_mut`].
844843
///
845844
/// # Safety
846-
/// If another reference to the internal data exists(e.g., `&[T]` or `ArrayView`),
847-
/// it might cause undefined behavior.
845+
///
846+
/// The existence of another reference to the internal data, e.g. `&[T]` or `ArrayView`, implies undefined behavior.
848847
pub unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D> {
849848
let (shape, ptr, inverted_axes) = self.ndarray_shape_ptr();
850849
let mut res = ArrayViewMut::from_shape_ptr(shape, ptr);
@@ -920,7 +919,7 @@ impl<D: Dimension> PyArray<PyObject, D> {
920919
///
921920
/// let pyarray = PyArray::from_owned_object_array(py, array);
922921
///
923-
/// assert!(pyarray.readonly().get(0).unwrap().as_ref(py).is_instance::<CustomElement>().unwrap());
922+
/// assert!(pyarray.readonly().as_array().get(0).unwrap().as_ref(py).is_instance::<CustomElement>().unwrap());
924923
/// });
925924
/// ```
926925
pub fn from_owned_object_array<'py, T>(py: Python<'py>, arr: Array<Py<T>, D>) -> &'py Self {
@@ -1069,14 +1068,6 @@ impl<T: Element> PyArray<T, Ix1> {
10691068
self.resize_(self.py(), [new_elems], 1, NPY_ORDER::NPY_ANYORDER)
10701069
}
10711070

1072-
/// Iterates all elements of this array.
1073-
/// See [NpySingleIter](../npyiter/struct.NpySingleIter.html) for more.
1074-
pub fn iter<'py>(
1075-
&'py self,
1076-
) -> PyResult<crate::NpySingleIter<'py, T, crate::npyiter::ReadWrite>> {
1077-
crate::NpySingleIterBuilder::readwrite(self).build()
1078-
}
1079-
10801071
fn resize_<D: IntoDimension>(
10811072
&self,
10821073
py: Python,

src/borrow.rs

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
use std::cell::UnsafeCell;
2+
use std::collections::hash_map::{Entry, HashMap};
3+
use std::ops::Deref;
4+
5+
use ndarray::{ArrayView, ArrayViewMut, Dimension, Ix1, Ix2, IxDyn};
6+
use pyo3::{FromPyObject, PyAny, PyResult};
7+
8+
use crate::array::PyArray;
9+
use crate::dtype::Element;
10+
use crate::error::NotContiguousError;
11+
12+
thread_local! {
13+
static BORROW_FLAGS: UnsafeCell<HashMap<usize, isize>> = UnsafeCell::new(HashMap::new());
14+
}
15+
16+
pub struct PyReadonlyArray<'py, T, D>(&'py PyArray<T, D>);
17+
18+
pub type PyReadonlyArray1<'py, T> = PyReadonlyArray<'py, T, Ix1>;
19+
20+
pub type PyReadonlyArray2<'py, T> = PyReadonlyArray<'py, T, Ix2>;
21+
22+
pub type PyReadonlyArrayDyn<'py, T> = PyReadonlyArray<'py, T, IxDyn>;
23+
24+
impl<'py, T, D> Deref for PyReadonlyArray<'py, T, D> {
25+
type Target = PyArray<T, D>;
26+
27+
fn deref(&self) -> &Self::Target {
28+
self.0
29+
}
30+
}
31+
32+
impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadonlyArray<'py, T, D> {
33+
fn extract(obj: &'py PyAny) -> PyResult<Self> {
34+
let array: &'py PyArray<T, D> = obj.extract()?;
35+
Ok(array.readonly())
36+
}
37+
}
38+
39+
impl<'py, T, D> PyReadonlyArray<'py, T, D>
40+
where
41+
T: Element,
42+
D: Dimension,
43+
{
44+
pub(crate) fn try_new(array: &'py PyArray<T, D>) -> Option<Self> {
45+
let address = array as *const PyArray<T, D> as usize;
46+
47+
BORROW_FLAGS.with(|borrow_flags| {
48+
// SAFETY: Called on a thread local variable in a leaf function.
49+
let borrow_flags = unsafe { &mut *borrow_flags.get() };
50+
51+
match borrow_flags.entry(address) {
52+
Entry::Occupied(entry) => {
53+
let readers = entry.into_mut();
54+
55+
let new_readers = readers.wrapping_add(1);
56+
57+
if new_readers <= 0 {
58+
cold();
59+
return None;
60+
}
61+
62+
*readers = new_readers;
63+
}
64+
Entry::Vacant(entry) => {
65+
entry.insert(1);
66+
}
67+
}
68+
69+
Some(Self(array))
70+
})
71+
}
72+
73+
pub fn as_array(&self) -> ArrayView<T, D> {
74+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
75+
// and `PyArray` is neither `Send` nor `Sync`
76+
unsafe { self.0.as_array() }
77+
}
78+
79+
pub fn as_slice(&self) -> Result<&[T], NotContiguousError> {
80+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
81+
// and `PyArray` is neither `Send` nor `Sync`
82+
unsafe { self.0.as_slice() }
83+
}
84+
}
85+
86+
impl<'a, T, D> Drop for PyReadonlyArray<'a, T, D> {
87+
fn drop(&mut self) {
88+
let address = self.0 as *const PyArray<T, D> as usize;
89+
90+
BORROW_FLAGS.with(|borrow_flags| {
91+
// SAFETY: Called on a thread local variable in a leaf function.
92+
let borrow_flags = unsafe { &mut *borrow_flags.get() };
93+
94+
let readers = borrow_flags.get_mut(&address).unwrap();
95+
96+
*readers -= 1;
97+
98+
if *readers == 0 {
99+
borrow_flags.remove(&address).unwrap();
100+
}
101+
});
102+
}
103+
}
104+
105+
pub struct PyReadwriteArray<'py, T, D>(&'py PyArray<T, D>);
106+
107+
pub type PyReadwriteArrayDyn<'py, T> = PyReadwriteArray<'py, T, IxDyn>;
108+
109+
impl<'py, T, D> Deref for PyReadwriteArray<'py, T, D> {
110+
type Target = PyArray<T, D>;
111+
112+
fn deref(&self) -> &Self::Target {
113+
self.0
114+
}
115+
}
116+
117+
impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadwriteArray<'py, T, D> {
118+
fn extract(obj: &'py PyAny) -> PyResult<Self> {
119+
let array: &'py PyArray<T, D> = obj.extract()?;
120+
Ok(array.readwrite())
121+
}
122+
}
123+
124+
impl<'py, T, D> PyReadwriteArray<'py, T, D>
125+
where
126+
T: Element,
127+
D: Dimension,
128+
{
129+
pub(crate) fn try_new(array: &'py PyArray<T, D>) -> Option<Self> {
130+
let address = array as *const PyArray<T, D> as usize;
131+
132+
BORROW_FLAGS.with(|borrow_flags| {
133+
// SAFETY: Called on a thread local variable in a leaf function.
134+
let borrow_flags = unsafe { &mut *borrow_flags.get() };
135+
136+
match borrow_flags.entry(address) {
137+
Entry::Occupied(entry) => {
138+
let writers = entry.into_mut();
139+
140+
if *writers != 0 {
141+
cold();
142+
return None;
143+
}
144+
145+
*writers = -1;
146+
}
147+
Entry::Vacant(entry) => {
148+
entry.insert(-1);
149+
}
150+
}
151+
152+
Some(Self(array))
153+
})
154+
}
155+
156+
pub fn as_array(&self) -> ArrayView<T, D> {
157+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
158+
// and `PyArray` is neither `Send` nor `Sync`
159+
unsafe { self.0.as_array() }
160+
}
161+
162+
pub fn as_slice(&self) -> Result<&[T], NotContiguousError> {
163+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
164+
// and `PyArray` is neither `Send` nor `Sync`
165+
unsafe { self.0.as_slice() }
166+
}
167+
168+
pub fn as_array_mut(&mut self) -> ArrayViewMut<T, D> {
169+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
170+
// and `PyArray` is neither `Send` nor `Sync`
171+
unsafe { self.0.as_array_mut() }
172+
}
173+
174+
pub fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError> {
175+
// SAFETY: Thread-local borrow flags ensure aliasing discipline on this thread,
176+
// and `PyArray` is neither `Send` nor `Sync`
177+
unsafe { self.0.as_slice_mut() }
178+
}
179+
}
180+
181+
impl<'a, T, D> Drop for PyReadwriteArray<'a, T, D> {
182+
fn drop(&mut self) {
183+
let address = self.0 as *const PyArray<T, D> as usize;
184+
185+
BORROW_FLAGS.with(|borrow_flags| {
186+
// SAFETY: Called on a thread local variable in a leaf function.
187+
let borrow_flags = unsafe { &mut *borrow_flags.get() };
188+
189+
borrow_flags.remove(&address).unwrap();
190+
});
191+
}
192+
}
193+
#[cold]
194+
#[inline(always)]
195+
fn cold() {}

src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,12 @@
3030
#![allow(clippy::needless_lifetimes)] // We often want to make the GIL lifetime explicit.
3131

3232
pub mod array;
33+
mod borrow;
3334
pub mod convert;
3435
mod dtype;
3536
mod error;
3637
pub mod npyffi;
3738
pub mod npyiter;
38-
mod readonly;
3939
mod slice_container;
4040
mod sum_products;
4141

@@ -46,17 +46,17 @@ pub use crate::array::{
4646
get_array_module, PyArray, PyArray0, PyArray1, PyArray2, PyArray3, PyArray4, PyArray5,
4747
PyArray6, PyArrayDyn,
4848
};
49+
pub use crate::borrow::{
50+
PyReadonlyArray, PyReadonlyArray1, PyReadonlyArray2, PyReadonlyArrayDyn, PyReadwriteArray,
51+
PyReadwriteArrayDyn,
52+
};
4953
pub use crate::convert::{IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
5054
pub use crate::dtype::{dtype, Complex32, Complex64, Element, PyArrayDescr};
5155
pub use crate::error::{DimensionalityError, FromVecError, NotContiguousError, TypeError};
5256
pub use crate::npyffi::{PY_ARRAY_API, PY_UFUNC_API};
5357
pub use crate::npyiter::{
5458
IterMode, NpyIterFlag, NpyMultiIter, NpyMultiIterBuilder, NpySingleIter, NpySingleIterBuilder,
5559
};
56-
pub use crate::readonly::{
57-
PyReadonlyArray, PyReadonlyArray1, PyReadonlyArray2, PyReadonlyArray3, PyReadonlyArray4,
58-
PyReadonlyArray5, PyReadonlyArray6, PyReadonlyArrayDyn,
59-
};
6060
pub use crate::sum_products::{dot, einsum_impl, inner};
6161
pub use ndarray::{array, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn};
6262

0 commit comments

Comments
 (0)