Spurious App Crash due to DLL injection because of Thread Local Storage?

311 views Asked by At

a while ago, we had a problem within a Citrix (probably XenApp) environment: Our (Win32) app simply wouldn't start and bailed out with an ACCESS_VIOLATION. When I finally got hold of some CoreDump / Minidump files (generation of those was somehow disabled), I noticed the following:

One of the injected DLLs from Citrix had created a thread that got started before the application itself had a chance to finish initializing its Runtime (CRT).

Now, both Windows and VC++ have mechanisms to initialize Thread Local Storage (TLS) data. Windows iteself calls a special entry point in the application every time a thread is started. This entry point is handled by the VS CRT which calls TLS initializers. These TLS initializerss may then call constructors of (global) variables that are declared thread local via __declspec(thread) in code, which is documented and seems perfectly reasonable.

However, since the thread (created by the injected DLL) was started before the app had a chance to complete its initialization, this TLS init mechanism called code that crashed with the ACCESS_VIOLATION since the CRT was not fully set up yet.

I tried very hard to write my own DLL that starts a thread, to simulate the behaviour. But I could not get the thread started (and therefore TLS init code called) before the apps CRT got initialized.

Of course I managed to implement some workaround, but I find it very disturbing that this is necessary at all. If the OS itself supports initializing TLS, how can it be that some code may create and start a thread, before the main apps CRT has been set up? Doesn't this destroy all the efforts in having a reasonable and documented TLS behaviour?

Can some please bring some light into this?

0

There are 0 answers