DebugActiveProcessStop崩溃正在调试的应用程序

时间:2015-10-20 10:55:15

标签: c++ c debugging

我有一个附加到应用程序的调试器。

在我完成获取所需信息后,我尝试分离调试器,但正在调试的应用程序在DebugActiveProcessStop()上崩溃:

int main(void)
{
    HWND window = FindWindow(NULL, L"apptodebug");

    DWORD_PTR pid = 0;
    GetWindowThreadProcessId(window, &pid);

    DWORD address = 0x004F0186; // address of the instruction after the call

    DebugActiveProcess(pid); // PID of target process

    DWORD dwThreadID = GetWindowThreadProcessId(window, &pid);

    CONTEXT ctx = {0};
    ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS | CONTEXT_INTEGER;
    ctx.Dr0 = address;
    ctx.Dr7 = 0x00000001;

    HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, dwThreadID);

    SetThreadContext(hThread, &ctx); // hThread with enough permissions

    DEBUG_EVENT dbgEvent;

    DWORD edx = 0;
    DWORD ecx = 0;
    int gg = 0;

    while (!gg)
    {
        if (WaitForDebugEvent(&dbgEvent, INFINITE) == 0)
            break;

        if (dbgEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
            dbgEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
        {
            if (dbgEvent.u.Exception.ExceptionRecord.ExceptionAddress == (LPVOID)address)
            {
                GetThreadContext(hThread, &ctx);

                edx = ctx.Edx; // edx get
                ecx = ctx.Ecx; // edx get

                std::cout<<edx<<"\n";
                std::cout<<ecx<<"\n";

                //system("pause");

                gg = 1;
            }
        }

        ContinueDebugEvent(dbgEvent.dwProcessId, dbgEvent.dwThreadId, DBG_CONTINUE);
    }

    DebugActiveProcessStop(pid); // The application I was debugging crashes here.
    DebugSetProcessKillOnExit(false);

    return 0;
}

我无法找到一种方法来分离调试器&#34;通常&#34;。该应用程序简单地停止工作&#34;并关闭。

1 个答案:

答案 0 :(得分:2)

您正在为流程注入断点。当遇到断点时,这将导致异常。如果在断点处于活动状态时分离调试器,则此类异常将导致程序崩溃。

因此,首先禁用断点(将DR7设置为0),然后分离。

我自己从未这样做,但是像

那样
setSelectedButton()

应该这样做。