How can I get a stacktrace from C++ in WinRT?

2020-06-03 08:39发布

问题:

I need to get a stacktrace from a C++ application, and serialize it into a string so it can be parsed later. The only API I've heard of for this on Windows is StackWalk64, which doesn't appear to be supported.

How can I get a stacktrace from C++ in a Windows Store app?

回答1:

The only way I have been able to debug complex WINRT issues is to use ETW to track causality chains. While kind of tedious to setup This article (while referring to c#) highlights the method:

  • Andrew Stasyuk. Async Causality Chain Tracking

Here are a couple of decent introduction to ETW for C/C++.

  • Event Tracing for Windows chapter in MSDN article by Dr. Insung Park and Ricky Buch "Improve Debugging And Performance Tuning With ETW"
  • SO question How to use ETW from a C++ windows client

Using this method you should be able to create ETW events then listen for them in the app and include them as a serialized string for analysis later.



回答2:

What worked for me is asm code as below. This only works on x86 platform, so it is usefull only during debugging on emulator. Returned frame pointers can be used in dissassembly window to jump into source code. I think it should be possible to use map file to get exact source code location.

I use this code to find memory leaks, combined with crtdbg it works very well in very large application with lots of allocations. VS 2013 memory profiler could handle at most 1 minute of data recording.

  FINLINE static DWORD GetCallerFrameNum(int index) {
#if defined(_DEBUG) && defined(_MSC_VER) && defined(_M_IX86)

    DWORD caller = 0;
    __asm
    {
      mov ebx, ebp
        mov ecx, index
        inc ecx
        xor eax, eax
      StackTrace_getCaller_next :
      mov eax, [ebx + 4]
        mov ebx, [ebx]
        dec ecx
        jnz StackTrace_getCaller_next
        mov caller, eax
    }
    return caller;

#else

    return 0;

#endif
  }

  template<class T>
  void RecordStackTrace(T& vecOut) {
    vecOut.clear();
    vecOut.reserve(32);
    for (INT iInitLevel = 1; iInitLevel < 32; ++iInitLevel) {
      DWORD dwFrameNum = GetCallerFrameNum(iInitLevel);
      if (!dwFrameNum)
        return;
      vecOut.push_back(dwFrameNum);
    }
  }