MSDN

Win32 Debugging API

Overview

The Win32 Debugging API provides functions that enable a developer to control, monitor, and manipulate the execution of a target process for debugging purposes. These functions form the foundation of many debugging tools, including Visual Studio, WinDbg, and custom debuggers.

Note: Debugging functions require appropriate privileges. On Windows 10 and later, a process must be started with SE_DEBUG_NAME privilege or run as Administrator.

Key Functions

DebugActiveProcess

Attaches the debugger to an already running process.

#include <windows.h>
BOOL result = DebugActiveProcess(dwProcessId);

DebugActiveProcessStop

Detaches the debugger from a process.

#include <windows.h>
BOOL result = DebugActiveProcessStop(dwProcessId);

DebugBreak

Causes a breakpoint exception to be raised in the calling process.

#include <windows.h>
DebugBreak();

ContinueDebugEvent

Continues a thread that previously reported a debugging event.

#include <windows.h>
BOOL result = ContinueDebugEvent(dwProcessId, dwThreadId, DBG_CONTINUE);

Sample Debugger Loop

#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    if (argc != 2) {
        printf("Usage: %s <pid>\n", argv[0]);
        return 1;
    }

    DWORD pid = (DWORD)atoi(argv[1]);
    if (!DebugActiveProcess(pid)) {
        printf("Failed to attach to process %lu (error %lu)\\n", pid, GetLastError());
        return 1;
    }

    DEBUG_EVENT dbgEvent;
    while (WaitForDebugEvent(&dbgEvent, INFINITE)) {
        printf("Debug event: %u from PID %lu\\n", dbgEvent.dwDebugEventCode, dbgEvent.dwProcessId);
        ContinueDebugEvent(dbgEvent.dwProcessId, dbgEvent.dwThreadId, DBG_CONTINUE);
    }

    return 0;
}