Original article: http://blogs.msdn.com/ B /kaevans/archive/2011/04/11/intro-to-windbg-for-net-developers.aspx
Translation: cxfksword
After your code is published as a product, you can no longer access the program files of other people's computers or deployed on servers, the current running status and running environment of the Code cannot be observed. When your code runs in a new environment, there are many factors that will affect the running of the program, such as the server system patching, network policy changes, firewall rule restrictions, disk permission configuration. When the code is not running properly, you may only rely on the logs output from different parts of the Code to determine the running status. However, you can't judge the cause of the fault only by outputting logs.
Troubleshooting without wasting customers' time is a great challenge for you, this is because no one of the customers who like the technology keeps asking which steps have been clicked to cause program errors. Boss won't give you a few days or even weeks for you to troubleshoot slowly. You must know what happened now.
Ideally, you should be able to see the stack trace, view the current variable value, and debug the code. It turns out that you can do this... And do not need to be appended to the customer environment!
Download windbg
Download debugging tools for Windows to your local development machine. windbg is a part of the Tool. If you only need windbg,Common utilities", Select"Debugging tools for Windows"Go to installation. The installer installs the corresponding windbg Based on the CPU type of your computer, the x86 computer installs the x86 version, and the x64 CPU computer installs the x64 version. If you select"Redistributable
Packages", We will download all three versions for you (x86, x64, itanium ).
By default, windbg is installed in the C drive's "Program Files \ debugging tools for Windows" folder. We recommend that you copy the installation directory to "D: \ debug ", this facilitates the addition of other extension components.
After installation, the windbg.exe in the directory is the windbg program.
Install psscor2
The next step is to load the managed code extension component psscor2. By default, windbg can only be used to debug unmanaged code programs. After loading the SOS. dll extension component used by. net, windbg can debug the managed program. Windbg debugging. the other choice of the net program is psscor2, Which is SOS. DLL superset, and provides some additional functions for hosting code, such as viewing managed threads, managed heaps, CLR stacks, and so on.
Download psscor2 and decompress it to "D: \ debug" for later debugging.
Set the symbolic path)
When you compile a program using Visual Studio, do you notice that there are files with the. PDB Suffix in the bin/debug folder? These file packages contain the debugging symbols of the DLL assembly. The PDB file does not contain the Execution Code, but enables the debugging tool to translate the code execution instructions into correct identifiable characters. Microsoft provides a public server that contains a large number of PDB files. The address is as follows:
Http://msdl.microsoft.com/download/symbols
After the path of the symbol file is set in windbg, the related PDB files are automatically downloaded from the server and saved to the local device. First, you must specify the storage path of a PDB file, for example, "d: \ debug \ symbols ".
Open the windbg program and select "file-> symbol file path... ", Copy the following content and save it.
srv*d:\debug\symbols*http://msdl.microsoft.com/download/symbols
Create a test program
First, create a simple command line program for testing:
using System;namespace Microsoft.PFE.Samples{ public class Program { static void Main() { Console.WriteLine("Enter a message:"); string input = Console.ReadLine(); Data d = new Data { ID = 5, Message = input, CurrentDateTime = System.DateTime.Now }; Console.WriteLine("You entered: " + d); } } public class Data { public int ID {get; set;} public string Message {get; set;} public DateTime CurrentDateTime {get; set;} public override string ToString() { Console.ReadLine(); return string.Format("ID:{0} {1} at {2}", ID, Message, CurrentDateTime.ToLongTimeString()); } }}
Because psscor2 can only process programs under. Net 3.5, you need to change the program environment to. Net 3.5 before compilation. For example, to debug the. NET 4.0 program, you can download psscor4. Compile and run the program and enter a string to check whether the program runs normally.
The customer complained that he does not know why the program needs to press ENTER twice. The program does not work as expected. We must find the specific cause. As a simple example, we can see at a glance that the tostring () method in the Code contains one more Readline (), but we will try to use windbg to find out the problem.
Run the program, enter a string, and press enter once. When the second input prompt appears, do not move it! We are at the key point of capturing the problem. We need to make a dump file.
Create a dump file
In Windows 7 and windows, you can directly create a dump file in the task manager. Open the task manager, right-click the process name, and select "create Dump File ".
After the dump file is created successfully, the following prompt is displayed:
The dump file is the memory snapshot of the current process. The size of the dump file is the same as the memory size used by the process. To reduce the size, you can use the compression software to compress the file.
Another tool can be used to create a dump file, such as process explorer from sysinternals. You only need to right-click Task Management and select "Full dump ".
Adplus and debugdiag can also create dump files. Adplus is a command line program in the windbg installation directory. You can use the following command to create a dump file:
Adplus -quiet -hang -p 4332 -o d:\debug
4332 indicates the process ID. By default, the task manager does not display the process ID. to display the ID, select View> Select column in the Windows Task Manager and check "PID (process identifier) ".
Start using windbg
Now we have the program dump file, open the windbg program, select "file-> open crash dump", and select the newly created dump file. You will see some information:
Loading Dump File [D:\debug\program6.dmp]User Mini Dump File: Only registers, stack and portions of memory are availableSymbol search path is: srv*d:\debug\symbols*http://msdl.microsoft.com/download/symbolsExecutable search path is:Windows 7 Version 7600 MP (8 procs) Free x64Product: WinNt, suite: SingleUserTSMachine Name:Debug session time: Sun Feb 6 10:43:57.000 2011 (GMT-6)System Uptime: not availableProcess Uptime: 0 days 1:05:48.000.........................ntdll!NtRequestWaitReplyPort+0xa:00000000`76d2ff7a c3 ret
In the above text, you can see the path of the dump file, the path of the symbolic file, and other information. There is an input box at the bottom of the program. You can enter the command above.
Display Module
Let's try to show which modules have been loaded by the program. In the input box at the bottom of the window, enter the LM command.
0:000> lmstart end module name00000000`00120000 00000000`00128000 program (deferred)00000000`742b0000 00000000`74379000 msvcr80 (deferred)00000000`76ac0000 00000000`76bba000 user32 (deferred)00000000`76bc0000 00000000`76cdf000 kernel32 (pdb symbols) d:\debug\symbols\kernel32.pdb\D5E268B5DD1048A1BFB011C744DD3DFA2\kernel32.pdb00000000`76ce0000 00000000`76e8b000 ntdll (pdb symbols) d:\debug\symbols\ntdll.pdb\0F7FCF88442F4B0E9FB51DC4A754D9DE2\ntdll.pdb000007fe`f3fb0000 000007fe`f4134000 mscorjit (deferred)000007fe`f5030000 000007fe`f5f0b000 mscorlib_ni (deferred)000007fe`f7650000 000007fe`f7ffe000 mscorwks (deferred)000007fe`f8010000 000007fe`f80a0000 mscoreei (deferred)000007fe`f80a0000 000007fe`f810f000 mscoree (deferred)000007fe`fcb70000 000007fe`fcb7f000 CRYPTBASE (deferred)000007fe`fcc40000 000007fe`fcc4f000 profapi (deferred)000007fe`fcf20000 000007fe`fcf8b000 KERNELBASE (deferred)000007fe`fd0e0000 000007fe`fd2e2000 ole32 (deferred)000007fe`fd4d0000 000007fe`fd59a000 usp10 (deferred)000007fe`fd6f0000 000007fe`fe476000 shell32 (deferred)000007fe`fe480000 000007fe`fe4ae000 imm32 (deferred)000007fe`fe840000 000007fe`fe84e000 lpk (deferred)000007fe`fe9d0000 000007fe`feaab000 advapi32 (deferred)000007fe`feb50000 000007fe`fec7e000 rpcrt4 (deferred)000007fe`fec80000 000007fe`fecf1000 shlwapi (deferred)000007fe`fed00000 000007fe`fed67000 gdi32 (deferred)000007fe`fee10000 000007fe`fef19000 msctf (deferred)000007fe`fef20000 000007fe`fefbf000 msvcrt (deferred)000007fe`fefd0000 000007fe`fefef000 sechost (deferred)
In the above module list, you need to check whether mscorwks exists. psscor2 can only be used for. Net 3.5 programs. If it is A. Net 4.0 program, the mscorwks module is invisible.
For SharePoint developers, if you are debugging program features such as receivers and event processing why they are not triggered, lm will be a good command. Through the list above, you can know which modules are not loaded, which may be caused by incorrect configuration, which can greatly reduce the scope of your search for problems. ASP. NET developers can find out why the httpmodule is not triggered, possibly because the Web. config configuration is incorrect.
Load psscor2
To add the psscor2 extension component to windbg, run the following command:
.load d:\debug\psscor2\amd64\psscor2.dll
My computer is 64-bit, so I loaded psscor2.dll of amd64. The loaded psscor2 version must be consistent with the architecture of the server where the dump file process is located. If you are debugging the dump file of an x86 program, you must load psscor2.dll of the x86 version.
Enter the following command to check whether psscor2 is successfully loaded:
!help
Enter the following content correctly:
0:000> .load d:\debug\psscor2\amd64\psscor2.dll0:000> !help-------------------------------------------------------------------------------PSSCOR is a debugger extension DLL designed to aid in the debugging of managedprograms. Functions are listed by category, then roughly in order ofimportance. Shortcut names for popular functions are listed in parenthesis.Type "!help " for detailed info on that function. Object Inspection Examining code and stacks----------------------------- -----------------------------DumpObj (do) ThreadsDumpArray (da) CLRStackDumpStackObjects (dso) IP2MDDumpAllExceptions (dae) BPMDDumpHeap UDumpVC DumpStackGCRoot EEStackObjSize GCInfoFinalizeQueue EHInfoPrintException (pe) COMStateTraverseHeapDumpField (df)DumpDynamicAssemblies (dda)GCRefDumpColumnNames (dcn)DumpRequestQueuesDumpUMServiceExamining CLR data structures Diagnostic Utilities----------------------------- -----------------------------DumpDomain VerifyHeapEEHeap DumpLogName2EE FindAppDomainSyncBlk SaveModuleDumpThreadConfig (dtc) SaveAllModules (sam)DumpMT GCHandlesDumpClass GCHandleLeaksDumpMD VMMapToken2EE VMStatEEVersion ProcInfoDumpModule StopOnException (soe)ThreadPool MinidumpModeDumpHttpRuntime FindDebugTrueDumpIL FindDebugModulesPrintDateTime AnalysisDumpDataTables CLRUsageDumpAssembly CheckCurrentException (cce)RCWCleanupList CurrentExceptionName (cen)PrintIPAddress VerifyObjDumpHttpContext HeapStatASPXPages GCWhereDumpASPNETCache (dac) ListNearObj (lno)DumpSigDumpMethodSig OtherDumpRuntimeTypes -----------------------------ConvertVTDateToDate (cvtdd) FAQConvertTicksToDate (ctd)DumpRequestTableDumpHistoryTableDumpBucketsGetWorkItemsDumpXmlDocument (dxd)DumpCollection (dc)Examining the GC history-----------------------------HistInitHistStatsHistRootHistObjHistObjFindHistClear
Mscordacwks. dll
I like to create a program's dump file on the server, and then transfer the dump file to my Windows 7 Development machine for debugging. If the server is a Windows Server 2008 R2 operating system, when I use psscor2 on a local development machine, it is easy to encounter the following error:
CLRDLL: CLR DLL load disabledFailed to load data access DLL, 0x80004005Verify that 1) you have a recent build of the debugger (6.2.14 or newer) 2) the file mscordacwks.dll that matches your version of mscorwks.dll is in the version directory 3) or, if you are debugging a dump file, verify that the file mscordacwks___.dll is on your symbol path. 4) you are debugging on the same architecture as the dump file. For example, an IA64 dump file must be debugged on an IA64 machine.You can also run the debugger command .cordll to control the debugger'sload of mscordacwks.dll. .cordll -ve -u -l will do a verbose reload.If that succeeds, the PSSCOR command should work on retry.If you are debugging a minidump, you need to make sure that your executablepath is pointing to mscorwks.dll as well.
A related blog article about how to work around the mscordacwks issue is found through Bing search. The article points out that the mscordacwks file of the server needs to be copied to the windbg program directory. Mscordacwks in my windows
The version on Server 2008 R2 is 4952, So I copied mscordacwks from the server to the windbg directory and renamed it "mscordacwks_amd64_amd64_2.0.50727.4952.dll". The path of mscordacwks on the server is "" C: \ WINDOWS \ Microsoft. net \ framework \ v2.0.50727 \ mscordacwks. DLL ", if you do not know the correct rename rules, you can enter the following command, the output will prompt the mscordacwks name to be loaded.
0:000> .cordll -ve -u -lCLR DLL status: No load attempts0:000> !threadsCLRDLL: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscordacwks.dll:2.0.50727.3053 f:0doesn't match desired version 2.0.50727.3625 f:0CLRDLL: Unable to find mscordacwks_AMD64_AMD64_2.0.50727.4952.dll by mscorwks searchCLRDLL: Unable to find 'mscordacwks_AMD64_AMD64_2.0.50727.4952.dll' on the pathCLRDLL: Unable to get version info for 'd:\debug\symbols\mscorwks.dll\4E154C985a9000\mscordacwks_AMD64_AMD64_2.0.50727.4952.dll', Win32 error 0n87CLRDLL: ERROR: Unable to load DLL mscordacwks_AMD64_AMD64_2.0.50727.4952.dll, Win32 error 0n87Failed to load data access DLL, 0x80004005Verify that 1) you have a recent build of the debugger (6.2.14 or newer) 2) the file mscordacwks.dll that matches your version of mscorwks.dll is in the version directory 3) or, if you are debugging a dump file, verify that the file mscordacwks___.dll is on your symbol path. 4) you are debugging on the same architecture as the dump file. For example, an IA64 dump file must be debugged on an IA64 machine.You can also run the debugger command .cordll to control the debugger'sload of mscordacwks.dll. .cordll -ve -u -l will do a verbose reload.If that succeeds, the PSSCOR command should work on retry.If you are debugging a minidump, you need to make sure that your executablepath is pointing to mscorwks.dll as well.
After the name is renamed, enter the preceding command again, and a message indicating successful loading is displayed.
0:000> .cordll -ve -u -lCLR DLL status: Loaded DLL mscordacwks_AMD64_AMD64_2.0.50727.4952.dl
Check CRL Stack
To view the CLR stack content, enter the following command:
!clrstack
The output is as follows:
0:000> !clrstackOS Thread Id: 0xa48 (0)*** WARNING: Unable to verify checksum for mscorlib.ni.dllChild-SP RetAddr Call Site000000000012e910 000007fef5a910e9 DomainNeutralILStubClass.IL_STUB(Microsoft.Win32.SafeHandles.SafeFileHandle, Byte*, Int32, Int32 ByRef, IntPtr)000000000012ea30 000007fef5a91202 System.IO.__ConsoleStream.ReadFileNative(Microsoft.Win32.SafeHandles.SafeFileHandle, Byte[], Int32, Int32, Int32, Int32 ByRef)000000000012ea90 000007fef538065a System.IO.__ConsoleStream.Read(Byte[], Int32, Int32)000000000012eaf0 000007fef53a28ca System.IO.StreamReader.ReadBuffer()000000000012eb40 000007fef5a9435f System.IO.StreamReader.ReadLine()000000000012eb90 000007ff0017015b System.IO.TextReader+SyncTextReader.ReadLine()000000000012ebf0 000007fef791d502 Program.Main()
Awesome! Now you can see the call status of the stack. We can immediately see that the program enters the program. Main Function, calls console. Readline, and waits for user input.
Conclusion
This article is just a brief introduction to the use of windbg. If you want to learn about windbg globally and how to use windbg for troubleshooting, you can refer to the video tutorial "debugging" in Tess ferrandez. net Applications with windbg ".
Additional reading:
Process explorer from sysinternals
Psscor2 debugging Extension
Download the debugging tools for Windows
SOS. dll (SOS debugging extension)
"Failed
To load data access DLL, 0 × 80004005 "-or-what is mscordacwks. dll?
Debugdiag
Getting started with windbg-Part I
Getting started with windbg-Part II