Imposible declaration INT variable in my program - c++

I tried to create a little project in C++ . My program should be able to read the currently running processes in Windows and send information about the processes to my private MySQL database every 5 minutes. In this amount of time I can read the processes.
See code below:
#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
bool getAllProcesses(void);
int main(void){
getAllProcesses();
}
bool getAllProcesses(){
HANDLE WINAPI snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
LPPROCESSENTRY32 pe32;
Process32First(snapshot, pe32);
while(Process32Next(snapshot, pe32)){
std::cout << pe32->szExeFile << "\n";
}
std::cout << "End of list";
CloseHandle( snapshot );
return true;
}
The code above is working fine.
But if I add the code "int i;i=1;" like this:
#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
bool getAllProcesses(void);
int main(void){
getAllProcesses();
}
bool getAllProcesses(){
int i;
i=0;
HANDLE WINAPI snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
LPPROCESSENTRY32 pe32;
Process32First(snapshot, pe32);
while(Process32Next(snapshot, pe32)){
std::cout << pe32->szExeFile << "\n";
}
std::cout << "End of list";
CloseHandle( snapshot );
return true;
}
With this change the program will crash, showing the alert "Program stop the work".
I tried to find the problem and I've determined the following :
If I use the function Process32First() OR Process32Next() I can't declare the same int in all of the program.
What is the problem?

You have a lot of issues going on here. I tried this on VS 2008 Win7.
The "i" declaration has nothing to do with the problem, but may just be moving the stack a bit to hide the real problems. See my comments in the corrected code below.
bool getAllProcesses(){
int i;
i=0;
HANDLE WINAPI snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
/* replace LPPROCESSENTRY32 with PROCESSENTRY32. LP is just a define as
a pointer to a structure, so you did not actually allocate any memory for the
return of Process32First() to return the result into.
So you were probably overwriting stuff in the stack. */
PROCESSENTRY32 pe32;
/* need to initialize the structure properly. Memset may be overkill,
but better to see all zeros than garbage. dwSize must be
initialized as per the SDK documentation. */
memset(&pe32,0,sizeof(pe32) );
pe32.dwSize = sizeof(pe32);
BOOL result;
/* did not check the result from the call if TRUE/FALSE */
result = Process32First(snapshot, &pe32);
std::cout << "result =" << result << "\n";
while(Process32Next(snapshot, &pe32)){
std::cout << pe32.szExeFile << "\n";
}
std::cout << "End of list";
CloseHandle( snapshot );
return true;
}

The addition of those 2 lines making the program not able to run is just a coincidence. The program should not be running at all, since there are 2 major mistakes:
pe32 is an uninitialized pointer
dwSize member of PROCESSENTRY32 structure is not initialized as described in the [MS.Docs]: Process32First function:
The calling application must set the dwSize member of PROCESSENTRY32 to the size, in bytes, of the structure.
And a third, smaller mistake is that you are ignoring the process data returned by Process32First.
In order to make things work correctly, replace the following lines of your code:
LPPROCESSENTRY32 pe32;
Process32First(snapshot, pe32);
while(Process32Next(snapshot, pe32)){
std::cout << pe32->szExeFile << "\n";
, with:
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &pe32))
{
do {
std::cout << pe32.szExeFile << "\n";
}
while (Process32Next(snapshot, &pe32));
}

Related

How to read a memory address' value from an exe?

So I am trying to output how many rings I have when I run SonicAdventureDXPC.exe via reading a memory address. I got the address where it stores the ring count but when I run the code it would always output -1082988699 (even if the ring count was 1 or higher). This is the code I have:
#include <windows.h>
#include <iostream>
DWORD ADDR = 0x370F0E4;
DWORD PID;
int main(int argc, char* argv[]) {
HWND Window = FindWindow(0, "SonicAdventureDXPC");
if (Window == 0) {
std::cout << "Can't find the window"<< std::endl;
}
else {
GetWindowThreadProcessId(Window, &PID);
HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
if (Process != 0) {
int Read_V;
ReadProcessMemory(Process, (LPVOID)ADDR, &Read_V, sizeof(Read_V), 0);
std::cout << "Rings: " << Read_V << std::endl;
system("PAUSE");
}
}
return 0;
}
Edit: The code is actually correct but me being me made a very dumb tiny mistake. While troubleshooting with Cheat Engine, I found out that I made a typo in the address variable. It was suppose to be 0x03B0F0E4, not 0x03F0F0E4.

GetProcessId doesn't find any process

