# Windows PE TLS callbacks in DLLs

This topic is 2009 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm attempting to use the TLS callback mechanism baked in to the PE format and Windows loader to provide proper cleanup in the Windows implementation my thread-local storage system.

(For those unfamiliar with this mechanism, the 'background' section of this codeproject article provides a quick summary).

When I link my threads library (static library) to an executable, my TLS callback is called as expected. However if I link the threads library in to a DLL (by which I mean, create a DLL which is linked against my static library), the callbacks aren't called.

Furthermore if I go poking around in my MSVC build of the dll (with this, for example) the AddressOfCallBacks field (0x1010DD88) in the PE TLS directory points in to the string table once I've subtracted the preferred image load address (0x10000000). Without the subtraction the address is beyond the end of the image, so it appears to be bogus either way, though realignment at load time might end up shuffling things about suitably(?).

Does anybody know if the PE TLS callback mechanism is supposed to work for DLLs in this manner?

I couldn't find anything on the web that indicated it shouldn't work, but on the other hand all the examples I found were creating executables.

I'm targeting recent versions of MS Visual C++ and MinGW GCC. Here's the code snippet compiled in to my static library that places a pointer to the callback in the appropriate PE section.

 extern "C" { #if defined(_MSC_VER) # if defined (_M_IX86) # pragma comment(linker, "/INCLUDE:__tls_used") # else # pragma comment(linker, "/INCLUDE:_tls_used") # endif # pragma data_seg(".CRT$XLB") PIMAGE_TLS_CALLBACK mtl_tls_callback_ = mtl::tls_callback; # pragma data_seg() #elif defined(__GNUC__) PIMAGE_TLS_CALLBACK mtl_tls_callback_ __attribute__ ((section(".CRT$XLB"))) = mtl::tls_callback; #else # error "Toolchain not supported " #endif } // extern "C" 

The workaround is to provide an auxhiliary DLL and have its DllMain do the cleanup, but I'd like to know if I can avoid having to do that.

##### Share on other sites
DLLs have different lifetime semantics than EXEs. It wouldn't surprise me if that means that TLS behaves very differently between the two. Also, note that doing nontrivial things in DllMain is generally a recipe for nasty races and deadlocks, and may result in Windows just nuking your process if you misbehave on accident.

##### Share on other sites
To follow-up, I've found that the TLS mechanism does work in DLLs, but not if they're loaded explicitly (with LoadLibrary(), etc), which is what my tests happened to be doing. This page gave me the answer, which appears to have loads of other really handy tidbits for those poking about in PE images.