无效的句柄窗口调试器

时间:2018-05-28 17:42:07

标签: c++ debugging winapi

我在Windows上使用简单的调试器。 当我试图获取我需要的线程的上下文时,GetLastError返回错误代码6,这意味着线程的句柄是invaild,但我不知道为什么。

Dbg标题

class PDbg
{
public:
    PDbg() = default;
    ~PDbg();
    bool StartDebugActiveProcess(DWORD processId);
    bool StartDebugNewProcess(LPTSTR processName);
    bool AddBreakpoint(LPVOID address, HANDLE hProecss, PBreakpointHandler pbreakpoint_handler = NULL);
    bool RemoveBreakpoint(LPVOID address, HANDLE hProcess);
    bool SetThreadTrapFlag(DWORD threadId);
    bool Shutdown();

private:
    DWORD _startupProcessId;
    LPVOID _image_base; 
    DWORD _image_size;
    std::map<DWORD, HANDLE> _processes; //handle all processes
    std::map<DWORD, HANDLE> _threads; // handle all threads
    std::map<LPVOID, PBreakpoint> _breakpoints; // handle all breakpoints
    std::map<DWORD, LPVOID> _pending_breakpoints; // handle breakpoints to recreate

    void run();
    void handle_create_process_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_create_thread_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_exception_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_load_dll_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_unload_dll_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_output_debug_string(DEBUG_EVENT* dbgEvent);
    void handle_exit_thread_debug_event(DEBUG_EVENT* dbgEvent);
    void handle_exit_process_debug_event(DEBUG_EVENT* dbgEvent);
};

CreateProcess方法,这里我得到了线程的句柄。

void PDbg::handle_create_process_debug_event(DEBUG_EVENT * dbgEvent)
{
    printf("Event: Create process, PID: %u, Base address: %p, Start address: %p\n",
        dbgEvent->dwProcessId, dbgEvent->u.CreateProcessInfo.lpBaseOfImage, dbgEvent->u.CreateProcessInfo.lpStartAddress);

    if (dbgEvent->u.CreateProcessInfo.hFile != NULL)
    {
        CloseHandle(dbgEvent->u.CreateProcessInfo.hFile);
    }

    this->_processes[dbgEvent->dwProcessId] = dbgEvent->u.CreateProcessInfo.hProcess;
    this->_threads[dbgEvent->dwThreadId] = dbgEvent->u.CreateThread.hThread;

}

SetTreadContext方法,我尝试更改线程的上下文

bool PDbg::SetThreadTrapFlag(DWORD threadId)
{
    const unsigned int k86trapflag = (1 << 8);
    CONTEXT ctx;
    memset(&ctx, 0, sizeof(ctx));

    ctx.ContextFlags = CONTEXT_CONTROL;

    auto x = this->_threads;
    if (!GetThreadContext(this->_threads[threadId], &ctx))
    {
        std::cout << "Cannot get thread context. Error:" << GetLastError() << std::endl;

        return FALSE;
    }

    ctx.EFlags |= k86trapflag;

    if (!SetThreadContext(this->_threads[threadId], &ctx))
    {
        std::cout << "Cannot set thread context." << std::endl;

        return FALSE;
    }

    return TRUE;
}

我调用SetTrhreadContext的方法并不重要。我确定并且我检查了threadId我在线程(DWORD,HANDLE)映射中传递给SetTreadContext EXISTS。是什么原因造成了这个问题?

0 个答案:

没有答案