WINAPI VirtualQueryEx - Invalid handle

I am trying to read some memory pages about a 32 bit process using VirtualQueryEx using Visual Studio 2012.

However, when I run the program, I get VirtualQueryEx Error 6: Invalid Handle. However, there is no [hProcess] error with the descriptor itself, and I pass the appropriate parameters. What could be?

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

//  Forward declarations:
BOOL GetProcessList( );
BOOL ListProcessModules( DWORD dwPID );
BOOL ListProcessThreads( DWORD dwOwnerPID );
void printError( TCHAR* msg );

int main( void )
{
  GetProcessList( );
   system("pause");

  return 0;
}

BOOL GetProcessList( )
{
  HANDLE hProcessSnap;
  HANDLE hProcess;
  PROCESSENTRY32 pe32;
  DWORD dwPriorityClass;

  // Take a snapshot of all processes in the system.
  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
  if( hProcessSnap == INVALID_HANDLE_VALUE )
  {
    printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
    return( FALSE );
  }

  // Set the size of the structure before using it.
  pe32.dwSize = sizeof( PROCESSENTRY32 );

  // Retrieve information about the first process,
  // and exit if unsuccessful
  if( !Process32First( hProcessSnap, &pe32 ) )
  {
    printError( TEXT("Process32First") ); // show cause of failure
    CloseHandle( hProcessSnap );          // clean the snapshot object
    return( FALSE );
  }

  // Now walk the snapshot of processes, and
  // display information about each process in turn
  do
  {
    //If the process name equals foo_process.exe
if (!_tcscmp(pe32.szExeFile, _T("foo_process.exe"))) 
{

    hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pe32.th32ProcessID );
    if( hProcess == NULL )
      printError( TEXT("OpenProcess") );

    unsigned char *addr = NULL;
    MEMORY_BASIC_INFORMATION meminfo;

    if (VirtualQueryEx(hProcess, addr, &meminfo, sizeof(meminfo)) == 0){
         printError( TEXT("VirtualQueryEx") );
         //return FALSE;
    }

}
  } while( Process32Next( hProcessSnap, &pe32 ) );

  CloseHandle( hProcessSnap );

  return( TRUE );
}

void printError( TCHAR* msg )
{
 ...
}

EDIT: The handle matters: enter image description here

EDIT 2: Additional Information:

  • Windows 7 64-bit platform.

  • Visual Studio 2012 (32-bit debugger) launched as Administrator

  • The process is * 32 (32 bit)
+4
source share

Source: https://habr.com/ru/post/1620932/


All Articles