C++ 逃逸陷阱/单步

C++ 逃逸陷阱/单步,c++,windows,multithreading,debugging,C++,Windows,Multithreading,Debugging,我正在写一个程序来跟踪其他程序的执行情况。我使用动态指令检测跟踪x86的CMP指令的行为 我正在使用windows调试api来控制已调试程序的行为。我使用“仅调试此进程”标志启动程序,然后在主线程上设置陷阱标志 然后进入主调试循环: bool cDebugger::ProcessNextDebugEvent(bool Verbose) { bool Result = true; DEBUG_EVENT Event = { 0 }; DWORD Status = DBG_

我正在写一个程序来跟踪其他程序的执行情况。我使用动态指令检测跟踪x86的CMP指令的行为

我正在使用windows调试api来控制已调试程序的行为。我使用“仅调试此进程”标志启动程序,然后在主线程上设置陷阱标志

然后进入主调试循环:

bool cDebugger::ProcessNextDebugEvent(bool Verbose)
{
    bool Result = true;
    DEBUG_EVENT Event = { 0 };

    DWORD Status = DBG_CONTINUE;

    if (!WaitForDebugEvent(&Event, INFINITE))
    {
        _Reporter("Error: WaitForDebugEvent: " + to_string(GetLastError()));
        return Result;
    }
    else
    {
        if (Event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Created process: " + GetFilenameFromHandle(Event.u.CreateProcessInfo.hFile));
        }
        else if (Event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Dll: " + GetFilenameFromHandle(Event.u.LoadDll.hFile) + " loaded at: " + to_string((unsigned int)Event.u.LoadDll.lpBaseOfDll));

            _Dlls.insert(make_pair((unsigned int)Event.u.LoadDll.lpBaseOfDll, GetFilenameFromHandle(Event.u.LoadDll.hFile)));
        }
        else if (Event.dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Thread[" + to_string(Event.dwThreadId) + "] created at: " + to_string((unsigned int)Event.u.CreateThread.lpStartAddress));

            _Threads.push_back(Event.dwThreadId);
        }
        else if (Event.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Thread[" + to_string(Event.dwThreadId) + "] exited with: " + to_string(Event.u.ExitThread.dwExitCode));

            auto It = std::find(_Threads.begin(), _Threads.end(), Event.dwThreadId);

            if (It != _Threads.end())
                _Threads.erase(It);
        }
        else if (Event.dwDebugEventCode == UNLOAD_DLL_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Dll " + _Dlls[(unsigned int)Event.u.UnloadDll.lpBaseOfDll] + " unloaded at : " + to_string((unsigned int)Event.u.UnloadDll.lpBaseOfDll));
        }
        else if (Event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
        {
            if (Verbose)
                _Reporter("Process exited with: " + to_string(Event.u.ExitProcess.dwExitCode));

            Result = false;

            _Threads.clear();
        }
        else if (Event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
        {
            if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
            {
                Status = DBG_EXCEPTION_HANDLED;
            }
            else
            {
                Status = DBG_EXCEPTION_NOT_HANDLED;
            }
        }

        for (size_t i = 0; i < _Threads.size(); i++)
        {
            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, _Threads[i]);

            if (hThread == NULL)
            {
                _Reporter("Error: Failed to open thread: " + to_string(GetLastError()));
            }
            else
            {
                CONTEXT ThreadContext = GetThreadContext(hThread);

                ProcessStep(ThreadContext, hThread);

                ThreadContext.EFlags |= 0x100; // Set trap flag.
                SetThreadContext(hThread, ThreadContext);

                CloseHandle(hThread);
            }
        }

        if (!ContinueDebugEvent(Event.dwProcessId, Event.dwThreadId, Status))
        {
            _Reporter("Error: ContinueDebugEvent: " + to_string(GetLastError()));
        }
    }

    return Result;
}
跟踪器的预期输出应为:

0xDEADBEEF CMP 1 41234123
但是,跟踪程序不知何故没有记录此指令(表示未引发调试事件,并且未设置陷阱标志)


有人能看到我在调试循环中是否做错了什么吗?或者测试程序的哪种行为(加载dll)会导致这种情况?

这个问题与调用windows API时代码进入内核空间有关。我的解决方案是将测试程序可执行部分的页面保护设置为page_GUARD:

    SYSTEM_INFO Info;
    GetSystemInfo(&Info);

    DWORD StartAddress = (DWORD)Info.lpMinimumApplicationAddress;
    DWORD StopAddress = (DWORD)Info.lpMaximumApplicationAddress;
    DWORD PageSize = 0;

    PageSize = Info.dwPageSize;

    _Sections.clear();

    for (DWORD AddressPointer = StartAddress; AddressPointer < StopAddress; AddressPointer += PageSize)
    {
        MEMORY_BASIC_INFORMATION Buffer;
        VirtualQueryEx(_Process.GetHandle(), (LPCVOID)AddressPointer, &Buffer, sizeof(Buffer));

        if (CheckBit(Buffer.Protect, 4) || CheckBit(Buffer.Protect, 5) || CheckBit(Buffer.Protect, 6) || CheckBit(Buffer.Protect, 7))
        {
            if (Buffer.State == MEM_COMMIT)
            {
                _Sections.push_back(make_pair((unsigned int)Buffer.BaseAddress, (unsigned int)Buffer.RegionSize));
                AddressPointer = (unsigned int)Buffer.BaseAddress + (unsigned int)Buffer.RegionSize;
            }
        }
    }


void cDebugger::SetPageGuard()
{
    for (size_t i = 0; i < _Sections.size(); i++)
    {
        DWORD Dummy;
        VirtualProtectEx(_Process.GetHandle(), (LPVOID)_Sections[i].first, _Sections[i].second, PAGE_GUARD | PAGE_EXECUTE_READWRITE, &Dummy);
    }
}

这个解决方案并不完美。在某些情况下,执行仍然可能逃脱“陷阱”。但是它解决了我最直接的问题(能够在我的测试程序中看到比较)。

你确定编译器生成了
CMP
指令,并对你期望的指令使用了编码吗?你的代码在哪里打印你想要的输出?是的,我用反汇编程序仔细检查了一遍,以确保实际上有一条CMP指令,而不是测试或其他什么。它就在那里,它被执行了,只是我的追踪者没有看到它。
    SYSTEM_INFO Info;
    GetSystemInfo(&Info);

    DWORD StartAddress = (DWORD)Info.lpMinimumApplicationAddress;
    DWORD StopAddress = (DWORD)Info.lpMaximumApplicationAddress;
    DWORD PageSize = 0;

    PageSize = Info.dwPageSize;

    _Sections.clear();

    for (DWORD AddressPointer = StartAddress; AddressPointer < StopAddress; AddressPointer += PageSize)
    {
        MEMORY_BASIC_INFORMATION Buffer;
        VirtualQueryEx(_Process.GetHandle(), (LPCVOID)AddressPointer, &Buffer, sizeof(Buffer));

        if (CheckBit(Buffer.Protect, 4) || CheckBit(Buffer.Protect, 5) || CheckBit(Buffer.Protect, 6) || CheckBit(Buffer.Protect, 7))
        {
            if (Buffer.State == MEM_COMMIT)
            {
                _Sections.push_back(make_pair((unsigned int)Buffer.BaseAddress, (unsigned int)Buffer.RegionSize));
                AddressPointer = (unsigned int)Buffer.BaseAddress + (unsigned int)Buffer.RegionSize;
            }
        }
    }


void cDebugger::SetPageGuard()
{
    for (size_t i = 0; i < _Sections.size(); i++)
    {
        DWORD Dummy;
        VirtualProtectEx(_Process.GetHandle(), (LPVOID)_Sections[i].first, _Sections[i].second, PAGE_GUARD | PAGE_EXECUTE_READWRITE, &Dummy);
    }
}
if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
            {
                Status = DBG_CONTINUE;
                if (!_Tracing)
                {
                    HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, Event.dwThreadId);
                    CONTEXT ThreadContext = GetThreadContext(hThread);

                    if (ThreadContext.Eip == _EntryAddress)
                    {
                        ClearHardwareBreakpoint(0, hThread);
                        _Tracing = true;
                    }

                    CloseHandle(hThread);
                }

                SetPageGuard();

                _Guarded = true;
            }
            else if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
            {
                Status = DBG_CONTINUE;
            }
            else if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_GUARD_PAGE)
            {
                Status = DBG_CONTINUE;   // fires when processor lands on guarded pages
            }
            else
            {
                Status = DBG_EXCEPTION_NOT_HANDLED;
            }