Troubleshooting Exceptions Module Overview

Exceptions Managed Exceptions Unhandled Exceptions (UhE) Corrupted State Exceptions (CSE) Just In Time (JIT) Debugging Debugging Managed Exceptions

2 Exceptions

Unexpected behavior (for example, an error) encountered by an executing program Managed exception inherits from System.Exception - Contains properties that describe and provide more info about the exception - All managed languages use the same exception-handling system

3 Exception Hierarchy

SystemException - Base class for all exceptions thrown by Application's and the Common Language Runtime - Types • System.Runtime.InteropServices.ComException • System.OutOfMemoryException • System.NullReferenceException • Many more… ApplicationException - .NET 1.1 - Design pattern, not used anymore

4 COM Interop Exception

The runtime tries to map the HRESULT from COM interop to .NET exceptions. eg: E_ACCESSDENIED becomes UnauthorizedAccessException E_OUTOFMEMORY becomes OutOfMemoryException If this does not work Throws COMException If HRESULT that does not map to a managed exception (eg. a custom HRESULT) IErrorInfo is used to gather more detailed information

5 How Runtime Manages Exceptions

The runtime creates an exception information table for each executable. Each method of the executable has an associated array of information in this table. Each exception information table entry describes a protected block of code, any exception filters associated with that code, any exception handlers (catch statements). no performance penalty when an exception does not occur. You use resources only when an exception occurs. Four types of exception handlers for protected blocks: A finally handler that executes whenever the block exits, whether that occurs by normal control flow or by an unhandled exception. A fault handler that has to execute if an exception occurs but does not execute on completion of normal control flow. A type-filtered handler that handles any exception of a specified class or any of its derived classes. A user-filtered handler that runs user-specified code to determine whether the exception should be handled by the associated handler or should be passed to the next protected block (VB.NET)

6 How Runtime Manages Exceptions

When an exception occurs: - The runtime creates an Exception object. - If a debugger is attached, the debugger is notified of the exception (first chance). - If no debugger is attached - or if a debugger is attached but ignores the exception - the runtime searches for an array for the protected block that: • Includes the currently executing instruction; and • Contains an exception handler that can handle the current exception.

7 How Runtime Manages Exceptions cont.

If the runtime finds a handler in the current method: - The runtime populates an Exception object that describes the exception and executes all finally statements or exception handlers between the statement where the exception occurred and the statement handling the exception. If no handler is found in the current method: - Search the “caller” of the method and continue your way up the call stack. If no handlers are found even in the callers: - If a debugger is attached, the debugger gets the second chance notification. - If a debugger is not attached, or the debugger does not handle, the runtime raises an UnhandledException event.

8 Exception Handling Model

Build an Exception Information Table for each executable Unhandled Exception event

Exception Occurs Notify Debugger 2nd Chance

Populate Exception Object Create an Execute Finally blocks Exception Object. yes Terminate !

Notify Debugger Beginning of no 1st Chance call stack? Search for an entry for the caller of the current method no Search for an entry for the in the call stack current method in the table to Handler handle the exception found?

Populate Exception Object yes Execute Finally blocks Resume Execution 9 Coding to Handle Managed Exceptions

Coding blocks - Try - Catch - Finally - Filters (VB.NET only) Implement exception-handling code appropriate for associated code blocks Handle most specific types first, then the more general types Minimum combo of statements - Try-Catch - Try-Finally AVOID empty catch blocks

10 # Using and Exceptions

Used to clean up resources that require disposal (IDisposable interface).

using (StreamReader reader = new StreamReader(@"C:\test.txt")) { string line = reader.ReadLine(); }

IL Code IL_0000: ldstr "C:\\test.txt" IL_0005: newobj instance void [mscorlib]System.IO.StreamReader::.ctor(string) … .try { … IL_000c: callvirt instance string [mscorlib]System.IO.TextReader::ReadLine() } // end .try finally { … IL_0018: callvirt instance void [mscorlib]System.IDisposable::Dispose() …. } // end handler 11 Demo: Exception Objects

Sxe clr !dumpheap –type Exception !ehinfo Corrupted State Exceptions (CSE)

Introduced in .Net 4.0 Corrupted State Exceptions are a symptom of the corrupted process, not the cause - Raised after the process has been corrupted By the time the OS gives you notification you don’t know what’s gone wrong & for how long People write managed code that swallows these exceptions all the time!

