]> git.lizzy.rs Git - rust.git/blob - src/test/ui/drop/dynamic-drop-async.rs
b027faa9d7c3a2ba3f8f684252af589f9cd6bcb3
[rust.git] / src / test / ui / drop / dynamic-drop-async.rs
1 // Test that values are not leaked in async functions, even in the cases where:
2 // * Dropping one of the values panics while running the future.
3 // * The future is dropped at one of its suspend points.
4 // * Dropping one of the values panics while dropping the future.
5
6 // run-pass
7 // edition:2018
8 // ignore-wasm32-bare compiled with panic=abort by default
9
10 #![allow(unused)]
11
12 use std::{
13     cell::{Cell, RefCell},
14     future::Future,
15     marker::Unpin,
16     panic,
17     pin::Pin,
18     ptr,
19     rc::Rc,
20     task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
21     usize,
22 };
23
24 struct InjectedFailure;
25
26 struct Defer<T> {
27     ready: bool,
28     value: Option<T>,
29 }
30
31 impl<T: Unpin> Future for Defer<T> {
32     type Output = T;
33     fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
34         if self.ready {
35             Poll::Ready(self.value.take().unwrap())
36         } else {
37             self.ready = true;
38             Poll::Pending
39         }
40     }
41 }
42
43 /// Allocator tracks the creation and destruction of `Ptr`s.
44 /// The `failing_op`-th operation will panic.
45 struct Allocator {
46     data: RefCell<Vec<bool>>,
47     failing_op: usize,
48     cur_ops: Cell<usize>,
49 }
50
51 impl panic::UnwindSafe for Allocator {}
52 impl panic::RefUnwindSafe for Allocator {}
53
54 impl Drop for Allocator {
55     fn drop(&mut self) {
56         let data = self.data.borrow();
57         if data.iter().any(|d| *d) {
58             panic!("missing free: {:?}", data);
59         }
60     }
61 }
62
63 impl Allocator {
64     fn new(failing_op: usize) -> Self {
65         Allocator { failing_op, cur_ops: Cell::new(0), data: RefCell::new(vec![]) }
66     }
67     fn alloc(&self) -> impl Future<Output = Ptr<'_>> + '_ {
68         self.fallible_operation();
69
70         let mut data = self.data.borrow_mut();
71
72         let addr = data.len();
73         data.push(true);
74         Defer { ready: false, value: Some(Ptr(addr, self)) }
75     }
76     fn fallible_operation(&self) {
77         self.cur_ops.set(self.cur_ops.get() + 1);
78
79         if self.cur_ops.get() == self.failing_op {
80             panic!(InjectedFailure);
81         }
82     }
83 }
84
85 // Type that tracks whether it was dropped and can panic when it's created or
86 // destroyed.
87 struct Ptr<'a>(usize, &'a Allocator);
88 impl<'a> Drop for Ptr<'a> {
89     fn drop(&mut self) {
90         match self.1.data.borrow_mut()[self.0] {
91             false => panic!("double free at index {:?}", self.0),
92             ref mut d => *d = false,
93         }
94
95         self.1.fallible_operation();
96     }
97 }
98
99 async fn dynamic_init(a: Rc<Allocator>, c: bool) {
100     let _x;
101     if c {
102         _x = Some(a.alloc().await);
103     }
104 }
105
106 async fn dynamic_drop(a: Rc<Allocator>, c: bool) {
107     let x = a.alloc().await;
108     if c {
109         Some(x)
110     } else {
111         None
112     };
113 }
114
115 struct TwoPtrs<'a>(Ptr<'a>, Ptr<'a>);
116 async fn struct_dynamic_drop(a: Rc<Allocator>, c0: bool, c1: bool, c: bool) {
117     for i in 0..2 {
118         let x;
119         let y;
120         if (c0 && i == 0) || (c1 && i == 1) {
121             x = (a.alloc().await, a.alloc().await, a.alloc().await);
122             y = TwoPtrs(a.alloc().await, a.alloc().await);
123             if c {
124                 drop(x.1);
125                 a.alloc().await;
126                 drop(y.0);
127                 a.alloc().await;
128             }
129         }
130     }
131 }
132
133 async fn field_assignment(a: Rc<Allocator>, c0: bool) {
134     let mut x = (TwoPtrs(a.alloc().await, a.alloc().await), a.alloc().await);
135
136     x.1 = a.alloc().await;
137     x.1 = a.alloc().await;
138
139     let f = (x.0).0;
140     a.alloc().await;
141     if c0 {
142         (x.0).0 = f;
143     }
144     a.alloc().await;
145 }
146
147 async fn assignment(a: Rc<Allocator>, c0: bool, c1: bool) {
148     let mut _v = a.alloc().await;
149     let mut _w = a.alloc().await;
150     if c0 {
151         drop(_v);
152     }
153     _v = _w;
154     if c1 {
155         _w = a.alloc().await;
156     }
157 }
158
159 async fn array_simple(a: Rc<Allocator>) {
160     let _x = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
161 }
162
163 async fn vec_simple(a: Rc<Allocator>) {
164     let _x = vec![a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
165 }
166
167 async fn mixed_drop_and_nondrop(a: Rc<Allocator>) {
168     // check that destructor panics handle drop
169     // and non-drop blocks in the same scope correctly.
170     //
171     // Surprisingly enough, this used to not work.
172     let (x, y, z);
173     x = a.alloc().await;
174     y = 5;
175     z = a.alloc().await;
176 }
177
178 #[allow(unreachable_code)]
179 async fn vec_unreachable(a: Rc<Allocator>) {
180     let _x = vec![a.alloc().await, a.alloc().await, a.alloc().await, return];
181 }
182
183 async fn slice_pattern_one_of(a: Rc<Allocator>, i: usize) {
184     let array = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
185     let _x = match i {
186         0 => {
187             let [a, ..] = array;
188             a
189         }
190         1 => {
191             let [_, a, ..] = array;
192             a
193         }
194         2 => {
195             let [_, _, a, _] = array;
196             a
197         }
198         3 => {
199             let [_, _, _, a] = array;
200             a
201         }
202         _ => panic!("unmatched"),
203     };
204     a.alloc().await;
205 }
206
207 async fn subslice_pattern_from_end_with_drop(a: Rc<Allocator>, arg: bool, arg2: bool) {
208     let arr = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
209     if arg2 {
210         drop(arr);
211         return;
212     }
213
214     if arg {
215         let [.., _x, _] = arr;
216     } else {
217         let [_, _y @ ..] = arr;
218     }
219     a.alloc().await;
220 }
221
222 async fn subslice_pattern_reassign(a: Rc<Allocator>) {
223     let mut ar = [a.alloc().await, a.alloc().await, a.alloc().await];
224     let [_, _, _x] = ar;
225     ar = [a.alloc().await, a.alloc().await, a.alloc().await];
226     let [_, _y @ ..] = ar;
227     a.alloc().await;
228 }
229
230 async fn move_ref_pattern(a: Rc<Allocator>) {
231     let mut tup = (a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await);
232     let (ref _a, ref mut _b, _c, mut _d) = tup;
233     a.alloc().await;
234 }
235
236 fn run_test<F, G>(cx: &mut Context<'_>, ref f: F)
237 where
238     F: Fn(Rc<Allocator>) -> G,
239     G: Future<Output = ()>,
240 {
241     for polls in 0.. {
242         // Run without any panics to find which operations happen after the
243         // penultimate `poll`.
244         let first_alloc = Rc::new(Allocator::new(usize::MAX));
245         let mut fut = Box::pin(f(first_alloc.clone()));
246         let mut ops_before_last_poll = 0;
247         let mut completed = false;
248         for _ in 0..polls {
249             ops_before_last_poll = first_alloc.cur_ops.get();
250             if let Poll::Ready(()) = fut.as_mut().poll(cx) {
251                 completed = true;
252             }
253         }
254         drop(fut);
255
256         // Start at `ops_before_last_poll` so that we will always be able to
257         // `poll` the expected number of times.
258         for failing_op in ops_before_last_poll..first_alloc.cur_ops.get() {
259             let alloc = Rc::new(Allocator::new(failing_op + 1));
260             let f = &f;
261             let cx = &mut *cx;
262             let result = panic::catch_unwind(panic::AssertUnwindSafe(move || {
263                 let mut fut = Box::pin(f(alloc));
264                 for _ in 0..polls {
265                     let _ = fut.as_mut().poll(cx);
266                 }
267                 drop(fut);
268             }));
269             match result {
270                 Ok(..) => panic!("test executed more ops on first call"),
271                 Err(e) => {
272                     if e.downcast_ref::<InjectedFailure>().is_none() {
273                         panic::resume_unwind(e);
274                     }
275                 }
276             }
277         }
278
279         if completed {
280             break;
281         }
282     }
283 }
284
285 fn clone_waker(data: *const ()) -> RawWaker {
286     RawWaker::new(data, &RawWakerVTable::new(clone_waker, drop, drop, drop))
287 }
288
289 fn main() {
290     let waker = unsafe { Waker::from_raw(clone_waker(ptr::null())) };
291     let context = &mut Context::from_waker(&waker);
292
293     run_test(context, |a| dynamic_init(a, false));
294     run_test(context, |a| dynamic_init(a, true));
295     run_test(context, |a| dynamic_drop(a, false));
296     run_test(context, |a| dynamic_drop(a, true));
297
298     run_test(context, |a| assignment(a, false, false));
299     run_test(context, |a| assignment(a, false, true));
300     run_test(context, |a| assignment(a, true, false));
301     run_test(context, |a| assignment(a, true, true));
302
303     run_test(context, |a| array_simple(a));
304     run_test(context, |a| vec_simple(a));
305     run_test(context, |a| vec_unreachable(a));
306
307     run_test(context, |a| struct_dynamic_drop(a, false, false, false));
308     run_test(context, |a| struct_dynamic_drop(a, false, false, true));
309     run_test(context, |a| struct_dynamic_drop(a, false, true, false));
310     run_test(context, |a| struct_dynamic_drop(a, false, true, true));
311     run_test(context, |a| struct_dynamic_drop(a, true, false, false));
312     run_test(context, |a| struct_dynamic_drop(a, true, false, true));
313     run_test(context, |a| struct_dynamic_drop(a, true, true, false));
314     run_test(context, |a| struct_dynamic_drop(a, true, true, true));
315
316     run_test(context, |a| field_assignment(a, false));
317     run_test(context, |a| field_assignment(a, true));
318
319     run_test(context, |a| mixed_drop_and_nondrop(a));
320
321     run_test(context, |a| slice_pattern_one_of(a, 0));
322     run_test(context, |a| slice_pattern_one_of(a, 1));
323     run_test(context, |a| slice_pattern_one_of(a, 2));
324     run_test(context, |a| slice_pattern_one_of(a, 3));
325
326     run_test(context, |a| subslice_pattern_from_end_with_drop(a, true, true));
327     run_test(context, |a| subslice_pattern_from_end_with_drop(a, true, false));
328     run_test(context, |a| subslice_pattern_from_end_with_drop(a, false, true));
329     run_test(context, |a| subslice_pattern_from_end_with_drop(a, false, false));
330     run_test(context, |a| subslice_pattern_reassign(a));
331
332     run_test(context, |a| move_ref_pattern(a));
333 }