Skip to content

[C++/CLI] Direct access of unmanaged thread_local variable from managed code causes unexpected NullReferenceException #42187

Description

@LEI-Hongfaan

Description

Consider the following code

// Compile with /clr

#pragma managed(push, off)

thread_local int thread_local_value;

int get_thread_local_value() {
    return thread_local_value;
}

void set_thread_local_value(int value) {
    thread_local_value = value;
}
#pragma managed(pop)

public ref class Test abstract sealed {

public:
    static int ManipulateThreadLocalValue(int value) {
        thread_local_value = value; // Throws a NullReferenceException at runtime
        return thread_local_value;
/* Jitted code
00007FFCF0FCFE70  push        rbp  
00007FFCF0FCFE71  sub         rsp,20h  
00007FFCF0FCFE75  lea         rbp,[rsp+20h]  
00007FFCF0FCFE7A  mov         dword ptr [rbp+10h],ecx  
00007FFCF0FCFE7D  mov         rcx,7FFCF1090020h  
00007FFCF0FCFE87  call        qword ptr [0]  ; <-- ???
00007FFCF0FCFE8E  mov         edx,dword ptr [rbp+10h]  
00007FFCF0FCFE91  mov         dword ptr [rax],edx  
00007FFCF0FCFE93  mov         eax,dword ptr [rbp+10h]  
00007FFCF0FCFE96  lea         rsp,[rbp]  
00007FFCF0FCFE9A  pop         rbp  
00007FFCF0FCFE9B  ret  
*/
    }

    static int ManipulateThreadLocalValue_Workaround(int value) {
        set_thread_local_value(value); // Ok
        return get_thread_local_value();
    }
};

Expected behavior

  1. VC++ Compiler should warn about it if not supported. - Or -
  2. VC++ Compiler should emit suitable metadata to identify thread_local fields and let the .NET runtime to deal with them. - Or -
  3. VC++ Compiler should generate unmanaged stubs to manipulate thread_local fields for the managed code. - Or -
  4. .NET jitter should correctly handle unmanaged thread_local field access.

I'm not very sure it's the right place to report the bug. It's more likely a problem of VC++ Compiler.

category:correctness
theme:managed-c++
skill-level:beginner
cost:medium
impact:small

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions