Windows API: Strange behaviour after calling GetModuleFileNameExA

Tobias Wassermann mail at ingrid-wassermann.de
Tue Nov 27 03:10:35 PST 2007


Hi,

here is the 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)
{
  uint[256] processIds;
  uint byteCount;
  char[] processFileName;
  int ret = EnumProcesses(processIds.ptr, processIds.length*uint.sizeof, &byteCount);
  if(ret!=0)
  {
    for(uint i=0; i<processIds.length && i<byteCount/uint.sizeof; i++)
    {
      if(processIds[i]==0)
        continue;
      uint pid =  processIds[i];   
      writefln("Process #%d - PID: %d", i, pid);   
      
      HANDLE hProcess = OpenProcess(0x410 /* QueryInformation | VMRead */, false, pid);
      if(cast(int)hProcess>0)
      {
        processFileName.length = 300;
        uint namelength = 0;
        namelength = GetModuleFileNameExA(hProcess, cast(HMODULE)0, processFileName.ptr, processFileName.length);
        processFileName.length = namelength;
        writefln("=> %s", processFileName);        
        CloseHandle(hProcess);
      }
    }
  }
}

If you comment out the  namelength = GetModuleFileNameExA(hProcess, cast(HMODULE)0, processFileName.ptr, processFileName.length); line, all works fine.

I also tried a char* allocated memory block with malloc() instead of the processFileName.ptr - so I thought about a bug between the communication between D and the Windows API, but the result is the same: a corrupted uint[] process-id-array.

Bye

Tobias


Regan Heath Wrote:

> 
> The thought I had was that perhaps GetModuleFileNameExA was overwriting 
> the wrong memory and corrupting the process list.
> 
> Can you post a complete working piece of code which exhibits the bug, 
> I'd like to help by debugging it locally.
> 
> Regan




More information about the Digitalmars-d mailing list