Skip to content

Inner statics in generic fns aren't handled correctly. #9186

Closed

Description

@alexcrichton

It turns out that an inner static is only generated once. Hence if you have a generic function and the static somehow takes the generic type into account, the static will have the same address for all instantiations. Turns out this is a soundness problem with TLS:

use std::local_data;

fn foo<T>() -> local_data::Key<T> {
    local_data_key!(foo: T);
    return foo;
}

fn main() {
    let k1 = foo::<int>();
    let k2 = foo::<float>();

    local_data::set(k1, 1);
    local_data::set(k2, 1f);

    println!("{:#x}", local_data::get(k1, |x| *x.unwrap()));
    println!("{}", local_data::get(k2, |x| *x.unwrap()));
}
$ rust run foo.rs
warning: no debug symbols in executable (-arch x86_64)
0x3ff0000000000000
1

Notably, the inner static foo has the same address each time the function foo is instantiated, hence k1 and k2 are the same value, so the first local_data::get is actually printing the hex representation of 1f.

Naturally this allows arbitrary coercion of types via TLS in safe code, this is a definite soundness issue.

You can't declare inner functions with the type parameters declared in outer functions, so perhaps the same rule should apply to statics as well? If not, then this is a codegen problem.

Activity

  1. alexcrichton commented on Sep 16, 2013

    @alexcrichton
    MemberAuthor

    Nominating for the well-defined milestone (whether type parameters can appear in statics).

  2. catamorphism commented on Sep 19, 2013

    @catamorphism
    Contributor

    accepted backwards-compatible

  3. nikomatsakis commented on Oct 10, 2013

    @nikomatsakis
    Contributor

    I think that the generic types etc should not be in scope for the static -- that is, trans et al are doing the right thing, just not resolve

  4. added a commit that references this issue on Oct 31, 2013
    0db5005
  5. added a commit that references this issue on Oct 31, 2013
    c7d5a52
  6. added a commit that references this issue on Aug 29, 2022
    679fa9f
  7. added a commit that references this issue on Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generation

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions