How to Log Stack Frames with Windows x64

放肆的年华 提交于 2019-11-28 03:29:33

I finally found a reliable way to log the stack frames in x64, using the Windows function CaptureStackBackTrace(). As i did not want to update my SDK, i call it via GetProcAddress(LoadLibrary());

   typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);
   CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary("kernel32.dll"), "RtlCaptureStackBackTrace"));

   if(func == NULL)
       return; // WOE 29.SEP.2010

   // Quote from Microsoft Documentation:
   // ## Windows Server 2003 and Windows XP:  
   // ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63.
   const int kMaxCallers = 62; 

   void* callers[kMaxCallers];
   int count = (func)(0, kMaxCallers, callers, NULL);
   for(i = 0; i < count; i++)
      printf(TraceFile, "*** %d called from %016I64LX\n", i, callers[i]);

This works without problems.

We use minidumps exclusively here. You can generate a stripped down one that just includes stack information and dump out a stack trace from a decent debugger later.

It doesn't solve your problem directly, but I think it will provide you a much better postmortem reporting mechanism.

In Trial 3, you may be using CaptureStackBackTrace() incorrectly. According to the documentation, on Windows XP and Windows Server 2003, the sum of the first and second parameters must be less than 63, but, in your case, the sum would be 128.

http://msdn.microsoft.com/en-us/library/windows/desktop/bb204633%28v=vs.85%29.aspx

For vs2008 x64: Based on https://msdn.microsoft.com/en-us/library/windows/desktop/bb204633%28v=vs.85%29.aspx and RED SOFT ADAIR:

#if defined DEBUG_SAMPLES_MANAGEMENT  

#include "DbgHelp.h"
#include <WinBase.h>
#pragma comment(lib, "Dbghelp.lib")

void printStack( void* sample_address, std::fstream& out )
{
    typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);
    CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary(L"kernel32.dll"), "RtlCaptureStackBackTrace"));

    if(func == NULL)
        return; // WOE 29.SEP.2010

    // Quote from Microsoft Documentation:
    // ## Windows Server 2003 and Windows XP:  
    // ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63.
    const int kMaxCallers = 62; 

    void         * callers_stack[ kMaxCallers ];
    unsigned short frames;
    SYMBOL_INFO  * symbol;
    HANDLE         process;
    process = GetCurrentProcess();
    SymInitialize( process, NULL, TRUE );
    frames               = (func)( 0, kMaxCallers, callers_stack, NULL );
    symbol               = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );
    symbol->MaxNameLen   = 255;
    symbol->SizeOfStruct = sizeof( SYMBOL_INFO );

    out << "(" << sample_address << "): " << std::endl;
    const unsigned short  MAX_CALLERS_SHOWN = 6;
    frames = frames < MAX_CALLERS_SHOWN? frames : MAX_CALLERS_SHOWN;
    for( unsigned int i = 0;  i < frames;  i++ )
    {
        SymFromAddr( process, ( DWORD64 )( callers_stack[ i ] ), 0, symbol );
        out << "*** " << i << ": " << callers_stack[i] << " " << symbol->Name << " - 0x" << symbol->Address << std::endl;
    }

    free( symbol );
}
#endif

Called here:

#if defined DEBUG_SAMPLES_MANAGEMENT
        if(owner_ != 0)
        {   
            std::fstream& out = owner_->get_debug_file();
            printStack( this, out );   
        }
#endif

Watch this, I do not know if it is relevant:
...
Working with Assembly Code Assembly code is straightforward to port to AMD64 and 64-bit Windows—and is worth the effort for performance reasons! For example, you can take advantage of the new 64-bit general-purpose registers (r8-r15), and new floating point and 128-bit SSE/SSE2/floating point registers (xmm8-xmm15). However, there are new 64-bit stack frames and calling conventions you should learn about in the ABI (application binary interface) specifications.
...

The trick is to stop calling StackWalk64 when it returns 0 in stk.AddrReturn.Offset. This means there are no more frames on the stack. If stk.AddrReturn.Offset is non-zero, you can use that value as the return address.

If you continue calling StackWalk64 after this, my guess is that it will try to interpret whatever is in the memory locations as being a stack and will return unpredictable data.

StackWalk64 is the right choice, the first call will give you the caller's address.

Your problem might be that in release you have a lot of inlining going on. The return address may not be what you expect.

edit : you only need to set AddrPC and AddrFrame. Just make sure that your rbp and rip are the ones corresponding to your callee context.

Regarding the first issue: disable "Omit stack frames" in thre release version, and the "trivial" stack tracing code will work.

Regarding RtlCaptureStackBackTrace, one thing I've noticed on 32-bit Windows is that it fails if you pass too large a number into it for FramesToCapture. Experimentally I've identified 61 as the maximum value, for no reason that I can fathom!

Not sure if it's the same in x64, but that might explain why you're getting no info out.

Disassembling RtlCaptureStackBackTrace() I noticed that maximum value passed to RtlCaptureStackBackTrace() should be: framesToSkip+framesToCapture+1 should be less than 64. otherwise it returns 0 and there is no other error codes.

When using StackWalk64 you are iterating through the thread's entire stack whether there is valid data or not. Once you hit a return address of 0 you should terminate the walk, like so:

for (ULONG Frame = 0; ; Frame++)
{
  if (FALSE == StackWalk64(...))
  {
    printf("Stack walk failed!\n");
    break;
  }  

  if (stackFrame.AddrPC.Offset == 0)
  {
    printf("Stack walk complete!\n");
    break;
  }

  do_something();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!