Search code examples
c++visual-studio-2015staticthread-safetythread-local-storage

Function local statics generate faulty code for Windows XP


I originally posted this on the ReverseEngineering StackExchange not knowing exactly where this belongs. I decided to post it here anyway.

Recently the Microsoft Visual Studio 2015 compiler finally complied with the C++ standards mandate to generate thread-safe code for function local statics. For the most part this works just fine but I ran into a situation on Windows XP where the following 3 instructions led to a blow up:

mov     eax,dword ptr fs:[0000002Ch]
mov     ecx,dword ptr [MyModule!_tls_index (102eea44)]
mov     ecx,dword ptr [eax+ecx*4]

Obviously the compiler seems to implement thread-safety by first poking into the TLS slot of the current thread. fs:2Ch is supposed to lead to the TLS array per documentation. However on Windows XP, fs:2Ch doesn't seem to be set. This returned 0 for me and so did the next instruction (_tls_index was also 0.) That led to the 3rd instruction blowing up as it was accessing invalid memory.

Does anybody know why fs:2Ch might not be set on Windows XP? Function local statics are used all over our code and I can't imagine no one else running into this.

UPDATE

I have carefully considered every tag I have applied to this question. Please DO NOT add or remove anything.


Solution

  • This question was ably answered by Peter Ferrie over at the Reverse Engineering SE.

    https://reverseengineering.stackexchange.com/a/14186/15780