try { CreateNamedPipe(MyBadPointer, 0, ..0, 0, new System.IntPtr(0)); } catch (Exception ex){ //Exception handling code… }

13 Corrupted State Exceptions (CSE)

Corrupted State Exceptions - STATUS_ACCESS_VIOLATION • presented as System.AccessViolationException - STATUS_STACK_OVERFLOW - EXCEPTION_ILLEGAL_INSTRUCTION - EXCEPTION_IN_PAGE_ERROR - EXCEPTION_INVALID_DISPOSITION - EXCEPTION_NONCONTINUABLE_EXCEPTION - EXCEPTION_PRIV_INSTRUCTION - STATUS_UNWIND_CONSOLIDATE Exception will be marked as “corrupted” COM will no longer convert a CSE to an HRESULT

14 Corrupted State Exceptions (Cont.)

.NET 4.0 marks CSE exceptions internally and will not allow them to be caught .NET 4.0 will not catch CSEs inside of runtime or swallow them - TargetInvocation and TypeInitialization will inherit corrupted exception state: • Eg: When CSE happens during TypeInitialization, a TypeInitializationException will be created with CSE as the inner exception and instance will be marked as corrupted (we can’t trust the state of the object). - COM will no longer convert CSEs to HRESULTS • Non-CSEs will still be converted into HRESULTS To handle CSE, you have to use: - [HandleProcessCorruptedStateExceptions] attribute • code must be SecurityCritical & not sandboxed - • Process-wide switch to mimic .NET 3.5 or older behavior

15 Exception Policies

Behavior of runtime in case of Exceptions can be controlled with CLR Policy: - Requires to host runtime - Eg: in case of stack overflow unload AppDomain instead of terminating Application

hr = pPolicyManager->SetActionOnFailure(EClrFailure::FAIL_StackOverflow, EPolicyAction::eRudeUnloadAppDomain);

- Eg: Change to Rude Abort (no finally) in case of a Thread Abort

hr = pPolicyManager->SetDefaultAction(EClrOperation::OPR_ThreadAbort, EPolicyAction::eRudeAbortThread);

16 Unhandled Exceptions (UhE)

Occurs when an exception is thrown and no catch filter accepts the exception object Set up UnhandledExceptionEventHandler - Delegate which is triggered by an unhandled exception In .NET 4.0, the following will terminate a process - StackOverflowException - Corrupted State Exceptions

17 Unhandled Exceptions (UhE)

What happens if unhandled Exception occurs on what kind of thread? .NET Version Unmanaged Main Finalizer Worker Threadpool 1.1 Process Process Thread Thread Thread Term. Term. Term. Term. Term.

2.0 / 4.0 Process Process Process Process Process Term. Term. Term. Term. Term.

2.0 / 4.0 + Process Process Thread Thread Thread Term.

18 Just In Time (JIT) Debugging .NET 4.X

JIT debugging for native and managed code configured in registry HKEY_LOCAL_MACHINE\Software\\Windows NT\Current Version\AeDebug During 2nd chance exceptions

Auto (REG_SZ) 0 – The system displays a message box notifying the user when an application error occurs.

Auto (REG_SZ) 1 – Starts automatically debugging Debugger Name of debugger and switch settings (REG_SZ) -p Stores the Process ID specified by %ld -e Stores the Events ID specified by %ld eg: cdb -pv -p %ld -c ".dump /u /ma c:\crashdump.dmp;.kill;qd"

UserDebuggerHot Specifies the key that, when pressed, establishes Key (DWORD) a breakpoint in code being debugged.

19 Exceptions and WinRT up from .NET 4.5.1

Better exception support for Windows Runtime components - Up from Windows 8.1 and .NET 4.5.1 - preserve information about the error that caused the exception, even across language boundaries

20 Perfmon Counters

.NET CLR Exceptions ASP.NET version # of Exceps Thrown Application Restarts # Exceps Thrown/sec Worker Process Restarts Memory Available MBytes

21 Debugging Managed Exceptions

Managed debuggers - Visual Studio 2008..2013 • Break if CLR exceptions are thrown

• Supports Full and Mini Dumps up from .NET 4.0

22 Managed debuggers - IntelliTrace

“Historical” Debugging facility Included with Ultimate Edition Cmd line tool “IntelliTrace.exe” Options - Exceptions and other Events only - Events and call information (can build custom) Limitations - Managed code only - 64-bit support launched from Visual Studio 2010 up from sp1 - Edit and continue is disabled

23 Gather Dumps on unhandled Exceptions

ProcDump Debug Diag Intellitrace Windows Error Reporting

24 Demo: WER, Procdump Native Debuggers

Windbg / cdb Pros - Debuggers of choice in production • Automated • Can be noninvasive Cons - Cannot see the true managed exception - During live debug, must suspend entire process – not just managed threads

26 Debugging Exceptions .NET

Common debugger cmd(s) Tell the debugger to break on CLR exception - sxe clr Get the native call stack - k Review the Exception Type - !PrintException Get the managed callstack - !clrstack Get All exceptions in the heap use: - !dumpheap –type Exception, !PrintException - !psscor4.dae,!psscor2.dae New in 4.0! CLR exception code changed

e0434f4d .NET 1.0 – 3.5. Look for 1st param of mscorwks!RaiseTheException e0434352 New in 4.0. Look for 1st param of clr!RaiseTheExceptionInternalOnly 27 Debugging Exceptions native

Controls debugger actions when an exception occurs Enable Exceptions sxe AV Disable Exceptions sxd AV Ignore Exceptions sxi AV Notify Exceptions sxn AV Types of events to handle sxe ld – break when a module loads sxn av – notify (don’t break) on Access Violations Debugging Exceptions in ASP.NET Symptoms

ASP.NET will report errors in application log

Event code: 3005 Event message: An unhandled exception has occurred. Event time: 2/27/2011 7:48:47 AM Event time (UTC): 2/27/2011 6:48:47 AM Event ID: d436a409de9b4f51a3554db02b178fff Event sequence: 14 Event occurrence: 1 Event detail code: 0

Application information: Application domain: /LM/W3SVC/1/ROOT/WebApplication1-1-129432629145240513 Trust level: Full Application Virtual Path: /WebApplication1 Application Path: c:\inetput\wwwroot\WebApplication1\ Machine name: NTXXXSRV

29 Debugging Exceptions in ASP.NET

Remediation Strategies Crash - Use Debug Diagnostics or Adplus to set breakpoint on

XP kernel32!ExitProcess / kernel32!TerminateProces Win7 ntdll!RtlExitUserProcess / ntdll!RtlpTerminateCurrentProcess

- Locate the crashing thread and determine cause Session State Loss and Application Restarts - Determine causes of Application restarts • Add logging in global.asax Application_End event • Since ASP.NET 2.0, you can use Health Monitoring to log application restarts

30 Debugging Exceptions in ASP.NET

Sample Health Monitoring Web.Config 31 Debugging Exceptions in ASP.NET

Sample Health Monitoring Log

Event code: 1002 Event message: Application is shutting down. Reason: Hosting environment is shutting down. Event time: 3/25/2011 5:34:10 PM Event time (UTC): 3/25/2011 9:34:10 PM Event ID: 8d7a69ed388a4b60ad09758d7c2f63b7 Event sequence: 4 Event occurrence: 1 Event detail code: 50002

Application information: Application domain: /LM/W3SVC/1/ROOT/Debugging2-1-129455624285402371 Trust level: Full Application Virtual Path: /WebApp Application Path: C:\inetpub\wwwroot\WebApp\ Machine name: WebServerName

Process information: Process ID: 3816 Process name: w3wp.exe Account name: IIS APPPOOL\DefaultAppPool

32 Debugging Exceptions in WinForm

Attach debugger to take memory dump for post-mortem analysis .NET 2.0 - .NET 3.5 sp1

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework] "InstallRoot"="C:\\WINDOWS\\Microsoft.NET\\Framework\\" "DbgManagedDebugger"="cdb -pv -p %ld -c ".dump /u /ma c:\crashdump.dmp;.kill;qd" "DbgJitDebugLaunchSetting"=dword:00000002

