MCPcopy Create free account
hub / github.com/Phobos-developers/Phobos / DetachFromDebugger

Method DetachFromDebugger

src/Phobos.Ext.cpp:301–369  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

299#include <tlhelp32.h>
300
301bool Phobos::DetachFromDebugger()
302{
303 auto GetDebuggerProcessId = [](DWORD dwSelfProcessId) -> DWORD
304 {
305 DWORD dwParentProcessId = -1;
306 HANDLE hSnapshot = CreateToolhelp32Snapshot(2, 0);
307 PROCESSENTRY32 pe32;
308 pe32.dwSize = sizeof(PROCESSENTRY32);
309 Process32First(hSnapshot, &pe32);
310 do
311 {
312 if (pe32.th32ProcessID == dwSelfProcessId)
313 {
314 dwParentProcessId = pe32.th32ParentProcessID;
315 break;
316 }
317 }
318 while (Process32Next(hSnapshot, &pe32));
319 CloseHandle(hSnapshot);
320 return dwParentProcessId;
321 };
322
323 HMODULE hModule = LoadLibrary("ntdll.dll");
324 if (hModule != NULL)
325 {
326 auto const NtRemoveProcessDebug =
327 (NTSTATUS(__stdcall*)(HANDLE, HANDLE))GetProcAddress(hModule, "NtRemoveProcessDebug");
328 auto const NtSetInformationDebugObject =
329 (NTSTATUS(__stdcall*)(HANDLE, ULONG, PVOID, ULONG, PULONG))GetProcAddress(hModule, "NtSetInformationDebugObject");
330 auto const NtQueryInformationProcess =
331 (NTSTATUS(__stdcall*)(HANDLE, ULONG, PVOID, ULONG, PULONG))GetProcAddress(hModule, "NtQueryInformationProcess");
332 auto const NtClose =
333 (NTSTATUS(__stdcall*)(HANDLE))GetProcAddress(hModule, "NtClose");
334
335 HANDLE hDebug;
336 HANDLE hCurrentProcess = GetCurrentProcess();
337 NTSTATUS status = NtQueryInformationProcess(hCurrentProcess, 30, &hDebug, sizeof(HANDLE), 0);
338 if (0 <= status)
339 {
340 ULONG killProcessOnExit = FALSE;
341 status = NtSetInformationDebugObject(
342 hDebug,
343 1,
344 &killProcessOnExit,
345 sizeof(ULONG),
346 NULL
347 );
348 if (0 <= status)
349 {
350 const auto pid = GetDebuggerProcessId(GetProcessId(hCurrentProcess));
351 status = NtRemoveProcessDebug(hCurrentProcess, hDebug);
352 if (0 <= status)
353 {
354 HANDLE hDbgProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
355 if (INVALID_HANDLE_VALUE != hDbgProcess)
356 {
357 BOOL ret = TerminateProcess(hDbgProcess, EXIT_SUCCESS);
358 CloseHandle(hDbgProcess);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected