How to obtain call stack programmatically in ATL and WTL (actually, ATL only)

While debugging, obtaining call stack at a certain [problematic] point of execution, such as especially deadlock condition or on assert, is an invaluable help. Debugger shows it, however it is possible to get the call stack programmatically and even more: having program database along with the executable it is even possible to resolve symbols and source code position. All this programmatically, without debugger running!

14-image001.png

The stack is taken using CDebugSymbols helper class, which walks through the stack frames and calls provided call back () for each frame:

// Take the call stack
m_sCallStack.Empty();
m_sCallStack.AppendFormat(_T(“Thread %d call stack:\r\n\r\n”), nThreadIdentifier);
CDebugSymbols::StackWalk(nThreadIdentifier, StackFrameProc, (INT_PTR) this);

static BOOL WINAPI StackFrameProc(CDebugSymbols* pDebugSymbols, INT_PTR nParameter, STACKFRAME64& StackFrame) throw()
{

Keywords: Debugging Tools and Symbols, Program Database (.pdb), StackWalk, StackWalk64, SymInitialize.

Visual C++.NET 2005 source code can be downloaded here, compiled binary – here.

Note 1: that compiled binary only would not show symbols as it required program database (.pdb file) which you need to create compiling the source code.

Note 2: the code is very likely to require certain amendment for 64-bit environment.

Leave a Reply