Handmade Hero » Forums » Code » CRT replecement fixes for allow static variables to work
albus95
Alberto Vaudagna
9 posts
#16262 CRT replecement fixes for allow static variables to work
3 months, 1 week ago Edited by Alberto Vaudagna on Sept. 9, 2018, 4:18 p.m.

When we remove the CRT we broke the static initializer in the code.
Now the static variables are not initialized anymore.
Also setting the _tls_index to 0 is wrong and will result in static variables inside function to not be initialized.
When there is a static variable inside a function the _tls_index get look to see if that variable is initialized or not.
Indeed _tls_index work with _Init_thread_header to ensure that the given static var would be initialized one.
I figured out this because in my code base I have the fix for the static variable initialization (using __xc_a and initerm) but when I was implementing the debug system, the first approach was to use static variables and the DEBUGInitializeValue function was never called.
Upon inspecting the CRT source code I'm now able to make that statics works as well.
Here are the gist of my msvc CRT replacament if any one is interested.

https://gist.github.com/vaualbus/622099d88334fbba1d4ae703642c2956

PS: This code work only on 64bit builds
PS2: new link now it is fixed there was a stupid error in the _Init_thread_footer func.

Best regards, Alberto.
mmozeiko
Mārtiņš Možeiko
1833 posts / 1 project
#16266 CRT replecement fixes for allow static variables to work
3 months, 1 week ago Edited by Mārtiņš Možeiko on Sept. 9, 2018, 1:52 p.m.

If all you want is to avoid thread-safe static initializations (which were introduced in VS2015), you can simply use /Zc:threadSafeInit- compiler argument. This will give you pre-C++11 static initialization behaviour - without dependency on C++ runtime.

But at this point I feel like it would be easier just to avoid C++ static variables than to do this kind of stuff. Which can change from one VS version to another. Not even talking about different platform or different compilers.

Similarly - that's why you also avoid __declspec(thread) for TLS and just directly call TlsGetValue/TlsSetValue when needed.
albus95
Alberto Vaudagna
9 posts
#16267 CRT replecement fixes for allow static variables to work
3 months, 1 week ago Edited by Alberto Vaudagna on Sept. 9, 2018, 3:24 p.m.

Well If I knew it I wouldn't spend all last night try to figured out what was happening ahahah
Any way thnaks. Also seem that my code is not working any way so hey better use old C++ initializer