首页
社区
课程
招聘
[分享]Mdbg (C# debugger in C#) source
发表于: 2010-11-27 09:31 8762

[分享]Mdbg (C# debugger in C#) source

2010-11-27 09:31
8762
The CLR Managed Debugger

sample illustrates how to build a managed debugger
using the included managed wrappers for the CLR Debugging Services APIs (ICorDebug).

This is a full source sample for building a managed debugger in C#.

We're up to version 2.1.0, and it includes:

   1. Mdbg + Python integration. (You need to download Python separately)
   2. Managed wrappers for native debugging APIs like WaitForDebugEvent. (This is what I alluded to previously here).
   3. Improved event logging infrastructure.
   4. Pdb2Xml conversion tool, which now includes round-tripping the pdbs. (I hoped we'd release this earlier, but better late than never.)
   5. Updated Eula.
   6. Better organized directory structure. This includes a "tools" subdirectory, which we expect to pave the way for adding new Mdbg-based tools.
   7. All IL files have been converted into C#, so it's now a pure C# solution.

FORUM

[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

上传的附件:
收藏
免费 0
支持
分享
最新回复 (3)
雪    币: 370
活跃值: (15)
能力值: ( LV9,RANK:170 )
在线值:
发帖
回帖
粉丝
2
http://msdn.microsoft.com/en-us/library/ms229861.aspx


MDbg.exe (.NET Framework Command-Line Debugger)
.NET Framework 4 Other Versions .NET Framework 3.5
.NET Framework 2.0

The NET Framework Command-Line Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET Framework common language runtime. This tool uses the runtime debugging API to provide debugging services. You can use MDbg.exe to debug only managed code; there is no support for debugging unmanaged code.

The .NET Framework Command-Line Debugger is automatically installed with both Visual Studio and the Windows SDK. To start the tool, open either the Visual Studio Command Prompt or the Windows SDK CMD Shell. (To open CMD Shell, click Start, click All Programs, click Microsoft Windows SDK v7.0, and then click CMD Shell.) At the command prompt, type the following:

CopyMDbg [ProgramName[arguments]] [options]

Commands
--------------------------------------------------------------------------------

When you are in the debugger (as indicated by the mdbg> prompt), type one of the commands described in the next section:

command [arguments]

MDbg.exe commands are case-sensitive.


Command
Description

ap[rocess] [number]
Switches to another debugged process or prints available processes. The numbers are not real process IDs (PIDs), but a 0-indexed list.

a[ttach] [pid]
Attaches to a process or prints available processes.

b[reak] [ClassName.Method | FileName:LineNo]
Sets a breakpoint at the specified method. Modules are scanned sequentially.

break FileName:LineNo sets a breakpoint at a location in the source.

break ~number sets a breakpoint on a symbol recently displayed with the x command.

break module!ClassName.Method+IlOffset sets a breakpoint on the fully qualified location.

block[ingObjects]
Displays monitor locks, which are blocking threads.

ca[tch] [exceptionType]
Causes the debugger to break on all exceptions, and not just on the unhandled exceptions.

cl[earException]
Marks the current exception as handled so that execution can continue. If the cause of the exception has not been dealt with, the exception may be quickly rethrown.

conf[ig] [option value]
Displays all configurable options and shows how the options are invoked without any optional values. If the option is specified, sets value as the current option. The following options are currently available:

extpath sets the path to search for extensions when the load command is used.

extpath+ adds a path for loading extensions.

del[ete]
Deletes a breakpoint.

de[tach]
Detaches from a debugged process.

d[own] [frames]
Moves the active stack frame down.

echo
Echoes a message to the console.

enableNotif[ication] typeName 0|1
Enables (1) or disables (0) custom notifications for the specified type.

ex[it] [exitcode]
Exits the MDbg.exe shell, and optionally specifies the process exit code.

fo[reach] [OtherCommand]
Performs a command on all threads. OtherCommand is a valid command that operates on one thread; foreach OtherCommand performs the same command on all threads.

f[unceval] [-ad Num] functionName [args ... ]
Performs a function evaluation on the current active thread where the function to evaluate is functionName. The function name must be fully qualified, including namespaces.

The -ad option specifies the application domain to use to resolve the function. If the -ad option is not specified, the application domain for resolution defaults to the application domain where the thread that is used for function evaluation is located.

If the function that is being evaluated is not static, the first parameter passed in should be a this pointer. All application domains are searched for arguments to the function evaluation..

To request a value from an application domain, prefix the variable with the module and application domain name; for example, funceval -ad 0 System.Object.ToString hello.exe#0!MyClass.g_rootRef. This command evaluates the function System.Object.ToString in the application domain 0. Because the ToString method is an instance function, the first parameter must be a this pointer.

g[o]
Causes the program to continue until it encounters a breakpoint, the program exits, or an event (for example, an unhandled exception) causes the program to stop.

h[elp] [command]

-or-

? [command]
Displays a description of all commands or a detailed description of a specified command.

ig[nore] [event]
Causes the debugger to stop on unhandled exceptions only.

int[ercept] FrameNumber
Rolls the debugger back to a specified frame number.

If the debugger encounters an exception, use this command to roll the debugger back to the specified frame number. You can change the program state by using the set command and continue by using the go command.

k[ill]
Stops the active process.

l[ist] [modules | appdomains | assemblies]
Displays the loaded modules, application domains, or assemblies.

lo[ad] assemblyName
Loads an extension in the following manner: The specified assembly is loaded and an attempt is then made to run the static method LoadExtension from the Microsoft.Tools.Mdbg.Extension.Extension type.

log [eventType]
Set or display the events to be logged.

mo[de] [option on/off]
Sets different debugger options. Use mode with no options to get a list of the debugging modes and their current settings.

mon[itorInfo] monitorReference
Displays object monitor lock information.

newo[bj] typeName [arguments...]
Creates a new object of type typeName.

n[ext]
Runs code and moves to the next line (even if the next line includes many function calls).

Opendump pathToDumpFile
Opens the specified dump file for debugging.

o[ut]
Moves to the end of the current function.

pa[th] [pathName]
Searches the specified path for the source files if the location in the binaries is not available.

p[rint] [var] | [-d]
Prints all variables in scope (print), prints the specified variable (print var), or prints the debugger variables (print -d).

printe[xception] [-r]
Prints the last exception on the current thread. Use the –r (recursive) option to traverse the InnerException property on the exception object to get information about the entire chain of exceptions.

pro[cessenum]
Displays the active processes.

q[uit] [exitcode]
Quits the MDbg.exe shell, optionally specifying the process exit code.

re[sume] [* | [~]threadNumber]
Resumes the current thread or the thread specified by the threadNumber parameter.

If the threadNumber parameter is specified as * or if the thread number starts with ~, the command applies to all threads except the one specified by threadNumber.

Resuming a non-suspended thread has no effect.

r[un] [-d(ebug) | -o(ptimize) |-enc] [[path_to_exe] [args_to_exe]]
Stops the current process (if there is one) and starts a new one. If no executable argument is passed, this command runs the program that was previously executed with the run command. If the executable argument is provided, the specified program is run using the optionally supplied arguments.

If class load, module load, and thread start events are ignored (as they are by default), the program stops on the first executable instruction of the main thread.

You can force the debugger to just-in-time (JIT) compile the code by using one of the following three flags:

-d(ebug) disables optimizations. This is the default for MDbg.exe.

-o(ptimize) forces the code to run more like it does outside the debugger, but also makes the debugging experience more difficult. This is the default for use outside the debugger.

-enc enables the Edit and Continue feature but incurs a performance hit.

Set variable=value
Changes the value of any in-scope variable.

You can also create your own debugger variables and assign reference values to them from within your application. These values act as handles to the original value, and even the original value is out of scope. All debugger variables must begin with $ (for example, $var). Clear these handles by setting them to nothing using the following command:

set $var=

Setip [-il] number
Sets the current instruction pointer (IP) in the file to the specified position. If you specify the -il option, the number represents a Microsoft intermediate language (MSIL) offset in the method. Otherwise, the number represents a source line number.

sh[ow] [lines]
Specifies the number of lines to show.

s[tep]
Moves execution into the next function on the current line, or moves to the next line if there is no function to step into.

su[spend] [* | [~]threadNumber]
Suspends the current thread or the thread specified by the threadNumber parameter. If threadNumber is specified as *, the command applies to all threads. If the thread number starts with ~, the command applies to all threads except the one specified by threadNumber. Suspended threads are excluded from running when the process is run by either the go or step command. If there are no non-suspended threads in the process and you issue the go command, the process will not continue. In that case, press CTRL-C to break into the process.

sy[mbol] commandName [commandValue]
Specifies one of the following commands:

symbol path ["value"] - Displays or sets the current symbol path.

symbol addpath "value" - Adds to your current symbol path.

symbol reload ["module"]- Reloads either all symbols or the symbols for the specified module.

symbol list [module] - Shows the currently loaded symbols for either all modules or the specified module.

t[hread] [newThread] [-nick nickname]
The thread command with no parameters displays all managed threads in the current process. Threads are usually identified by their thread numbers; however, if the thread has an assigned nickname, the nickname is displayed instead. You can use the -nick parameter to assign a nickname to a thread.

thread -nick threadName assigns a nickname to the currently running thread.

Nicknames cannot be numbers. If the current thread already has an assigned nickname, the old nickname is replaced with the new one. If the new nickname is an empty string (""), the nickname for the current thread is deleted and no new nickname is assigned to the thread.

u


Moves the active stack frame up.

uwgc[handle] [var] | [address]
Prints the variable tracked by a handle. The handle can be specified by name or address.

when
Displays the currently active when statements.

when delete all | num [num [num …]] - Deletes the when statement specified by the number, or all when statements if all is specified.

when stopReason [specific_condition] do cmd [cmd [cmd …] ] - The stopReason parameter can be one of the following:

StepComplete , ProcessExited, ThreadCreated, BreakpointHit, ModuleLoaded, ClassLoaded, AssemblyLoaded, AssemblyUnloaded, ControlCTrapped, ExceptionThrown, UnhandledExceptionThrown, AsyncStop, AttachComplete, UserBreak, EvalComplete, EvalException, RemapOpportunityReached, NativeStop.

specific_condition can be one of the following:

number - For ThreadCreated and BreakpointHit, triggers action only when stopped by a thread ID/breakpoint number with same value.

[!]name - For ModuleLoaded, ClassLoaded, AssemblyLoaded, AssemblyUnloaded, ExceptionThrown, and UnhandledExceptionThrown, triggers action only when the name matches the name of the stopReason.

specific_condition must be empty for other values of stopReason.

w[here] [-v] [-c depth] [threadID]
Displays debug information about stack frames.

The -v option provides verbose information about each displayed stack frame.

Specifying a number for depth limits how many frames are displayed. Use the all command to display all frames. The default is 100.

If you specify the threadID parameter, you can control which thread is associated with the stack. The default is the current thread only. Use the all command to get all threads.

x [-c numSymbols] [module[!pattern]]
Displays functions that match the pattern for a module.

If numSymbols is specified, the output is limited to the specified number. If ! (indicating a regular expression) is not specified for pattern, all functions are displayed. If module is not provided, all loaded modules are displayed. Symbols (~#) can be used to set breakpoints using the break command.


Remarks
--------------------------------------------------------------------------------

Compile the application to be debugged by using compiler-specific flags that cause your compiler to generate debugging symbols. Refer to your compiler's documentation for more information about these flags. You can debug optimized applications, but some debugging information will be missing. For example, many local variables will not be visible and source lines will be inaccurate.

After you compile your application, type mdbg at the command prompt to start a debugging session, as shown in the following example.

Copy C:\Program Files\Microsoft Visual Studio 8\VC>mdbg
MDbg (Managed debugger) v2.0.50727.42 (RTM.050727-4200) started.
Copyright (C) Microsoft Corporation. All rights reserved.

For information about commands type "help";
to exit program type "quit".
mdbg>

The mdbg> prompt indicates that you are in the debugger.

Once you are in the debugger, use the commands and arguments described in the previous section.


2010-11-27 12:31
0
雪    币: 370
活跃值: (15)
能力值: ( LV9,RANK:170 )
在线值:
发帖
回帖
粉丝
3
http://msdn.microsoft.com/en-us/library/ms229861.aspx


MDbg.exe (.NET Framework Command-Line Debugger)
.NET Framework 4 Other Versions .NET Framework 3.5
.NET Framework 2.0

The NET Framework Command-Line Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET Framework common language runtime. This tool uses the runtime debugging API to provide debugging services. You can use MDbg.exe to debug only managed code; there is no support for debugging unmanaged code.

The .NET Framework Command-Line Debugger is automatically installed with both Visual Studio and the Windows SDK. To start the tool, open either the Visual Studio Command Prompt or the Windows SDK CMD Shell. (To open CMD Shell, click Start, click All Programs, click Microsoft Windows SDK v7.0, and then click CMD Shell.) At the command prompt, type the following:

CopyMDbg [ProgramName[arguments]] [options]

Commands
--------------------------------------------------------------------------------

When you are in the debugger (as indicated by the mdbg> prompt), type one of the commands described in the next section:

command [arguments]

MDbg.exe commands are case-sensitive.


Command
Description

ap[rocess] [number]
Switches to another debugged process or prints available processes. The numbers are not real process IDs (PIDs), but a 0-indexed list.

a[ttach] [pid]
Attaches to a process or prints available processes.

b[reak] [ClassName.Method | FileName:LineNo]
Sets a breakpoint at the specified method. Modules are scanned sequentially.

break FileName:LineNo sets a breakpoint at a location in the source.

break ~number sets a breakpoint on a symbol recently displayed with the x command.

break module!ClassName.Method+IlOffset sets a breakpoint on the fully qualified location.

block[ingObjects]
Displays monitor locks, which are blocking threads.

ca[tch] [exceptionType]
Causes the debugger to break on all exceptions, and not just on the unhandled exceptions.

cl[earException]
Marks the current exception as handled so that execution can continue. If the cause of the exception has not been dealt with, the exception may be quickly rethrown.

conf[ig] [option value]
Displays all configurable options and shows how the options are invoked without any optional values. If the option is specified, sets value as the current option. The following options are currently available:

extpath sets the path to search for extensions when the load command is used.

extpath+ adds a path for loading extensions.

del[ete]
Deletes a breakpoint.

de[tach]
Detaches from a debugged process.

d[own] [frames]
Moves the active stack frame down.

echo
Echoes a message to the console.

enableNotif[ication] typeName 0|1
Enables (1) or disables (0) custom notifications for the specified type.

ex[it] [exitcode]
Exits the MDbg.exe shell, and optionally specifies the process exit code.

fo[reach] [OtherCommand]
Performs a command on all threads. OtherCommand is a valid command that operates on one thread; foreach OtherCommand performs the same command on all threads.

f[unceval] [-ad Num] functionName [args ... ]
Performs a function evaluation on the current active thread where the function to evaluate is functionName. The function name must be fully qualified, including namespaces.

The -ad option specifies the application domain to use to resolve the function. If the -ad option is not specified, the application domain for resolution defaults to the application domain where the thread that is used for function evaluation is located.

If the function that is being evaluated is not static, the first parameter passed in should be a this pointer. All application domains are searched for arguments to the function evaluation..

To request a value from an application domain, prefix the variable with the module and application domain name; for example, funceval -ad 0 System.Object.ToString hello.exe#0!MyClass.g_rootRef. This command evaluates the function System.Object.ToString in the application domain 0. Because the ToString method is an instance function, the first parameter must be a this pointer.

g[o]
Causes the program to continue until it encounters a breakpoint, the program exits, or an event (for example, an unhandled exception) causes the program to stop.

h[elp] [command]

-or-

? [command]
Displays a description of all commands or a detailed description of a specified command.

ig[nore] [event]
Causes the debugger to stop on unhandled exceptions only.

int[ercept] FrameNumber
Rolls the debugger back to a specified frame number.

If the debugger encounters an exception, use this command to roll the debugger back to the specified frame number. You can change the program state by using the set command and continue by using the go command.

k[ill]
Stops the active process.

l[ist] [modules | appdomains | assemblies]
Displays the loaded modules, application domains, or assemblies.

lo[ad] assemblyName
Loads an extension in the following manner: The specified assembly is loaded and an attempt is then made to run the static method LoadExtension from the Microsoft.Tools.Mdbg.Extension.Extension type.

log [eventType]
Set or display the events to be logged.

mo[de] [option on/off]
Sets different debugger options. Use mode with no options to get a list of the debugging modes and their current settings.

mon[itorInfo] monitorReference
Displays object monitor lock information.

newo[bj] typeName [arguments...]
Creates a new object of type typeName.

n[ext]
Runs code and moves to the next line (even if the next line includes many function calls).

Opendump pathToDumpFile
Opens the specified dump file for debugging.

o[ut]
Moves to the end of the current function.

pa[th] [pathName]
Searches the specified path for the source files if the location in the binaries is not available.

p[rint] [var] | [-d]
Prints all variables in scope (print), prints the specified variable (print var), or prints the debugger variables (print -d).

printe[xception] [-r]
Prints the last exception on the current thread. Use the –r (recursive) option to traverse the InnerException property on the exception object to get information about the entire chain of exceptions.

pro[cessenum]
Displays the active processes.

q[uit] [exitcode]
Quits the MDbg.exe shell, optionally specifying the process exit code.

re[sume] [* | [~]threadNumber]
Resumes the current thread or the thread specified by the threadNumber parameter.

If the threadNumber parameter is specified as * or if the thread number starts with ~, the command applies to all threads except the one specified by threadNumber.

Resuming a non-suspended thread has no effect.

r[un] [-d(ebug) | -o(ptimize) |-enc] [[path_to_exe] [args_to_exe]]
Stops the current process (if there is one) and starts a new one. If no executable argument is passed, this command runs the program that was previously executed with the run command. If the executable argument is provided, the specified program is run using the optionally supplied arguments.

If class load, module load, and thread start events are ignored (as they are by default), the program stops on the first executable instruction of the main thread.

You can force the debugger to just-in-time (JIT) compile the code by using one of the following three flags:

-d(ebug) disables optimizations. This is the default for MDbg.exe.

-o(ptimize) forces the code to run more like it does outside the debugger, but also makes the debugging experience more difficult. This is the default for use outside the debugger.

-enc enables the Edit and Continue feature but incurs a performance hit.

Set variable=value
Changes the value of any in-scope variable.

You can also create your own debugger variables and assign reference values to them from within your application. These values act as handles to the original value, and even the original value is out of scope. All debugger variables must begin with $ (for example, $var). Clear these handles by setting them to nothing using the following command:

set $var=

Setip [-il] number
Sets the current instruction pointer (IP) in the file to the specified position. If you specify the -il option, the number represents a Microsoft intermediate language (MSIL) offset in the method. Otherwise, the number represents a source line number.

sh[ow] [lines]
Specifies the number of lines to show.

s[tep]
Moves execution into the next function on the current line, or moves to the next line if there is no function to step into.

su[spend] [* | [~]threadNumber]
Suspends the current thread or the thread specified by the threadNumber parameter. If threadNumber is specified as *, the command applies to all threads. If the thread number starts with ~, the command applies to all threads except the one specified by threadNumber. Suspended threads are excluded from running when the process is run by either the go or step command. If there are no non-suspended threads in the process and you issue the go command, the process will not continue. In that case, press CTRL-C to break into the process.

sy[mbol] commandName [commandValue]
Specifies one of the following commands:

symbol path ["value"] - Displays or sets the current symbol path.

symbol addpath "value" - Adds to your current symbol path.

symbol reload ["module"]- Reloads either all symbols or the symbols for the specified module.

symbol list [module] - Shows the currently loaded symbols for either all modules or the specified module.

t[hread] [newThread] [-nick nickname]
The thread command with no parameters displays all managed threads in the current process. Threads are usually identified by their thread numbers; however, if the thread has an assigned nickname, the nickname is displayed instead. You can use the -nick parameter to assign a nickname to a thread.

thread -nick threadName assigns a nickname to the currently running thread.

Nicknames cannot be numbers. If the current thread already has an assigned nickname, the old nickname is replaced with the new one. If the new nickname is an empty string (""), the nickname for the current thread is deleted and no new nickname is assigned to the thread.

u


Moves the active stack frame up.

uwgc[handle] [var] | [address]
Prints the variable tracked by a handle. The handle can be specified by name or address.

when
Displays the currently active when statements.

when delete all | num [num [num …]] - Deletes the when statement specified by the number, or all when statements if all is specified.

when stopReason [specific_condition] do cmd [cmd [cmd …] ] - The stopReason parameter can be one of the following:

StepComplete , ProcessExited, ThreadCreated, BreakpointHit, ModuleLoaded, ClassLoaded, AssemblyLoaded, AssemblyUnloaded, ControlCTrapped, ExceptionThrown, UnhandledExceptionThrown, AsyncStop, AttachComplete, UserBreak, EvalComplete, EvalException, RemapOpportunityReached, NativeStop.

specific_condition can be one of the following:

number - For ThreadCreated and BreakpointHit, triggers action only when stopped by a thread ID/breakpoint number with same value.

[!]name - For ModuleLoaded, ClassLoaded, AssemblyLoaded, AssemblyUnloaded, ExceptionThrown, and UnhandledExceptionThrown, triggers action only when the name matches the name of the stopReason.

specific_condition must be empty for other values of stopReason.

w[here] [-v] [-c depth] [threadID]
Displays debug information about stack frames.

The -v option provides verbose information about each displayed stack frame.

Specifying a number for depth limits how many frames are displayed. Use the all command to display all frames. The default is 100.

If you specify the threadID parameter, you can control which thread is associated with the stack. The default is the current thread only. Use the all command to get all threads.

x [-c numSymbols] [module[!pattern]]
Displays functions that match the pattern for a module.

If numSymbols is specified, the output is limited to the specified number. If ! (indicating a regular expression) is not specified for pattern, all functions are displayed. If module is not provided, all loaded modules are displayed. Symbols (~#) can be used to set breakpoints using the break command.


Remarks
--------------------------------------------------------------------------------

Compile the application to be debugged by using compiler-specific flags that cause your compiler to generate debugging symbols. Refer to your compiler's documentation for more information about these flags. You can debug optimized applications, but some debugging information will be missing. For example, many local variables will not be visible and source lines will be inaccurate.

After you compile your application, type mdbg at the command prompt to start a debugging session, as shown in the following example.

Copy C:\Program Files\Microsoft Visual Studio 8\VC>mdbg
MDbg (Managed debugger) v2.0.50727.42 (RTM.050727-4200) started.
Copyright (C) Microsoft Corporation. All rights reserved.

For information about commands type "help";
to exit program type "quit".
mdbg>

The mdbg> prompt indicates that you are in the debugger.

Once you are in the debugger, use the commands and arguments described in the previous section.


2010-11-27 12:32
0
雪    币: 478
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
4
怎么都是英文啊。。悲剧。。
2010-11-27 12:39
0
游客
登录 | 注册 方可回帖
返回
//