Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix double drop in StreamExt::cycle #903

Merged
merged 1 commit into from
Nov 5, 2020

Conversation

taiki-e
Copy link
Contributor

@taiki-e taiki-e commented Nov 1, 2020

StreamExt::cycle drop source field without updating field if source field's destructor panicked.

ManuallyDrop::drop(&mut this.source);
this.source = ManuallyDrop::new(this.orig.clone());

This is unsound because it causes double drop if the user catches panic in the scope where the Cycle is alive.

Repro:

#[test]
#[should_panic(expected = "second")]
fn test() {
    use async_std::stream::*;
    use futures::task::{noop_waker, Context, Poll};
    use std::{panic, pin::Pin, thread};

    #[derive(Clone, Default)]
    struct S {
        dropped: bool,
    }

    impl Stream for S {
        type Item = ();

        fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Ready(None)
        }
    }

    impl Drop for S {
        fn drop(&mut self) {
            if !thread::panicking() {
                if std::mem::replace(&mut self.dropped, true) {
                    panic!("second")
                } else {
                    panic!("first")
                }
            }
        }
    }

    let mut s = Box::pin(S::default().cycle());
    let w = noop_waker();
    let cx = &mut Context::from_waker(&w);
    let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let _ = s.as_mut().poll_next(cx); // <-- dropped the first clone of `s`
    }));
    // <-- dropped the first clone of`s` again since `source` field wasn't updated
}

Copy link
Contributor

@yoshuawuyts yoshuawuyts left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, thanks for catching this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants