General Purpose Call Stack Tracer

Published October 22, 2002 by Bryan Ross, posted by Myopic Rhino
Do you see issues with this article? Let us know.
Advertisement
(Editor's Note: Source code for this article is currently not available)

[size="5"]Introduction

This is a short little snippet whose purpose is to aid in debugging, by keeping track of which function the thread of execution is currently in, using a staticly allocated doubly-linked list (for performance reasons).


[size="5"]Usage

To use, include CallStackTrace.h (this file) and CallStackTrace.cpp in your project. Then, ensure that in any source file that you'd like to trace the stack you put
[bquote][font="Courier New"][color="#000080"]#include "CallStackTrace.h"[/color][/font][/bquote]
near the top.

Then, to enable the stack tracing, at the top of the function (preferrably the first line of the function), put

[font="Courier New"] TRACE_ENTER_FN(functionName)[/font]

where functionName is (obviously) the name of the function being traced. Then, at the end of the function, put

[font="Courier New"]TRACE_LEAVE_FN()[/font]

The only function you shouldn't have to put that in is the [font="Courier New"]main()[/font] function. Note that no functionName is required.

If an error occurs, just call [font="Courier New"]CallStackTrace::Dump()[/font] to dump the current call stack (with file names and line numbers) to stdout. You can optionally pass a std::ostream to [font="Courier New"]CallStackTrace::Dump()[/font] to dump the stack trace to a file or other ostream derived object.


[size="5"]Catching Unhandled Exceptions

To report the call stack when an unhandled exception is thrown, structure your [font="Courier New"]main()[/font] function like the following:

main()
{
try
{
run program here
}

catch(...)
{
cout << "Unhandled Exception!" << endl;
CallStackTrace::Dump();
}
}

[size="5"]Handling "Expected" Exceptions

"But wait!" you say. "What if I handle an exception in a [font="Courier New"]catch()[/font] block? Well, in that case, just make the first line of your catch block the [font="Courier New"]TRACE_UNWIND()[/font] macro (no function name needed, as long as it has a [font="Courier New"]TRACE_ENTER_FN(functionName)[/font] at the top of the function). That will unwind the Call Stack Trace, and allow normal functioning from that point forward.
Cancel Save
0 Likes 0 Comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!

This is a short little snippet whose purpose is to aid in debugging, by keeping track of which function the thread of execution is currently in, using a staticly allocated doubly-linked list

Advertisement
Advertisement
Advertisement