WINAPI VirtualQueryEx - invalid handle - c++

I am trying to read some pages of memory of 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 error with the handle itself [hProcess] and I am passing in the appropriate parameters. What could be it?
#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: Handle has value:
EDIT 2: More Info:
Windows 7 64bit platform.
Visual Studio 2012 (32 bit debugger) ran
as Administrator
Process is *32 (32bit)

unsigned char *addr = NULL;
You're asking VirtualQueryEx to Query address 0 which is not valid, causing the failure.

Related

How to determine an application is already launched or not in windows using C++?

I am launching an windows desktop application by
CATStartProcess (const char *comPath,
char *const argv[],
int wait, int *pid,
int *exitStatus);
The arguments are passed to it.
If the application is already running I don't need to create a new instance for this. How can I check if this application is already running in background or not?
int wait = 0;
int pid;
int exitStatus;
char *CommandArgs[9] = { 0 };
CommandArgs[0] = (char*)usComposerExePath.ConvertToChar();
CommandArgs[1] = (char*)usOpen.ConvertToChar();
CommandArgs[2] = (char*)usComposerProjectDocPath.ConvertToChar();
CommandArgs[3] = (char*)strInfiniteTicket.ConvertToChar();
CommandArgs[4] = (char*)strDocName.ConvertToChar();
CommandArgs[5] = (char*)strSecurityContext.ConvertToChar();
CommandArgs[6] = (char*)usBusID.ConvertToChar();
CommandArgs[7] = (char*)usUserID.ConvertToChar();
CommandArgs[8] = NULL;
CATLibStatus startComposerBatchStatus = CATStartProcess((char*)usComposerExePath.ConvertToChar(), CommandArgs, wait, &pid, &exitStatus);
There's a few ways, but I'll admit, neither of my two solutions are portable/standard C++, but you tagged Windows, so I'll give a Windows method.
The below code actually performs both checks. The first method is to use a named mutex. Windows has a "Global" mutex, which checks for running processes by any user. If the mutex already exists, then its running. If it doesn't exist, then it's not running. There's some states where things can't be easily determined, so it checks the running process list. This part is less accurate, since different permissions affects the list.
The part with mutexes will only work if you can modify the application you are trying to launch so that it creates a mutex.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <psapi.h>
#include <TlHelp32.h>
#include <shellapi.h>
#include <advpub.h>
enum class ProcessRunningState {
YES,
NO,
ERR
};
ProcessRunningState CheckIfProcessIsAlreadyRunning( DWORD currentProcessId, const wchar_t *programName, const wchar_t *programGUID, HANDLE *mutex_handle ) noexcept {
{ // Check the mutexes first
wchar_t global_prog_name[1024] = L"Global\\";
wcsncat_s( global_prog_name, programName, wcslen( programGUID ) );
if ( mutex_handle ) {
*mutex_handle = CreateMutex( NULL, TRUE, global_prog_name );
if ( !( *mutex_handle ) ) {
const DWORD dw = GetLastError();
if ( dw == ERROR_ALREADY_EXISTS )
return ProcessRunningState::YES;
} else {
return ProcessRunningState::NO;
}
} else {
HANDLE h = OpenMutex( SYNCHRONIZE, FALSE, global_prog_name );
if ( h ) {
CloseHandle( h );
return ProcessRunningState::YES;
} else if ( GetLastError() == ERROR_FILE_NOT_FOUND ) {
return ProcessRunningState::NO;
}
}
}
{ // At this point, the state is unknown, so try running through the process list
DWORD aProcesses[2048], cProcesses;
if ( !EnumProcesses( aProcesses, sizeof( aProcesses ), &cProcesses ) ) {
return ProcessRunningState::ERR;
}
// Calculate how many process identifiers were returned.
cProcesses = cProcesses / sizeof( DWORD );
for ( unsigned int i = 0; i < cProcesses; i++ ) {
if ( aProcesses[i] != 0 && aProcesses[i] != currentProcessId ) {
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i] );
WCHAR szProcessName[MAX_PATH] = { 0 };
if ( hProcess ) {
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof( hMod ), &cbNeeded ) ) {
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof( szProcessName ) / sizeof( TCHAR ) ); // Can't error here, since this function "errors" on access
}/* else {
return ProcessRunningState::ERR;
}*/
CloseHandle( hProcess );
}
if ( _wcsicmp( szProcessName, programName ) == 0 ) {
return ProcessRunningState::YES;
}
}
}
}
return ProcessRunningState::NO;
}
Calling it like so will create the mutex if possible, and basically says that "I want to run, can I?"
HANDLE mutex_handle;
const ProcessRunningState cur_state = CheckIfProcessIsAlreadyRunning( GetCurrentProcessId(), L"PROGRAM_NAME", programGUID, &mutex_handle );
switch ( cur_state ) {
case ProcessRunningState::ERR:
case ProcessRunningState::YES:
return ERROR_ALREADY_EXISTS;
default:
break;
}
Calling it like so, simply checks if its already running, and launches the application if not.
if ( CheckIfProcessIsAlreadyRunning( GetCurrentProcessId(), L"PROGRAM_NAME", programGUID, nullptr ) == ProcessRunningState::NO ) {
std::wstring programInstallLocation = L"path";
std::wstring programName = programInstallLocation + L"\\PROGRAM_NAME";
ShellExecute( NULL, L"open", programName.c_str(), NULL, NULL, SW_SHOW );
}
And somewhere in your code, you would specify what programGUID is. For example:
WCHAR programGUID[] = L"ba2e95a0-9168-4b6e-bcd6-57309748df21";

