Log in

View Full Version : TLS callbacks


omega_red
February 16th, 2006, 08:19
Do I have to link with user32.dll to use them? As I discovered during playing with my code, if I remove user32 imports, the callback is not invoked. Is that true or I am missing something? It's damn hard to find any comprehensive reference on this subject...

Kayaker
February 16th, 2006, 13:49
Hi omega_red,

I don't know why you'd specifically have to include user32.dll. Any TLS callbacks are called through ntdll!LdrpRunInitializeRoutines during normal process initialization. There shouldn't be any dependancy on user32.dll any more than at any other time. Maybe PIMAGE_TLS_DIRECTORY32 is being affected in some other way by any modifications you're making?


EDIT:
Checking my references I noticed this, maybe there truly is a bug...

http://blogs.msdn.com/mgrier/archive/2005/06/24/432455.aspx

I know what's written in books (TLS works for statically modules only). Therefore I wrote what new I found. I wrote nothing about (dynamic) loading. Just create simple .exe (it means static module) with TLS callbacks that imports from kernel32.dll only, run it on XP+ (kernel32.dll is preloaded and inited) and you will see that the callbacks are not called (because all modules (kernel32.dll, resp. ntdll.dll) were already inited. There's a logical bug in LdrpRunInitializeRoutines.


Comment: Refer to Matt Pietrek pseudocode. TLS callbacks are executed when implicitly loaded DLLs are initialized. In theory kernel32.dll should be sufficient, the usual InLoadOrderModuleList after ntdll.dll goes kernel32.dll, user32.dll, etc.

Kayaker

Kayaker
March 2nd, 2006, 17:57
Actually I don't find there's any bug with not having User32.dll declared or used, when compiling a skeleton TLS callback in either MASM or MSVC++. A simple breakpoint will prove the callback is working. There *is* a bug with MSVC++6 in that it compiles the TLS directory with a wrong pointer, but that is easily fixed.

For what it's worth here's a small TLS callback .exe example in MASM with a few references on the subject.

Kayaker

evaluator
January 10th, 2009, 03:20
(drop from blog)
i found code in NTDLL, where flags tested in module-list
Code:

cmp edx,ecx
je . --1
and b,[edx+025],0EF
test b,[edx+025],040 << this test flag is present for NTDLL & KERNEL32
je . --2
mov edx,[edx]
jmps . --3




@2:
and then IF this DLL has EntryPoint, counter increases!
BTW! USER32 has not EP.. but others loaded with USER32 have..

so if this counter reterns NULL, then TLS-callback will NOT called

RESUME:
TLS-callback will called if there will any DLL (except NTDLL & KERNEL32) wilth EntryPoint

APPENDIX:
but also TLS-callback will be called on ExitProcess, if at runtime will be loaded & present
such like DLL;