rust-lang / unsafe-code-guidelines

Forum for discussion about what unsafe code can and can't do
https://rust-lang.github.io/unsafe-code-guidelines
Apache License 2.0
667 stars 58 forks source link

Are long-lived references to thread_local variables allowed? #541

Open theemathas opened 2 weeks ago

theemathas commented 2 weeks ago

Is the following code sound?

thread_local! {
    static X: String = String::from("abc");
}

/// SAFETY: If this function is called in a certain thread,
/// then the returned reference must not be used after
/// the "top-level function" of that thread finishes.
unsafe fn smuggle() -> &'static String {
    &*X.with(|a| a as *const String)
}

In other words, is it guaranteed that:

RalfJung commented 2 weeks ago

There is no way to get a &mut to thread-locals in safe code. And the address is indeed stable.

However once the destructor of the thread-local gets run, the reference gets invalidated, so the 'static lifetime is a lie. You seem to be aware of that.

The notion of "soundness" of an unsafe function is non-trivial to define so it's not entirely clear what you are asking about.

theemathas commented 2 weeks ago

And the address is indeed stable.

Is this documented anywhere?

RalfJung commented 2 weeks ago

Not that I am aware of.

thread-locals are a library feature, so this would be a t-libs-api issue to be raised in https://github.com/rust-lang/rust/issues/