Troubleshooting Exceptions Module Overview Exceptions Managed - - PowerPoint PPT Presentation
Troubleshooting Exceptions Module Overview Exceptions Managed - - PowerPoint PPT Presentation
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,
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 exception handling 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
- nly when an exception occurs.
Four types of exception handlers for protected blocks:
A finally handler that executes whenever the block exits, whether that
- ccurs 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
Build an Exception Information Table for each executable Search for an entry for the current method in the table to handle the exception Handler found? Create an Exception Object. Search for an entry for the caller of the current method in the call stack Exception Occurs Beginning of call stack? no no yes yes
Exception Handling Model
Populate Exception Object Execute Finally blocks Populate Exception Object Execute Finally blocks Resume Execution Unhandled Exception event Terminate Process! Notify Debugger 1st Chance Notify Debugger 2nd Chance
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
C# Using and Exceptions
Used to clean up resources that require disposal (IDisposable interface). IL Code
using (StreamReader reader = new StreamReader(@"C:\test.txt")) { string line = reader.ReadLine(); } 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
- <legacyCorruptedStateExceptionsPolicy enabled="true|false"/>
- 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
- Eg: Change to Rude Thread Abort (no finally) in case of a Thread
Abort
hr = pPolicyManager->SetActionOnFailure(EClrFailure::FAIL_StackOverflow, EPolicyAction::eRudeUnloadAppDomain); 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 Term. Process Term. Thread Term. Thread Term. Thread Term.
2.0 / 4.0
Process Term. Process Term. Process Term. Process Term. Process Term.
2.0 / 4.0 + <legacyUnhandledExce
ptionPolicy =“true”/> Process Term. Process Term. Thread Term. Thread Term. Thread Term.
18
Just In Time (JIT) Debugging .NET 4.X
19
JIT debugging for native and managed code configured in registry
HKEY_LOCAL_MACHINE\Software\Microsoft\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 (REG_SZ) Name of debugger and switch settings
- 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 Key (DWORD) Specifies the key that, when pressed, establishes a breakpoint in code being debugged.
Exceptions and WinRT up from .NET 4.5.1
20
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
Perfmon Counters
.NET CLR Exceptions
# of Exceps Thrown # Exceps Thrown/sec Memory Available MBytes ASP.NET version Application Restarts Worker Process Restarts
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 <exception address>
Get the managed callstack
- !clrstack
Get All exceptions in the heap use:
- !dumpheap –type Exception, !PrintException <obj>
- !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
- 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
XP kernel32!ExitProcess / kernel32!TerminateProces Win7 ntdll!RtlExitUserProcess / ntdll!RtlpTerminateCurrentProcess
30
Debugging Exceptions in ASP.NET
Sample Health Monitoring Web.Config
<healthMonitoring enabled="true"> <providers> <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider" /> </providers> <eventMappings> <add name="Application Lifetime Events" type="System.Web.Management.WebApplicationLifetimeEvent" /> </eventMappings> <rules> <add name="Web Application Lifetime Events" eventName="Application Lifetime Events" provider="EventLogProvider" /> </rules> </healthMonitoring>
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 Enable jitDebugging in App.config
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 <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.windows.forms jitDebugging="true" /> </configuration> 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
- AppName.mda.config
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]"MDA"="1“ [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework]"MDA"="1“ <mdaConfig> <assistants> <reportAvOnComRelease allowAv="false"/> </assistants> </mdaConfig> 35
Demo: MDA
<reportAvOnComRelease>
Review
- 1. When debugging managed exceptions, what is
- ne 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