Skip to content

Thread locals do not guard against recursive initialization. #30228

Closed
@eddyb

Description

@eddyb
use std::cell::Cell;
struct Foo;
thread_local!(static INIT: Cell<bool> = Cell::new(false));
thread_local!(static FOO: Foo = Foo::init());
impl Foo {
    fn init() -> Foo {
        INIT.with(|i| {
            let init = i.get();
            i.set(true);
            if !init {
                // Trigger recursive initialization, just once.
                FOO.with(|_| {});
            }
        });
        Foo
    }
}
impl Drop for Foo {
    fn drop(&mut self) {
        FOO.with(|foo| alias_check(self, foo));
    }
}

fn alias_check<T>(m: &mut T, r: &T) {
    println!("alias_check({:p}, {:p})", m, r);
    if m as *mut _ as usize == r as *const _ as usize {
        panic!("aliasing detected!");
    }
}

fn main() {
    FOO.with(|_| {});
}

In current stable (1.4), beta, and nightly the above snippet produces aliased references instead of triggering library asserts.

Currently, libstd assumes there is no value already in the slot when assigning the one produced by the latest initializer call.

It should either drop one of the two values (perhaps after putting the TLS slot in "destructor being called" mode) or panic, if a multiple initialization condition is detected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions