C++ Process Monitoring (GetExitCodeProcess) - c++

I want to monitor a process in c++, so I'm using:
std::wstring windowName = TEXT("needle");
HWND windowHandle = FindWindowW(NULL, windowName.c_str());
The FindWindow function, as I understand it, checks the title for all windows (Why did Microsoft name their OS after a core part of it, checking windows in Windows, madness). If a title matches "needle" then it gives me the...
HWND windowHandle
Next I am using:
DWORD* PID;
GetWindowThreadProcessId(windowHandle, PID);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, *PID);
This gives me the processID or PID as I've named it. I can then use that to...
HWND p;
DWORD state;
GetExitCodeProcess(p, &state);
... get the state of the process, I'm going to check for it being "STILL_ACTIVE", like so:
if (state != STILL_ACTIVE) {
std::cout << "excessive profanity\n";
}
else {
std::cout << "sigh of relief\n";
}
Except this doesn't work, "cout-ing" (new verb) the value of state gives me some kind of hexadecimal code. It's never "STILL_ACTIVE" despite having multiple windows with "needle" as the title. The code compiles fine, it's just something to do with conversion, pointers, LPCWSTR's or something I've never come across. Help would be appreciated. Thanks

You have two problems:
1) As PaulMcKenzie points out in his answer, PID points to nothing, and will cause problems. Instead you should declare a DWORD and pass a pointer to it to GetWindowThreadProcessId:
DWORD PID;
// note: &PID instead of just PID
GetWindowThreadProcessId(windowHandle, &PID);
// note: Just PID instead of *PID
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
2) GetExitCodeProcess needs a handle to a process, not an uninitialized HWND. Instead you should give it the handle returned from OpenProcess:
DWORD state;
// note: this is the hProcess returned from OpenProcess
GetExitCodeProcess(hProcess, &state);
Note that this will still only work for one process. If multiple processes have windows with the title "needle" then the result of your FindWindow call will be unpredictable.

One error (and probably not the only error) is that there is no way this can work correctly:
DWORD* PID;
GetWindowThreadProcessId(windowHandle, PID);
You are giving GetWindowThreadProcessId an uninitialized pointer, PID. There is nothing that the function can do with it except dereference it (causing undefined behavior), or at best, check if the value is NULL.
When a function asks for a pointer, it doesn't mean you literally declare a pointer and pass it to the function. The function wants the address of an existing entity:
DWORD PID;
GetWindowThreadProcessId(windowHandle, &PID);

Related

C++ Correct Usage of LPDWORD

I have an array of hWnds of buttons that I want to monitor for clicks. I also have an array of HWINEVENTHOOKs that I will use to monitor them. GetWindowThreadProcessID gives me an LPDWORD process ID, which is not accepted by SetWinEventHook. I am unclear on whether I am correctly using LPDWORDs in this example. Please could somebody point me in the right direction?
EDIT: Thank you to everyone who contributed, I have posted the corrected code below.
New Code:
int i = 0;
for (HWND hWnd : hWnds) {
DWORD processID = 0;
DWORD threadID = GetWindowThreadProcessId(hWnd, &processID);
hooks[i] = SetWinEventHook(EVENT_OBJECT_INVOKED, EVENT_OBJECT_INVOKED,
NULL,
WinEventProcCallback, processID, threadID, WINEVENT_OUTOFCONTEXT);
i++;
}
LPDWORD is just a typedef for DWORD* and when a Windows SDK function parameter is a "LPsomething" you generally need to pass a pointer to a "something" (except for the LP[C][W]STR string types).
DWORD processID;
DWORD threadID = GetWindowThreadProcessId(hWnd, &processID);
if (threadID)
{
// Do something with threadID and/or processID
}
The Windows SDK uses Systems Hungarian notation for the Desktop/Classic API.

C++ return float

I create a API for a Game.
My Problem: I want to read a float value from the Memory.
Result (Cheat Engine) 100
My Result with the API: 0.00000
extern "C" __declspec(dllexport) float samp_health()
{
hwnd = FindWindow(NULL, L"MyGame");
GetWindowThreadProcessId(hwnd, &pid);
HANDLE phandle = OpenProcess(PROCESS_VM_READ, false, pid);
float value = 0;
ReadProcessMemory(phandle, (float*)(PlayerPointer + HealthOffset), &value, 4, NULL);
CloseHandle(phandle);
return value;
}
What is wrong?
With this line,
HANDLE phandle = OpenProcess(PROCESS_VM_READ, false, pid);
you need to check for failure.
And in this following line,
ReadProcessMemory(phandle, (float*)(PlayerPointer + HealthOffset), &value, 4, NULL);
assuming the ReadProcessMemory works as roughly indicated by the arguments, the PlayerPointer needs to be a valid pointer in the process identified by phandle, and if the HealthOffset is an offset in bytes, then PlayerPointer needs to be a pointer to byte.
Most likely it's not.
Reading process memory is generally not a good way to communicate between processes.
Here are some alternatives:
Don't do process communication, do threads or whatever.
Use Windows COM technology.
Use Windows mailslots.
Use Windows window messages (e.g. WM_DATA).
Use sockets.
Use files.
Use pipes.
Almost anything, just not the direct access of process memory.
Summing up, the main problem is use of a too low level of abstraction.