I'm using the following code to try to get the PID of notepad.exe, but it doesn't find the process.
I'm currently running on Windows 10 and compiling using VS Studio 19 as Release x64.
Also tried to find other processes, like chrome.exe, calculator.exe, etc, but couldn't find anything.
DWORD GetProcessId(LPCTSTR ProcessName)
{
PROCESSENTRY32 pt;
HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0
pt.dwSize = sizeof(PROCESSENTRY32);
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0
if (Process32First(hsnap, &pt)) { // must call this first
do {
if (!lstrcmpi(pt.szExeFile, ProcessName)) {
CloseHandle(hsnap);
return pt.th32ProcessID;
}
} while (Process32Next(hsnap, &pt));
}
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 24
CloseHandle(hsnap); // close handle on failure
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD processId;
processId = GetProcessId(TEXT("notepad.exe"));
std::wcout << "processId: " << processId << std::endl;
return 0;
}
While debugging, I see the code is skipping the do while and jumping directly to CloseHandle(hsnap)
GetLastError() returns 24 at this line.
The image you posted of your debug output window shows pt.dwSize is set to 2168. This looks wrong. pt.dwSize is important, it used by Windows for version control.
On my computer sizeof(PROCESSENTRY32) is 556 (it depends on Windows version, I am using Windows 10). If project is not Unicode, the size should about half that. In VS, you can right click on PROCESSENTRY32 and it takes you to this definition:
typedef struct tagPROCESSENTRY32W
{
DWORD dwSize;
DWORD cntUsage;
DWORD th32ProcessID; // this process
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID; // associated exe
DWORD cntThreads;
DWORD th32ParentProcessID; // this process's parent process
LONG pcPriClassBase; // Base priority of process's threads
DWORD dwFlags;
WCHAR szExeFile[MAX_PATH]; // Path
} PROCESSENTRY32W;
MAX_PATH should be 260. My guess is that you have redefined MAX_PATH or you have put the wrong #pragma statement somewhere. Or there is something weird happening. Try restarting Windows (use Restart instead of shutdown/start)
Also, zero the memory with PROCESSENTRY32 pt = {0}
PROCESSENTRY32 pt = { 0 };
pt.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hsnap, &pt))
{
DWORD err = GetLastError();
std::cout << "Process32First failed\n";
std::cout << pt.dwSize << " GetLastError : " << err << "\n";
CloseHandle(hsnap);
return DWORD(-1);
}
The only expected GetLastError is ERROR_NO_MORE_FILES as shown in Windows documentation. If the error is something else, it means the function has totally failed.
If your project is Unicode, as it should be, consider avoiding those T macros. Just use GetProcessId(L"notepad.exe"); and LPCWSTR etc.
Ps, I ran your code and it was fine in my computer. The only difference was sizeof(PROCESSENTRY32)

How to get the returned exit value of an invoked program to store it internally? [duplicate]

