rust icon indicating copy to clipboard operation
rust copied to clipboard

Simply enabling `feature(async_drop)` causes cancelled async blocks to not drop their contents

Open maxdexh opened this issue 1 month ago • 2 comments

I suspect this is the underlying cause for some other open drop-soundness issues with feature(async_drop), though I'm not sure which if any, as cancelled closures seem to behave unpredictably and depending on whether cancelled in an async or non-async context.

This code violates the drop guarantee:

#![feature(async_drop)] // comment out to make this behave properly
#![allow(incomplete_features, dead_code)]

use std::{
    pin::{Pin, pin},
    task::{Context, Waker},
};

fn main() {
    for _ in 0..2 {
        _ = pin!(async {
            // the payload is structurally pinned inside the future, so dropping the future
            // after it has been polled must drop the payload to uphold the drop guarantee
            let mut pinned = pin!(Payload([0x42; _], std::marker::PhantomPinned));
            pinned.as_mut().observe_pin();
            std::future::pending::<()>().await
        })
        .poll(&mut Context::from_waker(Waker::noop())); // future polled and then dropped
    }
}

struct Payload([u8; 1024], std::marker::PhantomPinned);
impl Drop for Payload {
    fn drop(&mut self) {
        println!("Dropping Payload at {self:p}");
    }
}
impl Payload {
    fn observe_pin(self: Pin<&mut Self>) {
        println!("Observed pin at: {self:p}..{:p}", &self.1);
    }
}

Output:

Observed pin at: 0x7ffdc74ee150..0x7ffdc74ee550
Observed pin at: 0x7ffdc74ee150..0x7ffdc74ee550

Output without feature(async_drop):

Observed pin at: 0x7fff0de123f0..0x7fff0de127f0
Dropping Payload at 0x7fff0de123f0
Observed pin at: 0x7fff0de123f0..0x7fff0de127f0
Dropping Payload at 0x7fff0de123f0

maxdexh avatar Oct 25 '26 10:10 maxdexh

@rustbot claim

Web4everyone32 avatar Oct 26 '26 07:10 Web4everyone32

The fix is getting reverted in https://github.com/rust-lang/rust/pull/165266

theemathas avatar Nov 01 '26 12:11 theemathas