Compiler magic for THREADVARs causes AV on manual module relocation
Original Reporter info from Mantis: Barvinok
-
Reporter name: Gennadiy
Original Reporter info from Mantis: Barvinok
- Reporter name: Gennadiy
Description:
=Preamble=
The task I'm working on is somewhat unorthodox and I'm not quite sure this qualifies as a true bug, but I'd like to get some comments anyway.
I'm writing "stealth" DLL that is one loaded by process while not residing on disk as a file. This is done by the following method:
- Call LoadLibrary on an existing DLL file
- Take memory snapshot of the loaded DLL
- Call FreeLibrary on it and delete DLL file.
- Create KnownDlls kernel section object, obtain its new base address.
- Process relocations and imagebase fixups, write patched image to kernel section.
Now whenever a process tries to load DLL by magic name, it is loaded from this kernel section, not from file.
=Problem=
To test the viability of the concept, I wrote a simple demo DLL:
---
library demo;
uses Windows;
begin
MessageBoxW(GetDesktopWindow,'Demo window','Demo',MB_OK or MB_ICONINFORMATION);
end.
---
Unlike even simplier DLLs written in assembler, which were working fine, this one failed by causing AV upon loading from kernel section.
I traced the problem to the system.pp file. Apparently this code:
\---<br/>
{ pass dummy value }
StackLength := CheckInitialStkLen($1000000);
StackBottom := StackTop - StackLength;
---
in the initialization section at the end causes the call of SysAllocateThreadVars() and suchlike since these are THREADVARs encountered first. Now the problem is that the module somehow managed to remember the absolute address to SysAllocateThreadVars() back when it was loaded normally by LoadLibrary() using its prescribed imagebase.
I tend to consider this a bug since module re-initialization (i.e. calling DLL entry point anew) must, I presume, re-initialize all RTL and compiler magic internals, no matter what is already remembered as offsets.
I'd like to know what others think and/or how to circumvent the issue.
Mantis conversion info:
- Mantis ID: 21031
- OS: any win32
- Build: svn r19692
- Platform: win32
- Version: 2.7.1