tu nguyen
tu nguyen

Reputation: 13

TLS callbacks implement not functioning

I am trying to implement the TLS callback on window 10. This is my code and I build it on visual studio 2022:

#include <Windows.h>
#include <cstdio>
__declspec(thread) int a;
__declspec(thread) int b;
void NTAPI on_tls_callback(void* dll, DWORD reason, void* reserved)
{
    a = 543; // 0x21F
    //MessageBox(nullptr, L"In TLS", L"In TLS", MB_OK);
    printf("a in on_tls_callback function: %d\n", a);
}
void NTAPI on_tls_callback_test(void* dll, DWORD reason, void* reserved)
{
    b = 10; // 0xA
    //MessageBox(nullptr, L"Another In TLS", L"Another In TLS", MB_OK);
    printf("b in on_tls_callback_test function: %d\n", b);
}

#pragma comment (linker, "/INCLUDE:__tls_used")


//test
#pragma data_seg(".CRT$XLA")
#pragma comment (linker, "/INCLUDE:__xl_a")
EXTERN_C __declspec(allocate(".CRT$XLA"))
PIMAGE_TLS_CALLBACK _xl_a = (PIMAGE_TLS_CALLBACK)on_tls_callback_test;
#pragma data_seg()

#pragma data_seg(".CRT$XLX")
#pragma comment (linker, "/INCLUDE:__xl_x")
EXTERN_C __declspec(allocate(".CRT$XLX"))
PIMAGE_TLS_CALLBACK _xl_x = (PIMAGE_TLS_CALLBACK)on_tls_callback;
#pragma data_seg()



__declspec(thread) int c = 9;

int main()
{
    printf("a in main: %d\n", a);
    printf("b in main: %d\n", b);
    c = 15;
    printf("c in main: %d\n", c);
    //MessageBox(nullptr, L"In Main", L"In Main", MB_OK);
    printf("end main !!!\n");
    getchar();
    return 0;
}

And the program output:

a in on_tls_callback function: 543
a in main: 543
b in main: 0
c in main: 15
end main !!!

I expect that above code will execute both on_tls_callback_test() and on_tls_callback() functions, but it only run on_tls_callback. And on main, b is 0 !

How can I make both on_tls_callback_test() and on_tls_callback() TLS callback run before main? And Why is b equal 0 ? Thank you for your time

Upvotes: 0

Views: 227

Answers (0)

Related Questions