Skip to content

Use-after-free when using a ThreadRng from a std::thread_local destructor #968

@nathdobson

Description

@nathdobson

A ThreadRng is just a raw pointer to the std::thread_local variable THREAD_RNG_KEY. If a client reuses a ThreadRng after the THREAD_RNG_KEY is dropped (e.g. inside another std::thread_local destructor), this is undefined behavior.

On targets with thread local support in the linker, the memory is typically freed after all destructors are run, so the use-after-destroy is hard to detect. However, other targets destroy and free at the same time, causing a use-after-free. This test can reproduce the use-after-free on OSX.

On targets that support it, THREAD_RNG_KEY could use the unstable #[thread_local] instead of std::thread_local. Other targets would probably have to use an Rc.

I'm happy to write a PR once we confirm the intended direction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions