Month: May 2014

I’ve always found this algorithm interesting, ever since I saw it in action back in university. I think it was among the first recursive functions we ever went over, albeit not a simple one to grasp, which is probably the reason why they wanted to teach it to us. Typically, the algorithm to move disks for the Towers of Hanoi is as follows:

public void Calculate(int n, int fromPole, int toPole, int intermediaryPole)
{
if (n == 1)
{
Move(fromPole, toPole); // This is the only place that does the actual move.
}
else
{
Calculate(n - 1, fromPole, intermediaryPole, toPole); // The first Calculate call in the recursion serves to expose the bottom-most disk.
Calculate(1, fromPole, toPole, intermediaryPole); // The second call in the Calculate method serves to move the bottom-most disk to the desired pole.
Calculate(n - 1, intermediaryPole, toPole, fromPole); // The last Calculate call in the recursion does exactly the same thing as the last two calls in this recursion did, except it repeats this process for the disks remaining in the intermediary pole.
}
}

Assume you call it as follows:

Calculate(numberOfDisksOnTheFirstPole, 0, 2, 1);

The initial conditions are that you have all of the disks on the first pole. You have three poles, and you want to move all disks from pole 0 to 2 via pole 1 as an intermediary pole. Assume 4 disks in total, so that the tower looks like this (each column represents a pole, and the disks are numbered):

1--
2--
3--
4--

Calls then runs as follows (I like to show the flow of the the method through coalescing, recursive function calls because its visually much more understandable to me to project a recursive method this way, and this is a tool I use to trace through recursive methods in order to figure out how they work, and I suggest that you use the same tool to project recursive functions in order to analyze them for understandability for yourself):

So, if you’re like me, you love saving a little bit of cash. Am I right? There’s nothing wrong with saving a few pennies in order to purpose them towards better expenses. Let me share a little hack with you that seems to work quite well at the pumps.

Most pumps have a flow measurement system that translates the amount you pump into the amount you pay. Meaning, the harder you clutch that pump, the harder your pockets will hurt at the end of the day. Don’t let your wallet down, play a little game with the pump.

The game’s called “use your senses.” Your ears are a magical weapon. Use them to hear the flow of volume when you’re clutching the pump at maximum grip, and slowly lessen your grip while maintaining the same flow. Its honestly that simple, and you’ll reach an optimum between flow and grip pressure, where you pay as little as possible for the amount of fuel you pump out. These flow measurement systems are often not calibrated as often or as well as you might think, and gripping it at maximum means you’re paying the premium off the bat. Sometimes, a single pump at a specific gas station will be the weakest link. It can be both a fun and rewarding experience in finding it. Plus, it makes pumping a fun challenge. Why not enjoy playing a game while you’re at it? Also, consider that when you do pump fuel, pumping at maximum grip means pumping at maximum pressure. That may or may not be a good thing. Do you really think that at maximum pressure you’re getting only pure fuel out of the underground tank at your local gas station that’s been just sitting there for years? Have you ever tried reusing the same coffee mug to make a batch of coffee? It stains…there’s a deposit that takes place at the bottom of it. Its just unavoidable. What do you think happens to underground fuel tanks?

So, you want to trace the stack of C++ applications in Windows, you say? You’ve come to the right place…luckily for you the dbghelp library is what you’re probably after, and I’ll explain that API shortly (I’ve made a very minimalistic class for this exact purpose because it’s just a fantastic library to use in and of itself when debugging, especially if you have some sort of logging mechanisms in place in your code, be it for production or debugging). But before we get into that, you also have the option of using Windows Error Reporting and crash dumps to catch those nasty production crashes, and often times its much, MUCH easier to do that than to use extra WINAPI libraries for stack tracing. So I will begin with a short detour on Windows Error Reporting…

Windows Error Reporting

