Win32 Programming Lesson 21: DLL Magic
Where are we? We’ve looked at DLLs from a build/link/execute perspective, as well as some more advanced techniques Today, start looking at Thread Local Storage and DLL interception >:)
Thread Local Storage (TLS) What does the strtok function do? How does it work? What happens in a multithreaded environment?
TLS Provides simple method for storing variables on a per-thread basis Two types: dynamic and static; we’ll be looking at both.
Supporting Structures
So… We call: DWORD TlsAlloc(); Returns TLS_OUT_OF_INDEXES if no storage is available Else, returns an index number which can be used to store a DWORD BOOL TlsSetValue( DWORD dwTlsIndex, PVOID pvTlsValue );
Cleaning Up It’s C++, so there’s not a lot of cleaning up done for us… PVOID TlsGetValue(DWORD dwTlsIndex); BOOL TlsFree(DWORD dwTlsIndex);
Using Static TLS Can also do this: __declspec(thread) DWORD gt_dwStartTime = 0; Creates a.tls section Allocates the necessary storage automatically
DLL Injection So, life can be interesting Windows provides limited process isolation But sometimes we want to “hook” into another process One way to do this is by leveraging DLLs
Danger, Will Robinson Some of these techniques will make global changes to how your computer functions. You need to carefully decide whether to do this on your main machine, or if a VM is a better option. You have been warned! (That said, I do this all on my own laptop…)
The Trick What are we actually trying to do?
Registry HKEY_LOCAL_MACHINE\Software\Micro soft \Windows NT\CurrentVersion\Window s\AppInit_DLLs Hmmm. Advantages? Drawbacks?
Drawbacks… You must restart your computer Only mapped into processes which use User32.dll You’re in *every* GUI app… … for it’s entire lifetime
Better… SetWindowsHookEx SetWindowsHookEx E.g: HHOOK hHook = SetWindowsHookEx( WH_GETMESSAGE, GetMsgProc, hinstDll, 0 ); Why hinstDll?
Walkthrough DIPS