GetProcessMemoryInfo failed with error 6 Handle is invalid

I'm trying to get the list of processes running in the system using C++. I use the functions available in the Windows API (like OpenProcess & CreateToolhelp32Snapshot ) to get it done.
The problem is that the code works fine for most of the processes, but couldn't get the memory info for crucial system processes alone, I have given the seDebugPrivilege also and have run the program as administrator only.
I get the output like
File Name PID Memory Used
winlogon.exe 1248 2432 KB
fontdrvhost.exe 1308
WARNING: GetProcessMemoryInfo failed with error 6 (The handle is invalid)
dwm.exe 1384
WARNING: GetProcessMemoryInfo failed with error 6 (The handle is invalid)
svchost.exe 1448 4744 KB
My code is :
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
HANDLE hToken;
PROCESSENTRY32 pe32;
DWORD dwPriorityClass;
PROCESS_MEMORY_COUNTERS pmc;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
char err[]="CreateToolhelp32Snapshot (of processes)";
printError( err );
return( FALSE );
}
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
char err[]="Process32First";
printError( err ); // show cause of failure
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken))
{
if (GetLastError() == ERROR_NO_TOKEN)
{
if (!ImpersonateSelf(SecurityImpersonation))
return FALSE;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)){
char err[]="OpenThreadToken";
printError( err );
return FALSE;
}
}
else
return FALSE;
}
SetPrivilege(hToken, SE_DEBUG_NAME, FALSE);
do
{
printf( "%-25s", pe32.szExeFile );
dwPriorityClass = 0;
SIZE_T dwMin, dwMax;
hProcess = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION , FALSE, pe32.th32ProcessID );
printf("%-10d", pe32.th32ProcessID );
if(GetProcessMemoryInfo( hProcess, (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc)))
{
printf( "%-10d KB", pmc.PagefileUsage/1024);
} else{
char err[]="GetProcessMemoryInfo";
printError( err );
}
printf("\n");
CloseHandle(hProcess);
}while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
To get this code to work, you have to change:
SetPrivilege(hToken, SE_DEBUG_NAME, FALSE)
to:
SetPrivilege(hToken, SE_DEBUG_NAME, TRUE)
As others have commented, to get this code to work properly, you have to:
check for and report all possible error conditions
release all resources when you are done, in this case release hToken (via CloseHandle()) and call revertToSelf() if needs be.
Other than that, it's a decent effort so thumbs up for that.
Link to SetPrivilege(), in case any future visitor needs it:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa446619.aspx
Happy hacking.

Kill a process with its processID

I'm trying to display all the running process along with their memory usage and provide a kill option, i've used the OpenProcess method to get the memory used by the current process. How do I kill a process with a processID?
Here is the code:
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
HANDLE hToken;
PROCESSENTRY32 pe32;
DWORD dwPriorityClass;
PROCESS_MEMORY_COUNTERS pmc;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
return( FALSE );
}
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
printError( TEXT("Process32First") ); // show cause of failure
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken))
{
if (GetLastError() == ERROR_NO_TOKEN)
{
if (!ImpersonateSelf(SecurityImpersonation))
return FALSE;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)){
printError( TEXT("OpenThreadToken") );
return FALSE;
}
}
else
return FALSE;
}
SetPrivilege(hToken, SE_DEBUG_NAME, FALSE);
do
{
printf( TEXT("\nPROCESS NAME: %s"), pe32.szExeFile );
dwPriorityClass = 0;
SIZE_T dwMin, dwMax;
hProcess = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION , FALSE, pe32.th32ProcessID );
if(GetProcessMemoryInfo( hProcess, (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc)))
{
printf( "\nPagefileUsage: %d KB", pmc.PagefileUsage/1024);
} else{
printError( TEXT("GetProcessMemoryInfo") );
}
CloseHandle(hProcess);
}while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
Since you have an hProcess to hand, you can just use that:
BOOL ok = TerminateProcess (hProcess, exit_code);
Where exit_code can be anything you like (try to make it meaningful, in case anything is waiting on the process and would like to know why it exited).
If you don't want to do it that way, you can use OpenProcess:
HANDLE hProcess = OpenProcess (PROCESS_TERMINATE, FALSE, process_id);
if (hProcess)
{
BOOL ok = TerminateProcess (hProcess, exit_code);
CloseHandle (hProcess);
}
else
{
DWORD err = GetLastError ();
...
}
You need to check that OpenProcess() succeeded because (amongst other things), you might not have sufficient access rights, and you need to close hProcess after you're done with it, even though you've killed the process itself.
Documentation for TerminateProcess() here.

