Windows API: Strange behaviour after calling GetModuleFileNameExA
Regan Heath
regan at netmail.co.nz
Tue Nov 27 04:31:52 PST 2007
This is totally whacky... using the code posted below I get the
following output:
a 4
b 2000
c
d
e 883C00 300
f 883C00 300
g 883C00 300
h 884FF0 4296896
The output for both g and h are written with:
writefln("h %p %d", processFileName.ptr, processFileName.length);
The line between the two which causes this behaviour is
processFileName = "Unknown".dup;
PID of 4 is of course "System".
Removing the call to GetModuleFileNameExA prevents the problem.
My guess is that GetModuleFileNameExA is corrupting the stack somehow,
perhaps the implib didn't correctly convert the dll to a lib. I used:
implib /noi /system psapi.lib C:\windows\system32\psapi.dll
The full code:
import std.stdio;
import std.c.windows.windows;
extern (Windows) HANDLE OpenProcess(uint dwDesiredAccess, BOOL
bInheritHandle, uint dwProcessId);
extern (C)
{
BOOL EnumProcesses(DWORD* pProcessIds, DWORD cb, DWORD* pBytesReturned);
DWORD GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule, char*
fileName, uint size);
}
void main(char[][] args)
{
char[] processFileName;
uint[] processIds;
uint[] processIds2;
uint byteCount;
processIds.length = 256;
int ret = EnumProcesses(processIds.ptr,
processIds.length*uint.sizeof, &byteCount);
if(ret!=0)
{
processIds.length = byteCount/uint.sizeof;
processIds2 = processIds.dup;
foreach(i, pid; processIds)
{
if(pid==0) continue;
writefln("a %d", pid);
HANDLE hProcess = OpenProcess(0x410 /* QueryInformation | VMRead
*/, false, pid);
writefln("b %d", cast(int)hProcess);
if(cast(int)hProcess>0)
{
writefln("c");
processFileName.length = 300;
writefln("d");
uint namelength = 0;
writefln("e %p %d", processFileName.ptr,
processFileName.length);
namelength = GetModuleFileNameExA(hProcess, cast(HMODULE)0,
processFileName.ptr, processFileName.length);
writefln("f %p %d", processFileName.ptr,
processFileName.length);
if (namelength == 0)
{
writefln("g %p %d", processFileName.ptr, processFileName.length);
processFileName = "Unknown".dup;
writefln("h %p %d", processFileName.ptr, processFileName.length);
}
else
{
writefln("i");
processFileName.length = namelength;
writefln("j");
}
break;
writefln("%d. (%d) => %s", i, pid, processFileName);
CloseHandle(hProcess);
}
}
}
}
More information about the Digitalmars-d
mailing list