Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active October 18, 2022 18:44
Show Gist options
  • Save pervognsen/adc1e767c9f62643ef09 to your computer and use it in GitHub Desktop.
Save pervognsen/adc1e767c9f62643ef09 to your computer and use it in GitHub Desktop.
debugbreakprocess.cpp
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <vector>
int main(int argc, char **argv)
{
if (argc != 2)
return 1;
const char *sibling_name = argv[1];
// Enumerate all processes in the system.
std::vector<PROCESSENTRY32> entries;
{
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot == INVALID_HANDLE_VALUE)
return 2;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
if(!Process32First(snapshot, &entry))
{
CloseHandle(snapshot);
return 3;
}
do
{
entries.push_back(entry);
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
}
// Find parent.
DWORD current_pid = GetCurrentProcessId();
DWORD parent_pid = 0;
for (int i = 0; i < entries.size(); i++)
{
if (entries[i].th32ProcessID == current_pid)
{
parent_pid = entries[i].th32ParentProcessID;
break;
}
}
if (parent_pid == 0)
{
printf("No parent process.\n");
return 4;
}
// Find named sibling.
DWORD sibling_pid = 0;
for (int i = 0; i < entries.size(); i++)
{
if (entries[i].th32ParentProcessID == parent_pid && strcmp(entries[i].szExeFile, sibling_name) == 0)
{
sibling_pid = entries[i].th32ProcessID;
break;
}
}
if (sibling_pid == 0)
{
printf("Sibling process '%s' not found.\n", sibling_name);
return 5;
}
// Call DebugBreakProcess on sibling's children.
for (int i = 0; i < entries.size(); i++)
{
if (entries[i].th32ParentProcessID == sibling_pid)
{
printf("Calling DebugBreakProcess on %s (%lu).\n", entries[i].szExeFile, entries[i].th32ProcessID);
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entries[i].th32ProcessID);
if (!process)
{
printf("Failed to open process %s.\n", entries[i].szExeFile);
return 6;
}
if (DebugBreakProcess(process) == 0)
{
printf("DebugBreakProcess failed.\n");
CloseHandle(process);
return 7;
}
CloseHandle(process);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment