12
I'm currently implementing the last task for a little debug framework, namely HW Breakpoints. I referred to this article so far: http://www.codeproject.com/KB/debug/hardwarebreakpoint.aspx and a Book about writing a Debugger.
I got following two functions so far for setting a HW breakpoint:
void debuglib::breakpoints::hw_bp() {
HANDLE helper = 0;
CONTEXT co;
CURRENTCONTEXT(co);
helper = ::CreateThread(0,0,threadfunc,reinterpret_cast<void*>(co.Eip),0,0);
DWORD status = ::WaitForSingleObject(helper,INFINITE);
if (status != WAIT_OBJECT_0) {
::MessageBoxA(0, "Helper thread didn't exit cleanly", "HWBreakpoint", MB_OK);
}
::CloseHandle(helper);
}
static DWORD WINAPI debuglib::breakpoints::threadfunc(void* param) {
DWORD suspendcnt = ::SuspendThread(debuglib::process::thread());
if(suspendcnt) {
return 0;
}
CONTEXT co;
::ZeroMemory(&co,sizeof(co));
co.ContextFlags = CONTEXT_DEBUG_REGISTERS;
BOOL ok = ::GetThreadContext(debuglib::process::thread(),&co);
if(!ok) {
return 0;
}
DWORD freeDr = 0;
DWORD condition = debuglib::breakpoints::TRIGGER::CODE;
DWORD length = debuglib::breakpoints::SIZE::SIZE_1;
co.Dr0 = reinterpret_cast<DWORD>(param);
co.Dr7 = co.Dr7 | 1 << (freeDr*2);
co.Dr7 = co.Dr7 | condition << ((freeDr*4)+16);
co.Dr7 = co.Dr7 | length << ((freeDr*4)+18);
co.ContextFlags = CONTEXT_DEBUG_REGISTERS;
ok = ::SetThreadContext(debuglib::process::thread(), &co);
co.ContextFlags = CONTEXT_DEBUG_REGISTERS;
::GetThreadContext(debuglib::process::thread(),&co);
suspendcnt = ::ResumeThread(debuglib::process::thread());
if(suspendcnt == 0xFFFFFFFF) {
return 0;
}
return 1;
}