##// END OF EJS Templates
rust-cpython: add sanity check to PySharedState::decrease_leak_count()...
Yuya Nishihara -
r43209:06080afd default
parent child Browse files
Show More
@@ -1,392 +1,396 b''
1 1 // macros.rs
2 2 //
3 3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 4 //
5 5 // This software may be used and distributed according to the terms of the
6 6 // GNU General Public License version 2 or any later version.
7 7
8 8 //! Macros for use in the `hg-cpython` bridge library.
9 9
10 10 use crate::exceptions::AlreadyBorrowed;
11 11 use cpython::{PyResult, Python};
12 12 use std::cell::{Cell, Ref, RefCell, RefMut};
13 13
14 14 /// Manages the shared state between Python and Rust
15 15 #[derive(Default)]
16 16 pub struct PySharedState {
17 17 leak_count: Cell<usize>,
18 18 mutably_borrowed: Cell<bool>,
19 19 }
20 20
21 21 impl PySharedState {
22 22 pub fn borrow_mut<'a, T>(
23 23 &'a self,
24 24 py: Python<'a>,
25 25 pyrefmut: RefMut<'a, T>,
26 26 ) -> PyResult<PyRefMut<'a, T>> {
27 27 if self.mutably_borrowed.get() {
28 28 return Err(AlreadyBorrowed::new(
29 29 py,
30 30 "Cannot borrow mutably while there exists another \
31 31 mutable reference in a Python object",
32 32 ));
33 33 }
34 34 match self.leak_count.get() {
35 35 0 => {
36 36 self.mutably_borrowed.replace(true);
37 37 Ok(PyRefMut::new(py, pyrefmut, self))
38 38 }
39 39 // TODO
40 40 // For now, this works differently than Python references
41 41 // in the case of iterators.
42 42 // Python does not complain when the data an iterator
43 43 // points to is modified if the iterator is never used
44 44 // afterwards.
45 45 // Here, we are stricter than this by refusing to give a
46 46 // mutable reference if it is already borrowed.
47 47 // While the additional safety might be argued for, it
48 48 // breaks valid programming patterns in Python and we need
49 49 // to fix this issue down the line.
50 50 _ => Err(AlreadyBorrowed::new(
51 51 py,
52 52 "Cannot borrow mutably while there are \
53 53 immutable references in Python objects",
54 54 )),
55 55 }
56 56 }
57 57
58 58 /// Return a reference to the wrapped data with an artificial static
59 59 /// lifetime.
60 60 /// We need to be protected by the GIL for thread-safety.
61 61 ///
62 62 /// # Safety
63 63 ///
64 64 /// This is highly unsafe since the lifetime of the given data can be
65 65 /// extended. Do not call this function directly.
66 66 pub unsafe fn leak_immutable<T>(
67 67 &self,
68 68 py: Python,
69 69 data: &PySharedRefCell<T>,
70 70 ) -> PyResult<&'static T> {
71 71 if self.mutably_borrowed.get() {
72 72 return Err(AlreadyBorrowed::new(
73 73 py,
74 74 "Cannot borrow immutably while there is a \
75 75 mutable reference in Python objects",
76 76 ));
77 77 }
78 78 let ptr = data.as_ptr();
79 79 self.leak_count.replace(self.leak_count.get() + 1);
80 80 Ok(&*ptr)
81 81 }
82 82
83 83 /// # Safety
84 84 ///
85 85 /// It's unsafe to update the reference count without knowing the
86 86 /// reference is deleted. Do not call this function directly.
87 87 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
88 self.leak_count
89 .replace(self.leak_count.get().saturating_sub(1));
90 88 if mutable {
89 assert_eq!(self.leak_count.get(), 0);
90 assert!(self.mutably_borrowed.get());
91 91 self.mutably_borrowed.replace(false);
92 } else {
93 let count = self.leak_count.get();
94 assert!(count > 0);
95 self.leak_count.replace(count - 1);
92 96 }
93 97 }
94 98 }
95 99
96 100 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
97 101 ///
98 102 /// Only immutable operation is allowed through this interface.
99 103 #[derive(Debug)]
100 104 pub struct PySharedRefCell<T> {
101 105 inner: RefCell<T>,
102 106 }
103 107
104 108 impl<T> PySharedRefCell<T> {
105 109 pub const fn new(value: T) -> PySharedRefCell<T> {
106 110 Self {
107 111 inner: RefCell::new(value),
108 112 }
109 113 }
110 114
111 115 pub fn borrow(&self) -> Ref<T> {
112 116 // py_shared_state isn't involved since
113 117 // - inner.borrow() would fail if self is mutably borrowed,
114 118 // - and inner.borrow_mut() would fail while self is borrowed.
115 119 self.inner.borrow()
116 120 }
117 121
118 122 pub fn as_ptr(&self) -> *mut T {
119 123 self.inner.as_ptr()
120 124 }
121 125
122 126 pub unsafe fn borrow_mut(&self) -> RefMut<T> {
123 127 // must be borrowed by self.py_shared_state(py).borrow_mut().
124 128 self.inner.borrow_mut()
125 129 }
126 130 }
127 131
128 132 /// Holds a mutable reference to data shared between Python and Rust.
129 133 pub struct PyRefMut<'a, T> {
130 134 inner: RefMut<'a, T>,
131 135 py_shared_state: &'a PySharedState,
132 136 }
133 137
134 138 impl<'a, T> PyRefMut<'a, T> {
135 139 // Must be constructed by PySharedState after checking its leak_count.
136 140 // Otherwise, drop() would incorrectly update the state.
137 141 fn new(
138 142 _py: Python<'a>,
139 143 inner: RefMut<'a, T>,
140 144 py_shared_state: &'a PySharedState,
141 145 ) -> Self {
142 146 Self {
143 147 inner,
144 148 py_shared_state,
145 149 }
146 150 }
147 151 }
148 152
149 153 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
150 154 type Target = RefMut<'a, T>;
151 155
152 156 fn deref(&self) -> &Self::Target {
153 157 &self.inner
154 158 }
155 159 }
156 160 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
157 161 fn deref_mut(&mut self) -> &mut Self::Target {
158 162 &mut self.inner
159 163 }
160 164 }
161 165
162 166 impl<'a, T> Drop for PyRefMut<'a, T> {
163 167 fn drop(&mut self) {
164 168 let gil = Python::acquire_gil();
165 169 let py = gil.python();
166 170 unsafe {
167 171 self.py_shared_state.decrease_leak_count(py, true);
168 172 }
169 173 }
170 174 }
171 175
172 176 /// Allows a `py_class!` generated struct to share references to one of its
173 177 /// data members with Python.
174 178 ///
175 179 /// # Warning
176 180 ///
177 181 /// The targeted `py_class!` needs to have the
178 182 /// `data py_shared_state: PySharedState;` data attribute to compile.
179 183 /// A better, more complicated macro is needed to automatically insert it,
180 184 /// but this one is not yet really battle tested (what happens when
181 185 /// multiple references are needed?). See the example below.
182 186 ///
183 187 /// TODO allow Python container types: for now, integration with the garbage
184 188 /// collector does not extend to Rust structs holding references to Python
185 189 /// objects. Should the need surface, `__traverse__` and `__clear__` will
186 190 /// need to be written as per the `rust-cpython` docs on GC integration.
187 191 ///
188 192 /// # Parameters
189 193 ///
190 194 /// * `$name` is the same identifier used in for `py_class!` macro call.
191 195 /// * `$inner_struct` is the identifier of the underlying Rust struct
192 196 /// * `$data_member` is the identifier of the data member of `$inner_struct`
193 197 /// that will be shared.
194 198 /// * `$leaked` is the identifier to give to the struct that will manage
195 199 /// references to `$name`, to be used for example in other macros like
196 200 /// `py_shared_iterator`.
197 201 ///
198 202 /// # Example
199 203 ///
200 204 /// ```
201 205 /// struct MyStruct {
202 206 /// inner: Vec<u32>;
203 207 /// }
204 208 ///
205 209 /// py_class!(pub class MyType |py| {
206 210 /// data inner: PySharedRefCell<MyStruct>;
207 211 /// data py_shared_state: PySharedState;
208 212 /// });
209 213 ///
210 214 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
211 215 /// ```
212 216 macro_rules! py_shared_ref {
213 217 (
214 218 $name: ident,
215 219 $inner_struct: ident,
216 220 $data_member: ident,
217 221 $leaked: ident,
218 222 ) => {
219 223 impl $name {
220 224 fn borrow_mut<'a>(
221 225 &'a self,
222 226 py: Python<'a>,
223 227 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
224 228 {
225 229 // assert $data_member type
226 230 use crate::ref_sharing::PySharedRefCell;
227 231 let data: &PySharedRefCell<_> = self.$data_member(py);
228 232 self.py_shared_state(py)
229 233 .borrow_mut(py, unsafe { data.borrow_mut() })
230 234 }
231 235
232 236 /// Returns a leaked reference and its management object.
233 237 ///
234 238 /// # Safety
235 239 ///
236 240 /// It's up to you to make sure that the management object lives
237 241 /// longer than the leaked reference. Otherwise, you'll get a
238 242 /// dangling reference.
239 243 unsafe fn leak_immutable<'a>(
240 244 &'a self,
241 245 py: Python<'a>,
242 246 ) -> PyResult<($leaked, &'static $inner_struct)> {
243 247 // assert $data_member type
244 248 use crate::ref_sharing::PySharedRefCell;
245 249 let data: &PySharedRefCell<_> = self.$data_member(py);
246 250 let static_ref =
247 251 self.py_shared_state(py).leak_immutable(py, data)?;
248 252 let leak_handle = $leaked::new(py, self);
249 253 Ok((leak_handle, static_ref))
250 254 }
251 255 }
252 256
253 257 /// Manage immutable references to `$name` leaked into Python
254 258 /// iterators.
255 259 ///
256 260 /// In truth, this does not represent leaked references themselves;
257 261 /// it is instead useful alongside them to manage them.
258 262 pub struct $leaked {
259 263 inner: $name,
260 264 }
261 265
262 266 impl $leaked {
263 267 // Marked as unsafe so client code wouldn't construct $leaked
264 268 // struct by mistake. Its drop() is unsafe.
265 269 unsafe fn new(py: Python, inner: &$name) -> Self {
266 270 Self {
267 271 inner: inner.clone_ref(py),
268 272 }
269 273 }
270 274 }
271 275
272 276 impl Drop for $leaked {
273 277 fn drop(&mut self) {
274 278 let gil = Python::acquire_gil();
275 279 let py = gil.python();
276 280 let state = self.inner.py_shared_state(py);
277 281 unsafe {
278 282 state.decrease_leak_count(py, false);
279 283 }
280 284 }
281 285 }
282 286 };
283 287 }
284 288
285 289 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
286 290 ///
287 291 /// TODO: this is a bit awkward to use, and a better (more complicated)
288 292 /// procedural macro would simplify the interface a lot.
289 293 ///
290 294 /// # Parameters
291 295 ///
292 296 /// * `$name` is the identifier to give to the resulting Rust struct.
293 297 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
294 298 /// * `$iterator_type` is the type of the Rust iterator.
295 299 /// * `$success_func` is a function for processing the Rust `(key, value)`
296 300 /// tuple on iteration success, turning it into something Python understands.
297 301 /// * `$success_func` is the return type of `$success_func`
298 302 ///
299 303 /// # Example
300 304 ///
301 305 /// ```
302 306 /// struct MyStruct {
303 307 /// inner: HashMap<Vec<u8>, Vec<u8>>;
304 308 /// }
305 309 ///
306 310 /// py_class!(pub class MyType |py| {
307 311 /// data inner: PySharedRefCell<MyStruct>;
308 312 /// data py_shared_state: PySharedState;
309 313 ///
310 314 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
311 315 /// let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
312 316 /// MyTypeItemsIterator::from_inner(
313 317 /// py,
314 318 /// leak_handle,
315 319 /// leaked_ref.iter(),
316 320 /// )
317 321 /// }
318 322 /// });
319 323 ///
320 324 /// impl MyType {
321 325 /// fn translate_key_value(
322 326 /// py: Python,
323 327 /// res: (&Vec<u8>, &Vec<u8>),
324 328 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
325 329 /// let (f, entry) = res;
326 330 /// Ok(Some((
327 331 /// PyBytes::new(py, f),
328 332 /// PyBytes::new(py, entry),
329 333 /// )))
330 334 /// }
331 335 /// }
332 336 ///
333 337 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
334 338 ///
335 339 /// py_shared_iterator!(
336 340 /// MyTypeItemsIterator,
337 341 /// MyTypeLeakedRef,
338 342 /// HashMap<'static, Vec<u8>, Vec<u8>>,
339 343 /// MyType::translate_key_value,
340 344 /// Option<(PyBytes, PyBytes)>
341 345 /// );
342 346 /// ```
343 347 macro_rules! py_shared_iterator {
344 348 (
345 349 $name: ident,
346 350 $leaked: ident,
347 351 $iterator_type: ty,
348 352 $success_func: expr,
349 353 $success_type: ty
350 354 ) => {
351 355 py_class!(pub class $name |py| {
352 356 data inner: RefCell<Option<$leaked>>;
353 357 data it: RefCell<$iterator_type>;
354 358
355 359 def __next__(&self) -> PyResult<$success_type> {
356 360 let mut inner_opt = self.inner(py).borrow_mut();
357 361 if inner_opt.is_some() {
358 362 match self.it(py).borrow_mut().next() {
359 363 None => {
360 364 // replace Some(inner) by None, drop $leaked
361 365 inner_opt.take();
362 366 Ok(None)
363 367 }
364 368 Some(res) => {
365 369 $success_func(py, res)
366 370 }
367 371 }
368 372 } else {
369 373 Ok(None)
370 374 }
371 375 }
372 376
373 377 def __iter__(&self) -> PyResult<Self> {
374 378 Ok(self.clone_ref(py))
375 379 }
376 380 });
377 381
378 382 impl $name {
379 383 pub fn from_inner(
380 384 py: Python,
381 385 leaked: $leaked,
382 386 it: $iterator_type
383 387 ) -> PyResult<Self> {
384 388 Self::create_instance(
385 389 py,
386 390 RefCell::new(Some(leaked)),
387 391 RefCell::new(it)
388 392 )
389 393 }
390 394 }
391 395 };
392 396 }
General Comments 0
You need to be logged in to leave comments. Login now