Windows API: Strange behaviour after calling GetModuleFileNameExA

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


Could be an implib problem - I ported the code to C and compiled with DMC, the same thing.

Used C-Code:

#include <stdio.h>
#include <windows.h>

HANDLE OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);    
CloseHandle(HANDLE hHandle);
BOOL EnumProcesses(DWORD* pProcessIds, DWORD cb, DWORD* pBytesReturned);
DWORD GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule, char* fileName, DWORD size);  


void main()
{
  unsigned long processIds[256];
  unsigned long byteCount;
  char processFileName[300];
  int ret = EnumProcesses(&processIds[0], 256*sizeof(unsigned long), &byteCount);
  
  if(ret!=0)
  {
    for(DWORD i=0; i<256 && i<byteCount/sizeof(unsigned long); i++)
    {
      if(processIds[i]==0)
        continue;
      unsigned int pid =  processIds[i];   
      printf("Process #%d - PID: %d\r\n", i, pid);   
      
      HANDLE hProcess = OpenProcess(0x410, FALSE, pid);
      if((int)hProcess>0)
      {
        unsigned int namelength = GetModuleFileNameExA(hProcess, NULL, &processFileName[0], 300);
        printf("=> %s\r\n", processFileName); 
        CloseHandle(hProcess);
      }
    }
  }
}

Compiled with:

dmc -L/+psapi/noi ProcessFinderTest.c

Uncomment the GetModuleFileNameExA-Call and all works fine - otherthise the array will be corrupted.

Regan Heath Wrote:

> 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



More information about the Digitalmars-d mailing list