Debugging NET Applications With WinDBG

31,836 views

Published on

In this presentation, Cory covers the basics of debugging production .NET application problems using WinDBG and the SOS extension.

Published in: Technology
2 Comments
15 Likes
Statistics
Notes
  • Hi,
    Can you send me the Windbg demo file?
    Thanks a lot!
    smsrede@hotmail.com
    Samuel Menezes
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Perfect
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
31,836
On SlideShare
0
From Embeds
0
Number of Embeds
5,880
Actions
Shares
0
Downloads
642
Comments
2
Likes
15
Embeds 0
No embeds

No notes for slide
  • Why you see OOM Exception objects on the heap
  • Debugging NET Applications With WinDBG

    1. 1. Debugging .NET Applications with WinDBG<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    2. 2. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks<br />Other Tools<br />
    3. 3. .NET Fundamentals<br />CLR Fundamentals<br />Memory Management Basics<br />Debugging Fundamentals<br />
    4. 4. CLR Fundamentals<br />Managed Assembly Layout<br />PE Header<br />CLR Header<br />IL (Intermediate Language)<br />Metadata Header<br />Metadata<br />
    5. 5. CLR Fundamentals<br />.NET Runtime in a Process<br />
    6. 6. Demo: Viewing Managed Objects<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    7. 7. Viewing Managed Objects<br />Start up the app and click on the Managed Objects button<br />Start up WinDBG and attach to the executable (click “No” if it asks you to save the workspace) then load SOS by typing “.loadbysosmscorwks” and hitting enter. Also load symbols by typing “.symfix C:symbols” and hitting enter, then typing “.reload” and hitting enter<br />
    8. 8. Viewing Managed Objects<br />View All Threads by typing in “~” and hitting enter. View all managed threads by typing in “!threads” and hitting enter. Note there are 5 native threads, but only 2 managed threads. Also note that thread 2 is marked as (Finalizer) – that’s the thread responsible for finalization<br />Change to the main thread by typing “~0s” (tilde zero s). This tells WinDBG to switch to thread 0. Then type “!clrstack” to see where we are in the application. Note we are in the Main method right now.<br />
    9. 9. Viewing Managed Objects<br />Next, let’s look at the objects on the heap. Type “!dumpheap –stat”. You’ll see many objects. You can filter by typing things like -min or –max as parameters to dumpheap.<br />Now find all of our objects on the heap by typing “!dumpheap –type WinDBG”. This filters for any object with the text “WinDBG” in it’s name. The top list are the actual objects and their memory locations, while the bottom list are the type names. You can figure out which is which by matching up the MethodTable addresses (MT Column)<br />
    10. 10. Viewing Managed Objects<br />We can view a specific object using “!dumpobj” (or “!do” for short). We’ll look at the HelloWorld Object by typing “!do &lt;address&gt;” where address is from the !dumpheap command earlier. We can see we have a string field called “hello” and a world property.<br />We can then look at the string by typing “!do &lt;address&gt;”. In this example, the address would be 263a000. We can see that field contains the string “Hello”.<br />
    11. 11. Viewing Managed Objects<br />When we did a !do on the HelloWorld object, one piece of information was the MethodTable address. We can use the !dumpmt command to see what methods the object exposes. Type “!dumpmt –md &lt;methodtableaddress&gt;”. If the JIT Column has “PreJIT” then the method came from an Ngen’d object. If it has JIT, then the method has been called and JIT’d. If it has NONE, the method hasn’t been called.<br />You can dissassemble IL that has been JIT’d by passing in the MethodDesc address to “!U”<br />
    12. 12. Viewing Managed Objects<br />If we’ve attached to the process doing a live debug (which we’re doing here), then you can set breakpoints using !bpmd. For example, we can have it breakpoint just before the MessageBox shows up by passing in the assembly name and fully qualified type. You can use bl to see the breakpoints.<br /> We then type “g” to release the current break we have on the app, and click the Managed Objects button again.<br />We’ll then see WinDBG hit the breakpoint. We can run !clrstack to see what led us to that call<br />
    13. 13. CLR Fundamentals<br />Threads<br />Managed Threads is an object – it lives on native system threads<br />CLR Threads<br />Finalizer<br />Garbage Collector (Server GC)<br />Debugger<br />Timer<br />Threadpool (I/O and Worker)<br />
    14. 14. CLR Fundamentals<br />Just-In-Time compilation<br />Program makes a call to a method<br />The .NET Runtime checks to see if the method has been called before<br />If so, it executes the JIT’d code<br />If not, it compiles the IL code and stores it in memory, updating the MethodDesc<br />
    15. 15. .NET Fundamentals<br />CLR Fundamentals<br />Memory Management Basics<br />Debugging Fundamentals<br />
    16. 16. Memory Management<br />Stacks versus Heaps<br />Stack – First in / First Out<br />Heap – access by address<br />Garbage Collector Heap<br />Where all objects are stored<br />Broken into 3 generations and one Large Object Heap<br />Large Object &gt; 85,000 bytes<br />
    17. 17. Memory Management<br />Garbage Collector Sequence<br />Suspend Execution Engine<br />Mark objects without roots<br />Plan (budgets, fragmentation)<br />Sweep (delete market objects)<br />Compact (move leftover objects to back of heap)<br />Restart Execution Engine<br />
    18. 18. Memory Management<br />Memory Leaks<br />Possible in both Managed and Unmanaged Code<br />Use Perfmon to check for symptoms<br />Unmanaged Leak<br />Private Bytes Increase, #Bytes In All Heaps stays flat<br />Managed Leak<br />Both Private Bytes and Bytes In All Heaps increase<br />Need multiple dump files<br />
    19. 19. Memory Management<br />http://blogs.msdn.com/tess/archive/2008/03/17/net-debugging-demos-lab-6-memory-leak-review.aspx<br />
    20. 20. Memory Management<br />Why do we leak managed memory?<br />Objects not being released<br />“Pinned” memory<br />Finalized Objects (Destructors on Managed Objects)<br />Finalized objects require an additional GC cycle to be cleaned since they have to go in the finalizer thread to run<br />
    21. 21. Memory Management<br />Exception Handling Workflow<br />Exception Occurs (create an exception object)<br />Notify Debugger (1st Chance Exception)<br />Look for a handler by walking up the call stack<br />If handler found, let it handle exception<br />If not, throw a 2nd Chance Exception and terminate the process<br />
    22. 22. .NET Fundamentals<br />CLR Fundamentals<br />Memory Management Basics<br />Debugging Fundamentals<br />
    23. 23. Debugging Fundamentals<br />Typical Problems in Production<br />System hangs or deadlocks<br />Fatal Exceptions<br />Data Loss or inconsistency<br />Performance Problems<br />Excessive Memory Usage<br />App Pool Restarts (slow access to ASP.NET pages)<br />
    24. 24. Debugging Fundamentals<br />Approaching the problem<br />Be the application (visualize what could cause the problem)<br />Use Application and System Logs<br />Try to reproduce in Development or Staging environments<br />Create a hypothesis and use WinDBG to validate<br />
    25. 25. Debugging Fundamentals<br />Debugging Production Apps<br />Typically don’t have Visual Studio installed, or access to the remote debugger<br />Attaching a debugger freezes all threads<br />Capture memory dumps<br />At time of crash / exception<br />Over time to troubleshoot hangs / leaks<br />
    26. 26. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks Other Tools<br />
    27. 27. Debugging Crashes<br />Application seems to work fine, but something happens<br />Unhandled Exception Dialog<br />App “disappears”<br />Steps<br />Desktop App: Attach and stop on Exceptions<br />Web App: Use DebugDiag to capture memory dump<br />
    28. 28. Demo: Debugging Crashes<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    29. 29. Debugging Crashes<br />Open Application and click the “Crash” button”. Unhandled Dialog should appear and kill the app. Start app back up and attach to it with WinDBG, then load SOS. Once SOS is loaded, type “sxeclr” to tell WinDBG to break on all .NET Exceptions, then type “g” and click on the Crash button again.<br />Because we’ve enabled exception notification, WinDBG breaks on the first-chance exception.<br />
    30. 30. Debugging Crashes<br />The first place to look is the exception object itself. We can either do a “!do” on the object address listed, or simply type “!pe”. You can also pass an address to !pe if you need to view other than the last exception thrown.<br />We can see there is a file not found exception. Let’s see where we were at.<br />So it looks like the app calls “ReadAllText” from a method called “Crash_Click” from the Form1 object. If we have access to Source, we’d start there. If not, we can find the method address and dissassemble<br />
    31. 31. Debugging Crashes<br />Note that if we click “g” at this point, WinDBG breaks again. This is because the exception we first saw was *not* the crash reason. Like the previous exception, this one is listed as a First Chance Exception. <br />If we click “g” again, we’ll see WinDBG breakpoint again. Note that it clearly tells us this is a second chance exception – the next thing that will happen is process termination.<br />
    32. 32. Demo: Debugging Crashes on Application Startup<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    33. 33. Debugging Crashes On Startup<br />Open the App and check the “Crash on Startup” option, then close the app and restart. Notice it immediately crashes.<br />The challenge is that we won’t have time to attach a debugger. You can set registry keys to automatically launch a debugger, or we could launch the app from the debugger, which we’ll do here.<br />Start up WinDBG and go to File-&gt;Open Executable. Browse to the WinDBGDemo executable and select it.<br />
    34. 34. Debugging Crashes On Startup<br />At this point, we are in the PE load of the application, meaning it hasn’t even decided if this is a native or managed app yet. Which also means no .NET libraries are loaded, so we can’t load SOS. <br />What we can do is set a breakpoint to fire when the .NET runtime is loaded, at which point we can set the handlers we need. Type “sxe ld mscorwks” which means set WinDBG to break when mscorwks is loaded. We can now load SOS and set the CLR Exception breakpoints. Now type “g” till our app breaks. You can now debug it as a crash.<br />
    35. 35. Debugging Crashes On Startup<br />If you have a Windows Service which is crashing on startup, then you’ll need to modify some registry keys and permissions on the service. For more information, see the following KB article, or the blog post from our site<br />(Note: When you finish this demo, go to your user directoryAppDataLocalMicrosoftWinDBGDemo.exe1.0.0.0 and modify the user.config file to have CrashOnStartup to be False)<br />http://support.microsoft.com/kb/824344<br />http://blog.coryfoy.com/2008/06/debugging-a-net-windows-service-that-is-crashing-on-startup/<br />
    36. 36. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks Other Tools<br />
    37. 37. Debugging Memory Leaks<br />Memory Usage Continues to grow in the app<br />May cause app pool restarts in ASP.NET<br />Out of Memory exceptions when you still have memory free<br />Several Reasons<br />Unreleased objects<br />“Pinned” memory<br />You have plenty of memory! (GC only runs when it feels memory pressure)<br />
    38. 38. Debugging Memory Leaks<br />Diagnosing Memory Leaks<br />PerfMon to determine if it is a managed leak<br />Take multiple memory dumps to determine what is happening<br />For the objects on the heap, find out why they are sticking around<br />Check the GC Generation for the objects<br />
    39. 39. Demo: Debugging Memory Leaks<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    40. 40. Debugging Memory Leaks<br />Start the app and task manager, then click on the Memory Leak button. Note that the memory is still increasing. <br />Fire up Perfmon to see if this is a managed or native leak. Start-&gt;Run-&gt;Perfmon. You can remove the Processor Time counter and add the following counters: .NET CLR Memory -&gt; #Bytes in all Heaps -&gt; WinDBGDemo and Process -&gt; Private Bytes -&gt; WinDBGDemo. <br />You should see that both are growing at about the same rate indicating a managed leak<br />
    41. 41. Debugging Memory Leaks<br />To debug this, we’ll need to take two snapshots of the application far enough apart to see memory difference. You can do this right from Task Manager. Create two, about 15 seconds apart. You can now kill the application.<br />Open two instances of WinDBG and open each memory dump file you created in a different instance of WinDBG. Load up SOS in each one as well.<br />
    42. 42. Debugging Memory Leaks<br />What we’re wanting to do is compare the two memory dumps to see if we can spot the culprit. Using !VMStat on each file we can see that memory usage is certainly increasing. <br />And if we do a “!dumpheap –stat” on each one, we can see something quite startlingly – 230,000 additional objects are on the heap!<br />
    43. 43. Debugging Memory Leaks<br />Normally you’d have to dig through the heap to find which objects increased, but we see something interesting. An object called “LeakForm” has had 900 instances created. Perhaps those aren’t being cleaned up?<br />Let’s look at one. We’ll see all the instances by doing a “!dumpheap -type WinDBGDemo.LeakForm” then picking any object at random to do a !do on<br />With that object address, let’s see what is holding on to it with “!GCRoot &lt;address&gt;”<br />
    44. 44. Debugging Memory Leaks<br />We see that the LeakForm is being held on to an object, which is of type System.Object[]. If we do a !do on it, we don’t see much of interest<br />But if we compare the arrays between the first dump and the second dump using the “!da &lt;address&gt;” command, we find a clue. Between the first and second memory dumps, all of the extra LeakForms were added to this array!<br />At this point, we examine the source code to see what is going on.<br />
    45. 45. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks Other Tools<br />
    46. 46. Debugging Hangs<br />Two types of hangs<br />Low CPU Hang<br />Generally caused by a deadlock<br />High CPU Hang<br />App in a tight loop, or under heavy load<br />
    47. 47. Debugging Hangs<br />Diagnosing Hangs<br />High CPU Hang<br />Multiple memory dumps<br />Compare which thread is getting processor time<br />Low CPU Hang<br />Walk through the waiting threads and match locks<br />Very tedious process<br />
    48. 48. Demo: Debugging High CPU Hangs<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    49. 49. Debugging High CPU Hangs<br />Start the app and Task Manager. Click on the High CPU Hang. You should see a single processor spike (100% on 1CPU). In this example, I have a 4CPU system, so a CPU of 25% indicates it is fully utilizing one processor.<br />Take two memory dumps from Task Manager about 15 seconds apart. You can then kill the application.<br />
    50. 50. Debugging High CPU Hangs<br />Open the two memory dump files in different WinDBG instances and load SOS.<br />The first thing we need to know is if a single thread is using up all of the time, indicating a possible loop. We can use the command !runaway to see which threads are getting CPU time<br />We can see from this that thread 0 was using up all of the time in between the two memory dumps<br />
    51. 51. Debugging High CPU Hangs<br />So what is thread 0 doing? By running !clrstack on each memory dump, we can see that the call stacks are the same, possibly indicating that this is the culprit.<br />I say possibly because if a bunch of calls are happening to different methods, we very well could have gotten “lucky” and seen the same method. Always verify your assumptions.<br />In this case, looking at the source (either real source, or through reflector) we see the following. I think we have our culprit <br />
    52. 52. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks<br />Other Tools<br />
    53. 53. Demo: WinDBG Tips and Tricks<br />Cory Foy<br />http://coryfoy.com | @cory_foy<br />
    54. 54. WinDBG Tips and Tricks<br />You can get quite a bit of help with both WinDBG and SOS.<br />For the WinDBG help content, type “.hh” and it will open the WinDBG CHM file. You can also type “.hh &lt;command&gt;” and it will take you to that section<br />For SOS, you can type “!help” to see all available commands, or “!help &lt;command&gt;” to see a specific one<br />
    55. 55. WinDBG Tips and Tricks<br />You can use the shell command to run the output of a WinDBG command to an external process and the results are displayed back into the UI. For example, to quickly find the shared domain, you can run ‘.shell –ci “!dumpdomain” find /i “shared domain”’<br />You can also take advantage of this to do integrations with PowerShell<br />
    56. 56. WinDBG Tips and Tricks<br />When viewing stacks, you can use !clrstack to view the managed stack. You can also use the command “k” to view the native stack<br />You can also output the stack for all threads by combining the “~” command with a star (for all threads) and the command. For example “~*k” or “~*e!clrstack” (which means execute the command !clrstack)<br />
    57. 57. WinDBG Tips and Tricks<br />You can do a lot with automation of WinDBG. For example, you can have WinDBG execute commands when certain breakpoints are hit<br />You can also automate what happens when CLR Exceptions are hit by using the –c option with sxe. In this example, every time we hit an exception we would spit out the exception and CLR stack trace. <br />
    58. 58. WinDBG Tips and Tricks<br />You can also loop through various elements. For example, if we wanted to dump out all strings greater than 5k that were on the heap, we could do the following with the “.foreach” command<br />Finally, if you want to adjust the colors, you can do that in View-&gt;Options<br />
    59. 59. Agenda<br />.NET Fundamentals<br />Debugging Crashes<br />Debugging Memory Leaks<br />Debugging Hangs<br />WinDBG Tips and Tricks<br />Other Tools<br />
    60. 60. Additional Tools<br />DebugDiag<br />Used to automate the capture of exceptions for IIS processes<br />ADPlus<br />Used to capture dumps from command line<br />Managed Debuggers (CorDbg, MDbg)<br />Managed Debugging Assistants (Visual Studio)<br />Profilers<br />
    61. 61. More Information<br />http://blogs.msdn.com/tess<br />microsoft.com/whdc/DevTools/Debugging<br />http://windbg.info<br />http://www.coryfoy.com<br />foyc at coryfoy dot com<br />@cory_foy on Twitter<br />Slides will be posted on CoryFoy.com<br />

    ×