【问题标题】:Escaping trapflag/single step转义陷阱标志/单步
【发布时间】:2014-09-05 20:11:34
【问题描述】:

我正在编写一个跟踪其他程序执行的程序。我正在使用动态指令检测来跟踪 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;
}

如您所见,我在函数末尾循环遍历所有线程,以确保单步异常将在每个线程中的每条下一条指令上触发。 然而,有时执行似乎“逃脱”了这个陷阱,通常在被下一个调试事件再次捕获之前执行数百万条指令。

我编写了另一个小应用程序来测试我的程序的行为:

int main(int argc, char* argv[])
{

    //__asm int 3h
    if (argc == 41234123)
    {
        printf("Got one\n");
    }

    return 0;
}

跟踪器的预期输出应该是:

0xDEADBEEF CMP 1 41234123

但是不知何故,跟踪器没有记录这个指令(表明没有引发调试事件,并且没有设置陷阱标志)。

谁能看看我在调试循环中是否做错了什么?或者测试程序的哪种行为(加载 dll)可能对此负责?

【问题讨论】:

  • 您确定编译器生成了CMP 指令,并为您期望的指令使用了编码?您在哪里打印您期望的输出的代码?
  • 是的,我用反汇编程序仔细检查了一遍,以确保确实有一条 CMP 指令,而不是 TEST 或其他指令。它就在那里,它会被执行,只是我的追踪器看不到它。

标签: c++ windows multithreading debugging


【解决方案1】:

问题与调用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);
    }
}

这样我可以重新获得控制权,因为当执行返回到受保护的页面时系统将触发 EXCEPTION_GUARD_PAGE。

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;
            }

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

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2015-01-20
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    相关资源
    最近更新 更多