Windows Error Reporting in an integrated OS feature within Microsoft Windows that allows you to generate crash dumps whenever a crash happens on any application running on your system. Generated crash dumps are files that you can open in Visual Studio and use to hook the Visual Studio debugger into. If you’ve never done that, I suggest you try it out right away! The crashed state of your application is essentially snapshot-ed into the dump file, so you’ll see the exact thread that threw the exception and its associated error messages. In fact, you’ll even be able to see where all running threads are at. If you’ve never used the Threads view while debugging, you’re really missing out. Its available in the top menu of Visual Studio while you’re debugging: Debug -> Windows -> Threads. You can even generate crash dumps on the fly for most running processes on your system through Task Manager (CTRL+SHIFT+ESCAPE) -> Right click the process you want a dump of -> Generate dump file. Note: I may be wrong but I think you may need to also deploy your application’s .pdb files in order for WER to generate full-on dumps. However, to actually hook the debugger in from your dump, the version of your solution’s code needs to match the version of your binaries that generated the dump.

Tracing a Windows MSVC++ Project’s Stack C#-Style

So if you’re like me and you just got into C++ applications in Windows (MFC, MSVC++, Win32 Console, WINAPI stuff, etc) from a C# background, you’d be pretty upset to find out that tracing just got a whole lot worse. If you’re also like me and want a nice and minimalistic library to use in order to trace your code, please feel free to use my StackTracer.h and StackTracer.cpp files. You can modify these as you wish but the only thing I do ask is that you keep the comment in my StackTracer.h header with my name in it. Also, and as always, you must agree to assume all liability and responsibility when using any code I provide. The StackTracing header and implementation basically just use the dbghelp.lib library (part of the WINAPI) to call functions like CaptureStackBackTrace or StackWalk, which basically allow you to walk the stack. The stack is, well, as you’ve come to know from C#, a place where stack frames reside, frames which store all kinds of neat information like return addresses and other things which we use to walk backwards up the call stack in order to see what went wrong.

How to Properly Set Up StackTracer

Recommended: Download the latest Standalone Debugging Tools for Windows (WinDbg) from MSDN. Install it. Find where it installed dbghelp.lib on your system as well as the dbghelp.dll file. Copy dbghelp.lib into a directory your project includes for libraries, and copy dbghelp.dll into the location where you run your project from (like the bin directory or something).

You must include dbghelp.lib into your project’s Linker’s dependencies in order to make use of these APIs in your project (Project Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies and add dbghelp.lib).

In order for everything to work with stack tracing, the PDB files must be present. Please ensure that your project is set to output debug information and has its PDBs in the working directory. You may set this by right-clicking your project, navigating to Properties -> Configuration Properties -> Linker -> Debugging, and set Generate Debug Info to Yes (/DEBUG), also making sure to set GenerateProgramDatabaseFile right below it to your output directory (typically, this is $(OutDir)$(TargetName).pdb).

Once enabled, you might see partial stack traces. This is because the inline optimization is enabled, or because your method is explicitly marked as inline. You can disable this feature on your project, by right-clicking it and navigating to Properties -> Configuration Properties -> C++ -> Optimization -> Inline Function Expansion and setting it to Disabled (/Ob0). For inline methods, you should search your project for the inline keyword and remove these methods temporarily.

Also, if you ever need to print a complete stack trace from somewhere in your code, you may use the PrintStackTrace() method. This will help if you have multiple threads contending for the same method, and are trying to figure out why something of that nature isn’t working. Inline methods and the inline optimizations may also cause you to see partial stack traces with this method as well, so it is recommended that you disable it while testing.

Yes, it catches C++ exceptions as well as SEH exceptions and I’m willing to bet that it also catches MFC exceptions. I’ve seen it work magic on runtime and believe me, it caught everything I pitched it so far and I didn’t even start playing baseball with it.

Yes, as you can tell from my overloads, it supports Win32, x64, x86, Unicode, Multibyte, you name it.

If you’ve read this far and understood everything thus far, then just include StackTracer.h and StackTracer.cpp in your project and create a new instance of the StackTracer class.

A Note on Inline

So why take a quick detour? Because you should know this. The inline function optimization, in a nutshell: Assume its on in a particular C++ project, and say you have two methods in this project: Method A and Method B. Method A calls Method B. The inline optimization will try to optimize your binaries so that, essentially, the compiled code in Method B is directly copied into Method A. If this happens, when the stack trace is printed, you will only see a partial stack trace, so your trace will likely start from Method A, because it never loaded a stack frame for the call to Method B (oh yes, these are the intricacies of methods in Windows). You may wonder why you always get a complete stack trace in C# applications? Well, actually there wasn’t any support for inline methods in C# as far as I know until .NET 4.5…that’s REALLY fresh considering when I wrote this article, and I’m not sure how it handles exceptions thrown within an inline C# method…something for you to try.