Get base address of process

I want to access a certain address of a process. But for that i need to get the base address of the process first. I'm using a tool to see if i'm actually doing it right. The tool shows i need the following: "app.exe"+0x011F9B08 = 0x119F8300
I thought i could obtain the base address of a process through OpenProcess(), but that gives me: 0x0000005c as a result. I don't think that is right? Atleast, not what i need.
I think the base address i need is: 0x119F8300 - 0x011F9B08 = 0x107FE7F8 <-- base?
This is my code:
hWindow = FindWindow(NULL, lpWindowName);
if(hWindow)
{
GetWindowThreadProcessId(hWindow, &dwProcId);
if(dwProcId != 0)
{
// hProcHandle -> 0x0000005c
hProcHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcId);
}
else
{
return 0;
}
}
How can i get the base address of the process that i've opened?
If you want to get the virtual address within the other process's address space, you can do that like so:
Open the process using OpenProcess -- if successful, the value returned is a handle to the process, which is just an opaque token used by the kernel to identify a kernel object. Its exact integer value (0x5c in your case) has no meaning to userspace programs, other than to distinguish it from other handles and invalid handles.
Call GetProcessImageFileName to get the name of the main executable module of the process.
Use EnumProcessModules to enumerate the list of all modules in the target process.
For each module, call GetModuleFileNameEx to get the filename, and compare it with the executable's filename.
When you've found the executable's module, call GetModuleInformation to get the raw entry point of the executable.
This will give you the virtual address, but there's not a whole lot you can do with it since it's not mapped into your current process's address space.
I wanted to elaborate a bit on #Adam Rosenfield's answer. I will use League of Legends as an example here.
In order to open the process (Getting a handle) we need it's PID (Process ID). We can do that via a window handle (HWND) because usually the title of the window is known
//You will need to change this the name of the window of the foreign process
HWND WindowHandle = FindWindow(nullptr, L"League of Legends (TM) Client");
DWORD PID;
GetWindowThreadProcessId(WindowHandle, &PID);
PVOID hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, PID);
Now that we are able to get a handle to the process let's continue
HMODULE Module = GetModule();
DWORD BaseAddress = (DWORD)Module;
The GetModule function
HMODULE GetModule()
{
HMODULE hMods[1024];
HANDLE pHandle = GetHandle();
DWORD cbNeeded;
unsigned int i;
if (EnumProcessModules(pHandle, hMods, sizeof(hMods), &cbNeeded))
{
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
{
TCHAR szModName[MAX_PATH];
if (GetModuleFileNameEx(pHandle, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
{
wstring wstrModName = szModName;
//you will need to change this to the name of the exe of the foreign process
wstring wstrModContain = L"League of Legends.exe";
if (wstrModName.find(wstrModContain) != string::npos)
{
CloseHandle(pHandle);
return hMods[i];
}
}
}
}
return nullptr;
}
as for me personally I like to write 2 separate functions one for getting a handle and one for getting the module.
There we go, we have successfully gotten the base address of a foreign process.

Reading a process memory

I'm trying to read the process memory of a console program using ReadProcessMemory() API function.
Updated Code:
HWND hWnd = FindWindow(NULL, "Read Memory Window");
DWORD ProcessId;
ProcessId = GetProcessId(hWnd);
GetWindowThreadProcessId(hWnd, &ProcessId);
HANDLE hProcess = OpenProcess(PROCESS_VM_READ,FALSE, ProcessId);
SIZE_T NumberOfBytesRead;
CHAR Buffer[128] = {0};
dwAddr = 0x0012FD6C; //address of array to get
BOOL sucess = ReadProcessMemory(hProcess, &dwAddr, &Buffer, 128, &NumberOfBytesRead);
I get null and garbage values as i run the program along with program to read the array.
your using a fixed address, that is generally a very bad idea, even more so now that windows vista and windows 7 use ASLR, making it unsafe for even fixed based modules(even without ASLR its unsafe, because the image can reallocated for various reasons).
also, that address looks very dodgy, how did you derive that address? and is it adjusted correctly as a virtual address and not a relative address?
finally and most importantly, you shouldn't be passing the address and buffer as you do, it should be passed like so:
BOOL sucess = ReadProcessMemory(hProcess, (LPVOID)dwAddr, &Buffer[0], 128, &NumberOfBytesRead);
or
BOOL sucess = ReadProcessMemory(hProcess, (LPVOID)dwAddr, Buffer, 128, &NumberOfBytesRead);

C++ TerminateProcess function

I've been searching examples for the Win32 API C++ function TerminateProcess() but couldn't find any.
I'm not that familiar with the Win32 API in general and so I wanted to ask if someone here who is better in it than me could show me an example for,
Retrieving a process handle by its PID required to terminate it and then call TerminateProcess with it.
If you aren't familiar with C++ a C# equivalent would help too.
To answer the original question, in order to retrieve a process handle by its PID and call TerminateProcess, you need code like the following:
BOOL TerminateProcessEx(DWORD dwProcessId, UINT uExitCode)
{
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (hProcess == NULL)
return FALSE;
BOOL result = TerminateProcess(hProcess, uExitCode);
CloseHandle(hProcess);
return result;
}
Keep in mind that TerminateProcess does not allow its target to clean up and exit in a valid state. Think twice before using it.