Net Debugging
Total Page:16
File Type:pdf, Size:1020Kb
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 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 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 Process! 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 C# 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 - <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 hr = pPolicyManager->SetActionOnFailure(EClrFailure::FAIL_StackOverflow, EPolicyAction::eRudeUnloadAppDomain); - Eg: Change to Rude Thread 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. <legacyUnhandledExce Term. Term. Term. Term. ptionPolicy =“true”/> 18 Just In Time (JIT) Debugging .NET 4.X 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 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