StackTracer.h

#pragma once
/*
StackTracer - v1.0 by Alexandru Dima
By default, StackTracer enables WER (Windows Error Reporting) to create crash dumps. This can be toggled by setting ENABLE_WER_CRASH_DUMPS to TRUE or FALSE. What it does is it creates a registry
key that tells Windows Error Reporting to generate crash dumps whenever an application crashes. The location of the dumps depend on what account you run the application with. They can can be dumped
out at C:\Windows\System32\TRACE_DUMP_FOLDER_LOCATION for example if running under the LOCAL SYSTEM account in Windows, or the respective user account folder for your current user account, just as an
example. WER will then try dumping all application crashes on the current machine there, not just for the application you run this code on. These dumps (.dmp files) located at TRACE_DUMP_FOLDER_LOCATION
can be opened in Visual Studio and used, against matching code (meaning your binaries have to match your code), to debug into the crash location. Therefore, it is recommended that you perfectly
save the code used in a particular deployment.
You can set EXCEPTION_STACK_TRACING_ENABLED to TRUE if you wish to capture stack traces on unhandled exceptions, as they will go to the vectored exception handler and print out the stack for that
exception. By default this feature is enabled (TRUE). Once enabled, you might see partial stack traces. This is because the inline optimization is enabled, or because your method is explicitly marked
as inline. You can disable this feature on your project, by right-clicking it and navigating to Properties -> Configuration Properties -> C++ -> Optimization -> Inline Function Expansion and
setting it to Disabled (/Ob0). For inline methods, you should search your project for the inline keyword and remove these methods temporarily.
Also, if you ever need to print a complete stack trace from somewhere in your code, you may use the PrintStackTrace() method. This will help if you have multiple threads contending for the
same method, and are trying to figure out why something of that nature isn't working. Inline methods and the inline optimizations may also cause you to see partial stack traces with this
method as well, so it is recommended that you disable it while testing.
And as always, in order for everything to work with stack tracing, the PDB files must be present. Please ensure that your project is set to output debug information and has its PDBs in the
working directory. You may set this by right-clicking your project, navigating to Properties -> Configuration Properties -> Linker -> Debugging, and set Generate Debug Info to Yes (/DEBUG),
also making sure to set GenerateProgramDatabaseFile right below it to your output directory (typically, this is $(OutDir)$(TargetName).pdb).
Once enabled, StackTracer's methods output to the standard output. Note, you must include dbghelp.lib in the Linker's dependencies in order to make use of these API's in another project.
*/
#include <Windows.h>
#include <dbghelp.h>
#include <sstream>
#include <iostream>
// Enables or disables stack tracing.
#define ENABLE_WER_CRASH_DUMPS TRUE
// Enables or disables stack tracing.
#define EXCEPTION_STACK_TRACING_ENABLED TRUE
// Sets the maximum function name of all functions when doing stack tracing.
#define TRACE_MAX_FUNCTION_NAME_LENGTH 1024
// Sets the maximum number of stack frames to walk when calling PrintStackTrace().
#define TRACE_MAX_STACK_FRAMES 1024
// Determines wether or not to catch exceptions as part of the WINAPI stack tracing methods.
#define TRACE_LOG_ERRORS FALSE
// This setting tells Windows Error Reporting to dump crashes to C:\Windows\System32\TRACE_DUMP_FOLDER_LOCATION under Local System credentials (services)...once set, it tries to dump ALL application crashes.
#define TRACE_DUMP_FOLDER_LOCATION "CrashDumps"
// Sets the maximum number of dump files for your TRACE_DUMP_FOLDER_LOCATION. Once max'd out, it will roll over.
#define TRACE_DUMP_MAXIMUM_DUMP_FILES 100
// Sets the dump type to a mini-dump. Possible values are: 0 (Custom Dump), 1 (Mini Dump), or 2 (Full Dump).
#define TRACE_DUMP_TYPE 1
void PrintStackTrace();
class StackTracer
{
public:
StackTracer();
~StackTracer();
};