Enable jitDebugging in App.config

33 Managed Debugging Assistants

MDA Debugging aids that provide additional info about runtime events Assist in troubleshooting specific issues when moving between managed & unmanaged code Common MDA’s - bindingFailure • Including probed path and/or display name • Helps troubleshoot FileNotFoundException / FileLoadException - pInvokeStackImbalance • Detects memory/stack corruptions during Pinvoke calls • Example calling convention not matching native API - reportAvOnComRelease • Detects invalid COM Release calls - callbackOnCollectedDelegate • Access violations attempting to call into managed code through function pointers that were obtained from managed delegates.

34 Enabling MDA(s)

Depending on Environment Development: Use Visual Studio - Debug | Exceptions

Production: - Regkey [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]"MDA"="1“ [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework]"MDA"="1“

- AppName.mda.config 35 Demo: MDA

Review

1. When debugging managed exceptions, what is one advantage a managed debugger has over native debugger? 2. How do you control JIT debugging of managed application when an unhandled exception is thrown? 3. What happens when a Finalizer thread throws an unhandled exception? 4. Is there a way to get .NET 2.0 Exception Handling behavior?

37 Reference

Handling Corrupted State Exceptions - http://msdn.microsoft.com/en-us/magazine/dd419661.aspx Sandboxing in .NET 4.0 - http://blogs.msdn.com/b/shawnfa/archive/2009/05/22/sandboxing-in-net-4- 0.aspx Logging ASP.NET Application Shutdown Events - http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx Diagnosing Errors with Managed Debugging Assistants - http://msdn.microsoft.com/en-us/library/d21c150d.aspx

38