This question already has an answer here:
checking the return value of a command executed using CreateProcess
(1 answer)
Closed 2 years ago.
This question is related to a previously asked question found here:
I'm able to invoke another executable within my runProgram() function. However, before this runProgram() function returns back to main() and closes the handle for the process. I need to retrieve the value that the executable returns when it exits...
Here is my current application:
#include <Windows.h>
#include <exception>
#include <stdio.h>
#include <tchar.h>
#include <cstdint>
#include <iostream>
uint32_t runProgram(LPCSTR lpApplicationName) {
STARTUPINFOA si;
PROCESS_INFORMATION pi;
// Set the size of the structures
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Run the program
CreateProcessA(
lpApplicationName, // the path
NULL, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Opens file in seperate console
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure
);
uint32_t error = GetLastError();
if ( error != 0)
std::cerr << error << "\n";
// How to retrieve and store the result from the exiting program above...?
uint32_t cache_size = 0;
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return cache_size;
}
int main() {
try {
const uint32_t cache_size = runProgram("CacheQuerry.exe");
std::cout << cache_size << '\n';
}
catch (const std::exception& e) {
std::cerr << e.what() << "\n\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
And I want to store the return value from this executable into runProgram()'s local variable: cache_size.
Here is the main.cpp from the invoked program:
#include "CacheQuerry.h"
int main() {
int error = cache_info();
if (error != 0)
std::cout << error << '\n';
else
std::cout << '\n';
std::cout << "l1d_cache_size = " << l1d_cache_size() << std::endl;
std::cout << "cache line size = " << cache_line_size() << '\n';
return l1d_cache_size();
}
The invoked program will return the value produced by l1d_cache_size() when this program exits. This is the value that I want to store within runProgram()'s cache_size variable. How do I get this return value after the program exits? The implementation of the function call found in "CacheQuerry.h" shouldn't be relevant here, but if you need to see it's implementation don't hesitate to ask. These are two separate projects within the same solution. The 1st main.cpp which is in its own project relies on the 2nd main.cpp within its own project.
You can get it by calling GetExitCodeProcess (pi.hProcess), after waiting on the handle but before you close it.
The exact code you need is:
DWORD exit_code;
BOOL ok = GetExitCodeProcess (pi.hProcess, &exit_code);
Strange this is not mentioned in the Remarks section for CreateProcess at all.

Getting a browser process ID and then using it in the program in C++

I am trying to create a simple word highlighter for browsers (Chrome and Firefox) and I would like my program to use the process name (chrome.exe or firefox.exe) and then get their process ID.
I've found code that lets me get the process ID, but it requires a user to type the process name manually:
#include "pch.h"
#include <iostream>
#include <string>
#include <windows.h>
#include <tlhelp32.h>
DWORD FindProcessId(const std::wstring& processName);
int main()
{
std::wstring processName;
std::wcout << "Enter the process name: ";
std::getline(std::wcin, processName);
DWORD processID = FindProcessId(processName);
if (processID == 0)
std::wcout << "Could not find " << processName.c_str() << std::endl;
else
std::wcout << "Process ID is " << processID << std::endl;
system("PAUSE");
return 0;
}
DWORD FindProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
Now, is there a way to manipulate this code for it to get the process ID automatically by checking whether the user is running firefox.exe or chrome.exe?
And after getting the process ID, how do I make my program understand that it needs to focus on said ID?
Now, is there a way to manipulate this code for it to get the process ID automatically by checking whether the user is running firefox.exe or chrome.exe?
#include <iostream>
#include <string>
#include <windows.h>
#include <tlhelp32.h>
DWORD FindProcessId(const std::wstring& processName);
int main()
{
std::wstring fifi = L"firefox.exe";
std::wstring gogo = L"chrome.exe";
auto fifi_proc_id = FindProcessId(fifi);
auto gogo_proc_id = FindProcessId(gogo);
if(fifi_proc_id && gogo_proc_id) {
// both runnin O.O what now?
}
else if(fifi_proc_id) {
// firefox running ... do stuff
}
else if(gogo_proc_id) {
// chrome running ... do stuff
}
else {
// none of both :(
}
}
And after getting the process ID, how do I make my program understand that it needs to focus on said ID?
I am sorry, but I don't know what you mean by "make my program understand that it needs to focus on said ID".

How to retrive process handle by using application name in c++?

How to retrieve process handle by using application name in c++?
Is there any windows API is there?
Example: Sample.exe
I have to get the handle of this sample.exe and I need to call Terminate process on that handle.
Any one suggest a good solution for this.
Note: its should support winxp and win8
Thanks in Advance
You should use toolhelp API's:
HANDLE OpenProcessByName(LPCTSTR Name, DWORD dwAccess)
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe;
ZeroMemory(&pe, sizeof(PROCESSENTRY32));
pe.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnap, &pe);
do
{
if (!lstrcmpi(pe.szExeFile, Name))
{
return OpenProcess(dwAccess, 0, pe.th32ProcessID);
}
} while (Process32Next(hSnap, &pe));
}
return INVALID_HANDLE_VALUE;
}
For example:
#include <windows.h>
#include <tlhelp32.h>
//...
int main()
{
HANDLE hFire = OpenProcessByName("firefox.exe", PROCESS_VM_READ);
cout << "Handle: " << hFire << endl;
CloseHandle(hFire);
cin.get();
return 0;
}
But you should be careful because if there are more than 1 copy of process you will get a handle of the first. To handle all processes in "return OpenProcess" use call of some function like Handler(OpenProcess(dwAccess, 0, pe.th32ProcessID)):
void Handler(HANDLE hndl)
{
//... work with your Handle
CloseHandle(hndl);
}
//...
if (!lstrcmpi(pe.szExeFile, Name))
{
Handler(OpenProcess(dwAccess, 0, pe.th32ProcessID)):
}
//...
To fetch the process name from process id see quiestions: get process name from process id (win32) or How to get the process name in C++
Enumerate process documentation https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629%28v=vs.85%29.aspx Example code: https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms682623%28v=vs.85%29.aspx
EDIT: There is solution that does not have problem "return the hanlde of the first matching found, whereas there may be multiple instances". This solution return array of pairs ProcessId and names, and you can select that you need in simple loop.
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <map>
typedef std::pair<DWORD,std::string> ProcessVectorEntry;
typedef std::vector<ProcessVectorEntry> ProcessVector;
void getProcessInformation( ProcessVector& processVector ) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnapshot, &pe32)) {
do {
processVector.push_back( ProcessVectorEntry( pe32.th32ProcessID, pe32.szExeFile ) );
} while(Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
}
}
And simple search in main
int main() {
std::string search = "firefox.exe";
ProcessVector processVector;
getProcessInformation( processVector );
std::cout << "Process IDs contains " << search << " in name:" << std::endl;
for( int i=0; i<processVector.size(); ++i )
if( processVector[i].second.find(search) != std::string::npos )
std::cout << processVector[i].first << std::endl;
return 0;
}