Filter System processes from user processes

I need to know how can I filter current user files/processes from operating system processes ?
I have listed all the current running files through the attached code in C++ .
now, i need to know how can i show only user files from this list?
Is there any demarcation parameter for this!!
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
// Forward declarations:
BOOL GetProcessList( );
BOOL ListProcessModules( DWORD dwPID );
void printError( TCHAR* msg );
int main( void )
{
GetProcessList( );
return 0;
}
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
// 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
{
_tprintf( TEXT("\n\n=====================================================" ));
_tprintf( TEXT("\nPROCESS NAME: %s"), pe32.szExeFile );
// List the modules and threads associated with this process
ListProcessModules( pe32.th32ProcessID );
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
BOOL ListProcessModules( DWORD dwPID )
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
MODULEENTRY32 me32;
// Take a snapshot of all modules in the specified process.
hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );
if( hModuleSnap == INVALID_HANDLE_VALUE )
{
printError( TEXT("CreateToolhelp32Snapshot (of modules)") );
return( FALSE );
}
// Set the size of the structure before using it.
me32.dwSize = sizeof( MODULEENTRY32 );
// Retrieve information about the first module,
// and exit if unsuccessful
if( !Module32First( hModuleSnap, &me32 ) )
{
printError( TEXT("Module32First") ); // show cause of failure
CloseHandle( hModuleSnap ); // clean the snapshot object
return( FALSE );
}
// Now walk the module list of the process,
// and display information about each module
do
{
_tprintf( TEXT("\n\n MODULE NAME: %s"), me32.szModule );
_tprintf( TEXT("\n Executable = %s"), me32.szExePath );
} while( Module32Next( hModuleSnap, &me32 ) );
CloseHandle( hModuleSnap );
return( TRUE );
}
void printError( TCHAR* msg )
{
DWORD eNum;
TCHAR sysMsg[256];
TCHAR* p;
eNum = GetLastError( );
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, eNum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
sysMsg, 256, NULL );
// Trim the end of the line and terminate it with a null
p = sysMsg;
while( ( *p > 31 ) || ( *p == 9 ) )
++p;
do { *p-- = 0; } while( ( p >= sysMsg ) &&
( ( *p == '.' ) || ( *p < 33 ) ) );
// Display the message
_tprintf( TEXT("\n WARNING: %s failed with error %d (%s)"), msg, eNum, sysMsg );
}

Does this program leak memory?

Due to the new usage for returning the process id? And how can i check when memory is begin leaked, throughtout debugging my application? (This length check on the explanation section really sucks =P)
#include "stdafx.h"
#include "Process.h"
#include <TlHelp32.h>
#include <iostream>
DWORD GetProcessId( const wchar_t* szProcess )
{
if( szProcess )
{
HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
PROCESSENTRY32 *pe32 = new PROCESSENTRY32();
memset( pe32, 0, sizeof( PROCESSENTRY32 ) );
pe32->dwSize = sizeof( PROCESSENTRY32 );
//Process32First( hSnapshot, pe32 );
while( Process32Next( hSnapshot, pe32 ) )
{
if( pe32->szExeFile && !wcscmp( szProcess, pe32->szExeFile ) )
{
CloseHandle( hSnapshot );
return( pe32->th32ProcessID ); // std::wcout << pe32->szExeFile << std::endl;
}
}
CloseHandle( hSnapshot );
}
return 0;
}
HANDLE GetProcessHandle( DWORD dwProcessId )
{
if( dwProcessId )
return( OpenProcess( PROCESS_VM_READ | PROCESS_VM_WRITE, 0, dwProcessId ) );
return 0;
}
bool WriteExternProcessMemory( HANDLE hProcess, void* pAddr, size_t uSize, const char* szWrite, LPCVOID outBuffer )
{
if( pAddr && szWrite && hProcess )
{
DWORD dwOldProtect;
if( !VirtualProtectEx( hProcess, pAddr, uSize, PAGE_EXECUTE_READWRITE, &dwOldProtect ) )
return( !WriteProcessMemory( hProcess, pAddr, outBuffer, uSize, NULL ) );
}
return false;
}
-Edit,
the usage is:
void *pRecv;
WriteExternProcessMemory( GetProcessHandle( GetProcessId( _T( "notepad.exe" ) ) ), (void*)0x401000, 2, "\x40\x40", &pRecv );
This is leaking:
PROCESSENTRY32 *pe32 = new PROCESSENTRY32();
Better use:
PROCESSENTRY32 pe32 = {0};
pe32.dwSize = sizeof( PROCESSENTRY32 );
//Process32First( hSnapshot, pe32 );
while( Process32Next( hSnapshot, &pe32 ) )
...
Also, you're not closing the handle created at GetProcessHandle, which is also a leak.
Yes, you are right. Allocating memory without freeing it later, as your program does, constitutes a memory leak.
You can find leaks in your program by using a memory leak detector.
Valgrind is a wonderful tool to tell you about memory leaks. If you are compiling with debugging symbols (-g for GCC), it will even tell you what line the leak happened on!
http://valgrind.org/