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

scoped threads: pass closure through MaybeUninit to avoid invalid dangling references #102589

Merged
merged 1 commit into from
Oct 11, 2022

Conversation

RalfJung
Copy link
Member

@RalfJung RalfJung commented Oct 2, 2022

The main function defined here looks roughly like this, if it were written as a more explicit stand-alone function:

// Not showing all the `'lifetime` tracking, the point is that
// this closure might live shorter than `thread`.
fn thread(control: ..., closure: impl FnOnce() + 'lifetime) {
    closure();
    control.signal_done();
    // A lot of time can pass here.
}

Note that thread continues to run even after signal_done! Now consider what happens if the closure captures a reference of lifetime 'lifetime:

  • The type of closure is a struct (the implicit unnameable closure type) with a &'lifetime mut T field. References passed to a function are marked with dereferenceable, which is LLVM speak for this reference will remain live for the entire duration of this function.
  • The closure runs, signal_done runs. Then -- potentially -- this thread gets scheduled away and the main thread runs, seeing the signal and returning to the user. Now 'lifetime ends and the memory the reference points to might be deallocated.
  • Now we have UB! The reference that as passed to thread with the promise of remaining live for the entire duration of the function, actually got deallocated while the function still runs. Oops.

Long-term I think we should be able to use ManuallyDrop to fix this without unsafe, or maybe a new MaybeDangling type. I am working on an RFC for that. But in the mean time it'd be nice to fix this so that Miri with -Zmiri-retag-fields (which is needed for "full enforcement" of all the LLVM flags we generate) stops erroring on scoped threads.

Fixes #101983
r? @m-ou-se

@rustbot rustbot added the T-libs Relevant to the library team, which will review and decide on the PR/issue. label Oct 2, 2022
@rustbot
Copy link
Collaborator

rustbot commented Oct 2, 2022

Hey! It looks like you've submitted a new PR for the library teams!

If this PR contains changes to any rust-lang/rust public library APIs then please comment with @rustbot label +T-libs-api -T-libs to tag it appropriately. If this PR contains changes to any unstable APIs please edit the PR description to add a link to the relevant API Change Proposal or create one if you haven't already. If you're unsure where your change falls no worries, just leave it as is and the reviewer will take a look and make a decision to forward on if necessary.

Examples of T-libs-api changes:

  • Stabilizing library features
  • Introducing insta-stable changes such as new implementations of existing stable traits on existing stable types
  • Introducing new or changing existing unstable library APIs (excluding permanently unstable features / features without a tracking issue)
  • Changing public documentation in ways that create new stability guarantees
  • Changing observable runtime behavior of library APIs

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 2, 2022
@@ -499,13 +499,18 @@ impl Builder {
let output_capture = crate::io::set_output_capture(None);
crate::io::set_output_capture(output_capture.clone());

// Pass `f` in `MaybeUninit` because actually that closure might *run longer than the lifetime of `F`*.
// See <https://github.com/rust-lang/rust/issues/101983> for more details.
let f = mem::MaybeUninit::new(f);
Copy link
Member Author

@RalfJung RalfJung Oct 3, 2022

Choose a reason for hiding this comment

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

Hm, this has the side effect that if the closure is dropped before being run, we leak f. That is probably not what we want... bit right now that is hard to avoid. We'd need a small wrapper type around MaybeUninit that drops its contents.

Copy link
Contributor

Choose a reason for hiding this comment

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

Does the stdlib use scopeguard? Writing such ad-hoc drop glues becomes the breeze it should have always been:

let mb_dangling_f = ::scopeguard::guard(MaybeUninit::new(f), /* drop: */ |f| unsafe {
    drop(MaybeUninit::assume_init(f));
});
let closure = move/*(mb_dangling_f, ..)*/ |…| {
    let f = ScopeGuard::into_inner(mb_dangling_f);
    let f = unsafe {
        MaybeUninit::assume_init(f)
    };

Copy link
Member Author

Choose a reason for hiding this comment

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

No I don't think it does.

@m-ou-se
Copy link
Member

m-ou-se commented Oct 11, 2022

@bors r+

@bors
Copy link
Contributor

bors commented Oct 11, 2022

📌 Commit 78b577c has been approved by m-ou-se

It is now in the queue for this repository.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Oct 11, 2022
bors added a commit to rust-lang-ci/rust that referenced this pull request Oct 11, 2022
Rollup of 7 pull requests

Successful merges:

 - rust-lang#102258 (Remove unused variable in float formatting.)
 - rust-lang#102277 (Consistently write `RwLock`)
 - rust-lang#102412 (Never panic in `thread::park` and `thread::park_timeout`)
 - rust-lang#102589 (scoped threads: pass closure through MaybeUninit to avoid invalid dangling references)
 - rust-lang#102625 (fix backtrace small typo)
 - rust-lang#102859 (Move lifetime resolution module to rustc_hir_analysis.)
 - rust-lang#102898 (rustdoc: remove unneeded `<div>` wrapper from sidebar DOM)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 919d6bf into rust-lang:master Oct 11, 2022
@rustbot rustbot added this to the 1.66.0 milestone Oct 11, 2022
@RalfJung RalfJung deleted the scoped-threads-dangling branch October 11, 2022 20:46
@coolreader18
Copy link
Contributor

Just looking at this cause it was in twir and I'm confused - doesn't closure.call_once() take ownership of the closure type and drop it? How would closure still be alive/dereferenceable if it was consumed by the call operator?

@RalfJung
Copy link
Member Author

The bug is described in a bit more detail at #101983, does that help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Scoped threads violate 'dereferenceable for function call' requirement of references
7 participants