Saturday, April 16, 2016

Your software WILL crash.

When reporting on unhandled .NET exceptions, don't use the builtin Exception.StackTrace. Instead, construct an instance of System.Diagnostics.StackTrace with the exception object as the parameter, and generate your own trace. The difference is, with the latter, you can get offset to the crash point within the method.

The StackTrace contains an array of StackFrame objects. Each of those has the following methods:

  • GetILOffset() - offset to the crash/call within method's bytecode (MSIL) body
  • GetNativeOffset() - the same in JIT-compiled, native form
  • GetMethod() - returns System.Reflection.MethodBase, which can be used to reconstruct a human readable method prototype.
The IL offset can be resolved to sources using ILDASM.

The native offset can be resolved to sources using the debugger, as long as you're debugging precisely the same DLL as the one the crash happened on. Go to the Disassembly window.

Generating the method name in the same format as the builtin StackTrace provides is rather straightforward:


static public string MethodNameWithParameters(MethodBase mb)
{
    return mb.DeclaringType.FullName + "." +
        mb.Name + "(" +
        string.Join(", ",
            mb.GetParameters().Select(
                pi => pi.ToString())) + ")";
}


No comments:

Post a Comment