3

I am trying to utilize GetThreadContext to view what the current debug registers are set to. No matter what program I debug, it returns 0xCCCCCCCC. I am able to successfully set breakpoints ctx.Dr0 and then catch these breaks with a custom exception handler, but if I try to view the address stored at ctx.Dr0, it always appears as 0xCCCCCCCC. Why is that?

Thanks

    CONTEXT ctx;
    GetThreadContext(GetCurrentThread(),&ctx);
    cout << hex << ctx.Eip << endl;

EDIT**

I think I did not ask my question well enough, because at the time I did not realize the error in my thinking. I actually was trying to call GetThreadContext from within the thread which I wanted to get it's context. This doesn't work for obvious reasons. Instead I think CONTEXT ctx = {CONTEXT_FULL} works. The answer that was most helpful was Hans Passant comment below.

SullX
  • 214
  • 4
  • 17
  • 6
    That's what happens when you don't check the return value of winapi functions for an error, you just don't know why it doesn't work. – Hans Passant Aug 12 '13 at 20:32
  • [0xCCCCCCCC is uninitialized memory](http://stackoverflow.com/q/370195/995714) – phuclv May 06 '18 at 16:31

2 Answers2

11

You cannot get a valid context for a running thread. You need to suspend the thread you want to get the context for. So, trying to do it in a current thread is not going to work. This is clearly stated in the GetThreadContext() documentation:

You cannot get a valid context for a running thread. Use the SuspendThread function to suspend the thread before calling GetThreadContext.

If you call GetThreadContext for the current thread, the function returns successfully; however, the context returned is not valid.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
lapk
  • 3,838
  • 1
  • 23
  • 28
3

On 64-bit platforms you can use RtlCaptureContext. This isn't however available to 32-bit platforms, so there you need a different solution. A possible approach is to use assembly as described in this blog post Walking the stack of the current thread.

CONTEXT Context;
ZeroMemory( &Context, sizeof( CONTEXT ) );
Context.ContextFlags = CONTEXT_CONTROL;

__asm
{
Label:
  mov [Context.Ebp], ebp;
  mov [Context.Esp], esp;
  mov eax, [Label];
  mov [Context.Eip], eax;
}
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91