Stacktrace / Stackwalk用于当前进程和当前具有IDebug接口的线程

时间:2014-07-17 14:16:58

标签: windows debugging c++-cli stack-trace

我想使用IDebugXXX interfaces来获取local process中某些函数的堆栈跟踪(没有远程连接)。

使用此代码可以附加到当前进程,但当前线程的堆栈跟踪始终包含only one frame,如: ntdll!ZwGetContextThread+0x00000012

{
    IDebugClient* debugClient;
    IDebugControl4 *control4;

    ...

    int flags = DEBUG_ATTACH_NONINVASIVE | DEBUG_ATTACH_NONINVASIVE_NO_SUSPEND;
    debugClient->AttachProcess(0, myProcessId, flags);

    control4->SetExecutionStatus(DEBUG_STATUS_GO);


    ...

    // get the stack trace for the current thread
    control4->GetStackTrace(0, 0, 0, _stackFrames, ARRAYSIZE((_stackFrames)), &_uFramesFilled)

    // _uFramesFilled is always '1' for the current thread
}

修改 该应用程序是用C ++ / CLI编写的,其他线程的结果至少包含更多的帧。

2 个答案:

答案 0 :(得分:1)

这对我很有用:(注意:请检查这些API的返回代码)

我认为你缺少的是:“AttachFor进程”之后的“WaitForEvent”调用。

IDebugClient4 * debugClient;
IDebugControl4 * control4;
DEBUG_STACK_FRAME frames[10];
ULONG filled = 0;
ULONG pid = 7288;

DebugCreate( __uuidof(IDebugClient4), (void **)&debugClient );

debugClient->QueryInterface( __uuidof(IDebugControl4), (void**)&control4 );

debugClient->AttachProcess(0, pid, DEBUG_ATTACH_NONINVASIVE | DEBUG_ATTACH_NONINVASIVE_NO_SUSPEND);

control4->WaitForEvent(DEBUG_WAIT_DEFAULT, INFINITE);

control4->GetStackTrace(0, 0, 0, &frames[0], 10, &filled);

答案 1 :(得分:1)

assert中读取WinDDK示例后,我发现缺少堆栈跟踪必须从中开始的上下文。之后(并添加WaitForEvent(...))跟踪工作正常。

{
    ...

    // capture the context end convert it to debug '.crx' command
    char CxrCommand[64];
    CONTEXT myContext;
    ZeroMemory(&myContext, sizeof(CONTEXT));
    RtlCaptureContext(&myContext);
    sprintf_s(CxrCommand, 64, ".cxr 0x%p", &myContext);
    // capture the context end

    ...

    control4->WaitForEvent(DEBUG_WAIT_DEFAULT, INFINITE);

    //execute debugger command: ".cxr (Display Context Record)"
    control4->Execute(DEBUG_OUTCTL_IGNORE, CxrCommand, DEBUG_EXECUTE_NOT_LOGGED

    control4->GetStackTrace( .... )
}