# Debugging Wine

## Introduction

### Processes and threads: in underlying OS and in Windows

Before going into the depths of debugging in Wine, here's a small overview of process and thread handling in Wine. It has to be clear that there are two different beasts: processes/threads from the Unix point of view and processes/threads from a Windows point of view.

Each Windows' thread is implemented as a Unix process (under Linux using the `clone` syscall), meaning that all threads of a same Windows' process share the same (unix) address space.

In the following:

- `W-process` means a process in Windows' terminology

- `U-process` means a process in Unix' terminology

- `W-thread` means a thread in Windows' terminology

A `W-process` is made of one or several `W-threads`. Each `W-thread` is mapped to one and only one `U-process`. All `U-processes` of a same `W-process` share the same address space.

Each Unix process can be identified by two values:

- the Unix process id (`upid` in the following)

- the Windows's thread id (`tid`)

Each Windows' process has also a Windows' process id (`wpid` in the following). It must be clear that `upid` and `wpid` are different and shall not be used instead of the other.

`Wpid` and `tid` are defined (Windows) system wide. They must not be confused with process or thread handles which, as any handle, is an indirection to a system object (in this case process or thread). A same process can have several different handles on the same kernel object. The handles can be defined as local (the values is only valid in a process), or system wide (the same handle can be used by any `W-process`).

### Wine, debugging and WineDbg

When talking of debugging in Wine, there are at least two levels to think of:

- the Windows' debugging API.

- the Wine integrated debugger, dubbed `WineDbg`.

Wine implements most of the Windows' debugging API (the part in `KERNEL32.DLL`, not the one in `IMAGEHLP.DLL`), and allows any program (emulated or Winelib) using that API to debug a `W-process`.

`WineDbg` is a Winelib application making use of this API to allow debugging both any Wine or Winelib applications as well as Wine itself (kernel and all DLLs).

## WineDbg's modes of invocation

### Starting a process

Any application (either a Windows' native executable, or a Winelib application) can be run through `WineDbg`. Command line options and tricks are the same as for wine:

    winedbg telnet.exe
    winedbg "hl.exe -windowed"

### Attaching

`WineDbg` can also be launched without any command line argument: `WineDbg` is started without any attached process. You can get a list of running `W-processes` (and their `wpid`'s) using the `walk process` command, and then, with the `attach` command, pick up the `wpid` of the `W-process` you want to debug. This is a neat feature as it allows you to debug an already started application.

### On exceptions

When something goes wrong, Windows tracks this as an exception. Exceptions exist for segmentation violation, stack overflow, division by zero, etc.

When an exception occurs, Wine checks if the `W-process` is debugged. If so, the exception event is sent to the debugger, which takes care of it: end of the story. This mechanism is part of the standard Windows' debugging API.

If the `W-process` is not debugged, Wine tries to launch a debugger. This debugger (normally `WineDbg`, see III Configuration for more details), at startup, attaches to the `W-process` which generated the exception event. In this case, you are able to look at the causes of the exception, and either fix the causes (and continue further the execution) or dig deeper to understand what went wrong.

If `WineDbg` is the standard debugger, the `pass` and `cont` commands are the two ways to let the process go further for the handling of the exception event.

To be more precise on the way Wine (and Windows) generates exception events, when a fault occurs (segmentation violation, stack overflow...), the event is first sent to the debugger (this is known as a first chance exception). The debugger can give two answers:

continue:

- the debugger had the ability to correct what's generated the exception, and is now able to continue process execution.

pass:

- the debugger couldn't correct the cause of the first chance exception. Wine will now try to walk the list of exception handlers to see if one of them can handle the exception. If no exception handler is found, the exception is sent once again to the debugger to indicate the failure of the exception handling.

since some of Wine's code uses exceptions and `try/catch` blocks to provide some functionality, `WineDbg` can be entered in such cases with segv exceptions. This happens, for example, with `IsBadReadPtr` function. In that case, the `pass` command shall be used, to let the handling of the exception to be done by the `catch` block in `IsBadReadPtr`.

### Interrupting

You can stop the debugger while it's running by hitting Ctrl-C in its window. This will stop the debugged process, and let you manipulate the current context.

### Quitting

Wine supports the new XP APIs, allowing for a debugger to detach from a program being debugged (see `detach` command). Unfortunately, as the debugger cannot, for now, neither clear its internal information, nor restart a new process, the debugger, after detaching itself, cannot do much except being quitted.

## Using the Wine Debugger

This section describes where to start debugging Wine. If at any point you get stuck and want to ask for help, please read the How to Report A Bug section of the Wine Users Guide for information on how to write useful bug reports.

### Crashes

These usually show up like this:

    |Unexpected Windows program segfault - opcode = 8b
    |Segmentation fault in Windows program 1b7:c41.
    |Loading symbols from ELF file /root/wine/wine...
    |....more Loading symbols from ...
    |In 16 bit mode.
    |Register dump:
    | CS:01b7 SS:016f DS:0287 ES:0000
    | IP:0c41 SP:878a BP:8796 FLAGS:0246
    | AX:811e BX:0000 CX:0000 DX:0000 SI:0001 DI:ffff
    |Stack dump:
    |0x016f:0x878a:  0001 016f ffed 0000 0000 0287 890b 1e5b
    |0x016f:0x879a:  01b7 0001 000d 1050 08b7 016f 0001 000d
    |0x016f:0x87aa:  000a 0003 0004 0000 0007 0007 0190 0000
    |0x016f:0x87ba:
    |
    |0050: sel=0287 base=40211d30 limit=0b93f (bytes) 16-bit rw-
    |Backtrace:
    |0 0x01b7:0x0c41 (PXSRV_FONGETFACENAME+0x7c)
    |1 0x01b7:0x1e5b (PXSRV_FONPUTCATFONT+0x2cd)
    |2 0x01a7:0x05aa
    |3 0x01b7:0x0768 (PXSRV_FONINITFONTS+0x81)
    |4 0x014f:0x03ed (PDOXWIN_@SQLCURCB$Q6CBTYPEULN8CBSCTYPE+0x1b1)
    |5 0x013f:0x00ac
    |
    |0x01b7:0x0c41 (PXSRV_FONGETFACENAME+0x7c):  movw        %es:0x38(%bx),%dx

Steps to debug a crash. You may stop at any step, but please report the bug and provide as much of the information gathered to the bug report as feasible.

1. Get the reason for the crash. This is usually an access to an invalid selector, an access to an out of range address in a valid selector, popping a segment register from the stack or the like. When reporting a crash, report this whole crashdump even if it doesn't make sense to you.

   (In this case it is access to an invalid selector, for `%es` is `0000`, as seen in the register dump).

2. Determine the cause of the crash. Since this is usually a primary/secondary reaction to a failed or misbehaving Wine function, rerun Wine with the`WINEDEBUG=+relay` environment variable set. This will generate quite a lot of output, but usually the reason is located in the last call(s). Those lines usually look like this:

       |Call KERNEL.90: LSTRLEN(0227:0692 "text") ret=01e7:2ce7 ds=0227
             ^^^^^^^^^  ^       ^^^^^^^^^ ^^^^^^      ^^^^^^^^^    ^^^^
             |          |       |         |           |            |Datasegment
             |          |       |         |           |Return address
             |          |       |         |textual parameter
             |          |       |
             |          |       |Argument(s). This one is a win16 segmented pointer.
             |          |Function called.
             |The module, the function is called in. In this case it is KERNEL.

       |Ret  KERNEL.90: LSTRLEN() retval=0x0004 ret=01e7:2ce7 ds=0227
                                         ^^^^^^
       				  |Returnvalue is 16 bit and has the value 4.

3. If you have found a misbehaving function, try to find out why it misbehaves. Find the function in the source code. Try to make sense of the arguments passed. Usually there is a `WINE_DEFAULT_DEBUG_CHANNEL(<channel>);` at the beginning of the file. Rerun wine with the `WINEDEBUG=+xyz,+relay` environment variable set.

   Occasionally there are additional debug channels defined at the beginning of the file in the form. `WINE_DECLARE_DEBUG_CHANNEL(<channel>);` If so the offending function may also uses one of these alternate channels. Look through the the function for `TRACE_(<channel>)(" ... /n");` and add any additional channels to the commandline.

4. Additional information on how to debug using the internal debugger can be found in `programs/winedbg/README`.

5. If this information isn't clear enough or if you want to know more about what's happening in the function itself, try running wine with `WINEDEBUG=+all`, which dumps ALL included debug information in wine.

6. If even that isn't enough, add more debug output for yourself into the functions you find relevant. See The section on Debug Logging in this guide for more information. You might also try to run the program in `gdb` instead of using the Wine debugger. If you do that, use `handle SIGSEGV nostop noprint` to disable the handling of seg faults inside `gdb` (needed for Win16).

7. You can also set a breakpoint for that function. Start wine useing `winedbg` instead of `wine`. Once the debugger is is running enter `break` `KERNEL_LSTRLEN` (replace by function you want to debug, CASE IS RELEVANT) to set a breakpoint. Then use `continue` to start normal program-execution. Wine will stop if it reaches the breakpoint. If the program isn't yet at the crashing call of that function, use `continue` again until you are about to enter that function. You may now proceed with single-stepping the function until you reach the point of crash. Use the other debugger commands to print registers and the like.

### Program hangs, nothing happens

Start the program with `winedbg` instead of `wine`. When the program locks up switch to the winedbg terminal and press Ctrl C. this will stop the program and let you debug the program as you would for a crash.

### Program reports an error with a Messagebox

Sometimes programs are reporting failure using more or less nondescript messageboxes. We can debug this using the same method as Crashes, but there is one problem... For setting up a message box the program also calls Wine producing huge chunks of debug code.

Since the failure happens usually directly before setting up the Messagebox you can start winedbg and set a breakpoint at `MessageBoxA` (called by win16 and win32 programs) and proceed with `continue`. With `WINEDEBUG=+all` Wine will now stop directly before setting up the Messagebox. Proceed as explained above.

You can also run wine using `WINEDEBUG=+relay wine program.exe 2>&1 | less -i` and in `less` search for MessageBox.

### Disassembling programs:

You may also try to disassemble the offending program to check for undocumented features and/or use of them.

The best, freely available, disassembler for Win16 programs is Windows Codeback, archive name `wcbxxx.zip` (e.g. `wcb105a.zip`), which usually can be found in the `Cica-Mirror` subdirectory on the Wine ftp sites. (See `ANNOUNCE`).

Disassembling win32 programs is possible using Windows Disassembler 32. Look for a file called `w32dsm87.zip` (or similar) on http://www.winsite.com and mirrors. The shareware version does not allow saving of disassembly listings. You can also use the newer (and in the full version better) Interactive Disassembler (IDA) from the ftp sites mentioned at the end of the document. Understanding disassembled code is mostly a question of exercise.

Most code out there uses standard C function entries (for it is usually written in C). Win16 function entries usually look like that:

    push bp
    mov bp, sp
    ... function code ..
    retf XXXX 	<--------- XXXX is number of bytes of arguments

This is a `FAR` function with no local storage. The arguments usually start at `[bp+6]` with increasing offsets. Note, that `[bp+6]` belongs to the rightmost argument, for exported win16 functions use the PASCAL calling convention. So, if we use `strcmp(a,b)` with `a` and `b` both 32 bit variables `b` would be at `[bp+6]` and `a` at `[bp+10]`.

Most functions make also use of local storage in the stackframe:

    enter 0086, 00
    ... function code ...
    leave
    retf XXXX

This does mostly the same as above, but also adds `0x86` bytes of stackstorage, which is accessed using `[bp-xx]`. Before calling a function, arguments are pushed on the stack using something like this:

    push word ptr [bp-02]	<- will be at [bp+8]
    push di			<- will be at [bp+6]
    call KERNEL.LSTRLEN

Here first the selector and then the offset to the passed string are pushed.

### Sample debugging session:

Let's debug the infamous Word `SHARE.EXE` messagebox:

    |marcus@jet $ wine winword.exe
    |            +---------------------------------------------+
    |            | !  You must leave Windows and load SHARE.EXE|
    |            |    before starting Word.                    |
    |            +---------------------------------------------+

    |marcus@jet $ WINEDEBUG=+relay,-debug wine winword.exe
    |CallTo32(wndproc=0x40065bc0,hwnd=000001ac,msg=00000081,wp=00000000,lp=00000000)
    |Win16 task 'winword': Breakpoint 1 at 0x01d7:0x001a
    |CallTo16(func=0127:0070,ds=0927)
    |Call WPROCS.24: TASK_RESCHEDULE() ret=00b7:1456 ds=0927
    |Ret  WPROCS.24: TASK_RESCHEDULE() retval=0x8672 ret=00b7:1456 ds=0927
    |CallTo16(func=01d7:001a,ds=0927)
    |     AX=0000 BX=3cb4 CX=1f40 DX=0000 SI=0000 DI=0927 BP=0000 ES=11f7
    |Loading symbols: /home/marcus/wine/wine...
    |Stopped on breakpoint 1 at 0x01d7:0x001a
    |In 16 bit mode.
    |Wine-dbg>break MessageBoxA                          <---- Set Breakpoint
    |Breakpoint 2 at 0x40189100 (MessageBoxA [msgbox.c:190])
    |Wine-dbg>c                                            <---- Continue
    |Call KERNEL.91: INITTASK() ret=0157:0022 ds=08a7
    |     AX=0000 BX=3cb4 CX=1f40 DX=0000 SI=0000 DI=08a7 ES=11d7 EFL=00000286
    |CallTo16(func=090f:085c,ds=0dcf,0x0000,0x0000,0x0000,0x0000,0x0800,0x0000,0x0000,0x0dcf)
    |...                                                   <----- Much debugoutput
    |Call KERNEL.136: GETDRIVETYPE(0x0000) ret=060f:097b ds=0927
                                   ^^^^^^ Drive 0 (A:)
    |Ret  KERNEL.136: GETDRIVETYPE() retval=0x0002 ret=060f:097b ds=0927
                                            ^^^^^^  DRIVE_REMOVEABLE
    						(It is a floppy diskdrive.)

    |Call KERNEL.136: GETDRIVETYPE(0x0001) ret=060f:097b ds=0927
                                   ^^^^^^ Drive 1 (B:)
    |Ret  KERNEL.136: GETDRIVETYPE() retval=0x0000 ret=060f:097b ds=0927
                                            ^^^^^^  DRIVE_CANNOTDETERMINE
    						(I don't have drive B: assigned)

    |Call KERNEL.136: GETDRIVETYPE(0x0002) ret=060f:097b ds=0927
                                   ^^^^^^^ Drive 2 (C:)
    |Ret  KERNEL.136: GETDRIVETYPE() retval=0x0003 ret=060f:097b ds=0927
                                            ^^^^^^ DRIVE_FIXED
                                                   (specified as a harddisk)

    |Call KERNEL.97: GETTEMPFILENAME(0x00c3,0x09278364"doc",0x0000,0927:8248) ret=060f:09b1 ds=0927
                                     ^^^^^^           ^^^^^        ^^^^^^^^^
                                     |                |            |buffer for fname
                                     |                |temporary name ~docXXXX.tmp
                                     |Force use of Drive C:.

    |Warning: GetTempFileName returns 'C:~doc9281.tmp', which doesn't seem to be writeable.
    |Please check your configuration file if this generates a failure.

Whoops, it even detects that something is wrong!

    |Ret  KERNEL.97: GETTEMPFILENAME() retval=0x9281 ret=060f:09b1 ds=0927
                                              ^^^^^^ Temporary storage ID

    |Call KERNEL.74: OPENFILE(0x09278248"C:~doc9281.tmp",0927:82da,0x1012) ret=060f:09d8 ds=0927
                                        ^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^^^^^
                                        |filename        |OFSTRUCT |open mode:

                                           OF_CREATE|OF_SHARE_EXCLUSIVE|OF_READWRITE

This fails, since my C: drive is in this case mounted readonly.

    |Ret  KERNEL.74: OPENFILE() retval=0xffff ret=060f:09d8 ds=0927
                                       ^^^^^^ HFILE_ERROR16, yes, it failed.

    |Call USER.1: MESSAGEBOX(0x0000,0x09278376"You must close Windows and load SHARE.EXE before you start Word.",0x00000000,0x1030) ret=060f:084f ds=0927

And MessageBox'ed.

    |Stopped on breakpoint 2 at 0x40189100 (MessageBoxA [msgbox.c:190])
    |190     {		<- the sourceline
    In 32 bit mode.
    Wine-dbg>

The code seems to find a writeable harddisk and tries to create a file there. To work around this bug, you can define C: as a networkdrive, which is ignored by the code above.

### Debugging Tips

Here are some additional debugging tips:

- If you have a program crashing at such an early loader phase that you can't use the Wine debugger normally, but Wine already executes the program's start code, then you may use a special trick. You should do a

      WINEDEBUG=+relay wine program

  to get a listing of the functions the program calls in its start function. Now you do a

      winedbg winfile.exe

  This way, you get into `winedbg`. Now you can set a breakpoint on any function the program calls in the start function and just type `c` to bypass the eventual calls of Winfile to this function until you are finally at the place where this function gets called by the crashing start function. Now you can proceed with your debugging as usual.

- If you try to run a program and it quits after showing an error messagebox, the problem can usually be identified in the return value of one of the functions executed before `MessageBox()`. That's why you should re-run the program with e.g.

      WINEDEBUG=+relay wine  <program name> &>relmsg

  Then do a `more relmsg` and search for the last occurrence of a call to the string "MESSAGEBOX". This is a line like

      Call USER.1: MESSAGEBOX(0x0000,0x01ff1246 "Runtime error 219 at 0004:1056.",0x00000000,0x1010) ret=01f7:2160 ds=01ff

  In my example the lines before the call to `MessageBox()` look like that:

      Call KERNEL.96: FREELIBRARY(0x0347) ret=01cf:1033 ds=01ff
      CallTo16(func=033f:0072,ds=01ff,0x0000)
      Ret  KERNEL.96: FREELIBRARY() retval=0x0001 ret=01cf:1033 ds=01ff
      Call KERNEL.96: FREELIBRARY(0x036f) ret=01cf:1043 ds=01ff
      CallTo16(func=0367:0072,ds=01ff,0x0000)
      Ret  KERNEL.96: FREELIBRARY() retval=0x0001 ret=01cf:1043 ds=01ff
      Call KERNEL.96: FREELIBRARY(0x031f) ret=01cf:105c ds=01ff
      CallTo16(func=0317:0072,ds=01ff,0x0000)
      Ret  KERNEL.96: FREELIBRARY() retval=0x0001 ret=01cf:105c ds=01ff
      Call USER.171: WINHELP(0x02ac,0x01ff05b4 "COMET.HLP",0x0002,0x00000000) ret=01cf:1070 ds=01ff
      CallTo16(func=0117:0080,ds=01ff)
      Call WPROCS.24: TASK_RESCHEDULE() ret=00a7:0a2d ds=002b
      Ret  WPROCS.24: TASK_RESCHEDULE() retval=0x0000 ret=00a7:0a2d ds=002b
      Ret  USER.171: WINHELP() retval=0x0001 ret=01cf:1070 ds=01ff
      Call KERNEL.96: FREELIBRARY(0x01be) ret=01df:3e29 ds=01ff
      Ret  KERNEL.96: FREELIBRARY() retval=0x0000 ret=01df:3e29 ds=01ff
      Call KERNEL.52: FREEPROCINSTANCE(0x02cf00ba) ret=01f7:1460 ds=01ff
      Ret  KERNEL.52: FREEPROCINSTANCE() retval=0x0001 ret=01f7:1460 ds=01ff
      Call USER.1: MESSAGEBOX(0x0000,0x01ff1246 "Runtime error 219 at 0004:1056.",0x00000000,0x1010) ret=01f7:2160 ds=01ff

  I think that the call to `MessageBox()` in this example is not caused by a wrong result value of some previously executed function (it's happening quite often like that), but instead the messagebox complains about a runtime error at `0x0004:0x1056`.

  As the segment value of the address is only `4`, I think that that is only an internal program value. But the offset address reveals something quite interesting: Offset `1056` is very close to the return address of `FREELIBRARY()`:

      Call KERNEL.96: FREELIBRARY(0x031f) ret=01cf:105c ds=01ff
                                                   ^^^^

  Provided that segment `0x0004` is indeed segment `0x1cf`, we now we can use IDA (available at http://www.filelibrary.com:8080/cgi-bin/freedownload/DOS/h/72/ida35bx.zip) to disassemble the part that caused the error. We just have to find the address of the call to `FreeLibrary()`. Some lines before that the runtime error occurred. But be careful! In some cases you don't have to disassemble the main program, but instead some DLL called by it in order to find the correct place where the runtime error occurred. That can be determined by finding the origin of the segment value (in this case `0x1cf`).

- If you have created a relay file of some crashing program and want to set a breakpoint at a certain location which is not yet available as the program loads the breakpoint's segment during execution, you may set a breakpoint to `GetVersion16/32` as those functions are called very often.

  Then do a `c` until you are able to set this breakpoint without error message.

- Some useful programs:

  IDA: `http://www.filelibrary.com:8080/cgi-bin/freedownload/DOS/h/72/ida35bx.zip`

- Very good DOS disassembler ! It's badly needed for debugging Wine sometimes.

XRAY: `http://garbo.uwasa.fi/pub/pc/sysinfo/xray15.zip`

- Traces DOS calls (Int 21h, DPMI, ...). Use it with Windows to correct file management problems etc.

pedump: `ftp://ftp.simtel.net/pub/simtelnet/win95/prog/pedump.zip`

- Dumps the imports and exports of a PE (Portable Executable) DLL.

winedump:

- Dumps the imports and exports of a PE (Portable Executable) DLL (included in wine tree).

### Some basic debugger usages:

After starting your program with

    wine -debug myprog.exe

the program loads and you get a prompt at the program starting point. Then you can set breakpoints:

      b RoutineName      (by outine name) OR
      b *0x812575        (by address)

Then you hit `c` (continue) to run the program. It stops at the breakpoint. You can type

      step               (to step one line) OR
      stepi              (to step one machine instruction at a time;
                          here, it helps to know the basic 386
                          instruction set)
      info reg           (to see registers)
      info stack         (to see hex values in the stack)
      info local         (to see local variables)
      list <line number> (to list source code)
      x <variable name>  (to examine a variable; only works if code
                          is not compiled with optimization)
      x 0x4269978        (to examine a memory location)
      ?                  (help)
      q                  (quit)

By hitting Enter, you repeat the last command.

## Useful memory addresses

Wine uses several different kinds of memory addresses.

Win32/"normal" Wine addresses/Linux: linear addresses.

- Linear addresses can be everything from 0x0 up to 0xffffffff. In Wine on Linux they are often around e.g. 0x08000000, 0x00400000 (std. Win32 program load address), 0x40000000. Every Win32 process has its own private 4GB address space (that is, from 0x0 up to 0xffffffff).

Win16 "enhanced mode": segmented addresses.

- These are the "normal" Win16 addresses, called SEGPTR. They have a segment:offset notation, e.g. 0x01d7:0x0012. The segment part usually is a "selector", which always has the lowest 3 bits set. Some sample selectors are 0x1f7, 0x16f, 0x8f. If these bits are set except for the lowest bit, as e.g. with 0x1f6,xi then it might be a handle to global memory. Just set the lowest bit to get the selector in these cases. A selector kind of "points" to a certain linear (see above) base address. It has more or less three important attributes: segment base address, segment limit, segment access rights.

  Example:

  Selector 0x1f7 (0x40320000, 0x0000ffff, r-x) So 0x1f7 has a base address of 0x40320000, the segment's last address is 0x4032ffff (limit 0xffff), and it's readable and executable. So an address of 0x1f7:0x2300 would be the linear address of 0x40322300.

DOS/Win16 "standard mode"

- They, too, have a segment:offset notation. But they are completely different from "normal" Win16 addresses, as they just represent at most 1MB of memory: The segment part can be anything from 0 to 0xffff, and it's the same with the offset part.

  Now the strange thing is the calculation that's behind these addresses: Just calculate segment*16 + offset in order to get a "linear DOS" address. So e.g. 0x0f04:0x3628 results in 0xf040 + 0x3628 = 0x12668. And the highest address you can get is 0xfffff (1MB), of course. In Wine, this "linear DOS" address of 0x12668 has to be added to the linear base address of the corresponding DOS memory allocated for dosmod in order to get the true linear address of a DOS seg:offs address. And make sure that you're doing this in the correct process with the correct linear address space, of course ;-)

## Configuration

### Registry configuration

The Windows' debugging API uses a registry entry to know which debugger to invoke when an unhandled exception occurs (see for some details). Two values in key

    "MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug"

Determine the behavior:

Debugger:

- this is the command line used to launch the debugger (it uses two `printf` formats (`%ld`) to pass context dependent information to the debugger). You should put here a complete path to your debugger (`WineDbg` can of course be used, but any other Windows' debugging API aware debugger will do). The path to the debugger you chose to use must be reachable via a DOS drive in the Wine config file !

Auto:

- if this value is zero, a message box will ask the user if he/she wishes to launch the debugger when an unhandled exception occurs. Otherwise, the debugger is automatically started.

A regular Wine registry looks like:

    [MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug] 957636538
    "Auto"=dword:00000001
    "Debugger"="winedbg %ld %ld"

#### Note 1

creating this key is mandatory. Not doing so will not fire the debugger when an exception occurs.

#### Note 2

`wineinstall` (available in Wine source) sets up this correctly. However, due to some limitation of the registry installed, if a previous Wine installation exists, it's safer to remove the whole

    [MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug]

key before running again `wineinstall` to regenerate this key.

### WineDbg configuration

`WineDbg` can be configured through a number of options. Those options are stored in the registry, on a per user basis. The key is (in my registry)

    [eric\\Software\\Wine\\WineDbg]

Those options can be read/written while inside `WineDbg`, as part of the debugger expressions. To refer to one of these options, its name must be prefixed by a `$` sign. For example,

    set $BreakAllThreadsStartup = 1

sets the option `BreakAllThreadsStartup` to `TRUE`.

All the options are read from the registry when `WineDbg` starts (if no corresponding value is found, a default value is used), and are written back to the registry when `WineDbg` exits (hence, all modifications to those options are automatically saved when `WineDbg` terminates).

Here's the list of all options:

#### Controlling when the debugger is entered

`BreakAllThreadsStartup`

- Set to `TRUE` if at all threads start-up the debugger stops set to `FALSE` if only at the first thread startup of a given process the debugger stops. `FALSE` by default.

`BreakOnCritSectTimeOut`

- Set to `TRUE` if the debugger stops when a critical section times out (5 minutes); `TRUE` by default.

`BreakOnAttach`

- Set to `TRUE` if when `WineDbg` attaches to an existing process after an unhandled exception, `WineDbg` shall be entered on the first attach event. Since the attach event is meaningless in the context of an exception event (the next event which is the exception event is of course relevant), that option is likely to be `FALSE`.

`BreakOnFirstChance`

- An exception can generate two debug events. The first one is passed to the debugger (known as a first chance) just after the exception. The debugger can then decides either to resume execution (see `WineDbg`'s `cont` command) or pass the exception up to the exception handler chain in the program (if it exists) (`WineDbg` implements this through the `pass` command). If none of the exception handlers takes care of the exception, the exception event is sent again to the debugger (known as last chance exception). You cannot pass on a last exception. When the `BreakOnFirstChance` exception is `TRUE`, then winedbg is entered for both first and last chance execptions (to `FALSE`, it's only entered for last chance exceptions).

`BreakOnDllLoad`

- Set to `TRUE` if the debugger stops when a DLL is loaded into memory; when the debugger is invoked after a crash, the DLLs already mapped in memory will not trigger this break. `FALSE` by default.

#### Context information

`ThreadId`

- ID of the `W-thread` currently examined by the debugger

`ProcessId`

- ID of the `W-thread` currently examined by the debugger

<registers>

- All CPU registers are also available

The `ThreadId` and `ProcessId` variables can be handy to set conditional breakpoints on a given thread or process.

## WineDbg Command Reference

### Misc

    abort		aborts the debugger
    quit		exits the debugger

    attach N	attach to a W-process (N is its ID, numeric or hexadecimal(0xN)).
    		IDs can be obtained using the walk process command.  Note the
    		walk process command returns hexadecimal values
    detach          detach from a W-process. WineDbg will exit (this may
                    be changed later on)

    help		prints some help on the commands
    help info	prints some help on info commands

    mode 16		switch to 16 bit mode
    mode 32		switch to 32 bit mode

### Flow control

    cont		continue execution until next breakpoint or exception.
    pass		pass the exception event up to the filter chain.
    step		continue execution until next C line of code (enters
    		function call)
    next 		continue execution until next C line of code (doesn't
    		enter function call)
    stepi		execute next assembly instruction (enters function
    		call)
    nexti		execute next assembly instruction (doesn't enter
    		function call)
    finish		do nexti commands until current function is exited

cont, step, next, stepi, nexti can be postfixed by a number (N), meaning that the command must be executed N times.

### Breakpoints, watch points

    enable N	enables (break|watch)point #N
    disable N	disables (break|watch)point #N
    delete N	deletes  (break|watch)point #N
    cond N		removes any a existing condition to (break|watch)point N
    cond N <expr>	adds condition <expr> to (break|watch)point N. <expr>
    		will be evaluated each time the breakpoint is hit. If
    		the result is a zero value, the breakpoint isn't
    		triggered
    break * N	adds a breakpoint at address N
    break <id>	adds a breakpoint at the address of symbol <id>
    break <id> N	adds a breakpoint at the address of symbol <id> (N ?)
    break N		adds a breakpoint at line N of current source file
    break		adds a breakpoint at current $pc address
    watch * N	adds a watch command (on write) at address N (on 4 bytes)
    watch <id>	adds a watch command (on write) at the address of
    		symbol <id>
    info break	lists all (break|watch)points (with state)

When setting a breakpoint on an <id>, if several symbols with this <id> exist, the debugger will prompt for the symbol you want to use. Pick up the one you want from its number.

Alternatively you can specify a DLL in the <id> (for example MYDLL.DLL.myFunc for function myFunc of `G:\AnyPath\MyDll.dll)`.

You can use the symbol EntryPoint to stand for the entry point of the Dll.

When setting a break/watch-point by <id>, if the symbol cannot be found (for example, the symbol is contained in a not yet loaded module), winedbg will recall the name of the symbol and will try to set the breakpoint each time a new module is loaded (until it succeeds).

### Stack manipulation

    bt		print calling stack of current thread
    bt N		print calling stack of thread of ID N (note: this
                    doesn't change the position of the current frame as
    		manipulated by the up & dn commands)
    up		goes up one frame in current thread's stack
    up N		goes up N frames in current thread's stack
    dn		goes down one frame in current thread's stack
    dn N		goes down N frames in current thread's stack
    frame N		set N as the current frame for current thread's stack
    info local	prints information on local variables for current
    		function

### Directory & source file manipulation

    show dir
    dir <pathname>
    dir
    symbolfile <pathname>   loads external symbol definition
    symbolfile <pathname> N loads external symbol definition
                               (applying an offset of N to addresses)

    list		lists 10 source lines from current position
    list - 		lists 10 source lines before current position
    list N		lists 10 source lines from line N in current file
    list <path>:N	lists 10 source lines from line N in file <path>
    list <id>	lists 10 source lines of function <id>
    list * N	lists 10 source lines from address N

You can specify the end target (to change the 10 lines value) using the ','. For example:

    list 123, 234 	lists source lines from line 123 up to line 234 in
    		current file
    list foo.c:1,56	lists source lines from line 1 up to 56 in file foo.c

### Displaying

A display is an expression that's evaluated and printed after the execution of any `WineDbg` command.

    display		lists the active displays
    info display	(same as above command)
    display <expr>	adds a display for expression <expr>
    display /fmt <expr>	adds a display for expression <expr>. Printing
    		evaluated <expr> is done using the given format (see
    		print command for more on formats)
    del display N	deletes display #N
    undisplay N	(same as del display)

### Disassembly

    disas		disassemble from current position
    disas <expr>	disassemble from address <expr>
    disas <expr>,<expr>disassembles code between addresses specified by
    		the two <expr>

### Information on Wine's internals

    info class <id> prints information on Windows's class <id>
    walk class	lists all Windows' class registered in Wine
    info share	lists all the dynamic libraries loaded the debugged
    		program (including .so files, NE and PE DLLs)
    info module <N> prints information on module of handle <N>
    walk module	lists all modules loaded by debugged program
    info regs	prints the value of CPU register
    info segment <N>prints information on segment <N>
    info segment	lists all allocated segments
    info stack	prints the values on top of the stack
    walk map	lists all virtual mappings used by the debugged
    		program
    walk map <N>    lists all virtual mappings used by the program of pid <N>
    info wnd <N>    prints information of Window of handle <N>
    walk wnd	lists all the window hierarchy starting from the
    		desktop window
    walk wnd <N>    lists all the window hierarchy starting from the
    		window of handle <N>
    walk process	lists all w-processes in Wine session
    walk thread	lists all w-threads in Wine session
    walk exception  lists the exception frames (starting from current
                    stack frame)

### Memory (reading, writing, typing)

    x <expr>	examines memory at <expr> address
    x /fmt <expr>	examines memory at <expr> address using format /fmt
    print <expr>	prints the value of <expr> (possibly using its type)
    print /fmt <expr>	prints the value of <expr> (possibly using its
    		type)
    set <lval>=<expr>	writes the value of <expr> in <lval>
    whatis <expr>	prints the C type of expression <expr>

`/fmt` is either `/<letter>` or `/<count><letter>` letter can be

    s => an ASCII string
    u => an Unicode UTF16 string
    i => instructions (disassemble)
    x => 32 bit unsigned hexadecimal integer
    d => 32 bit signed decimal integer
    w => 16 bit unsigned hexadecimal integer
    c => character (only printable 0x20-0x7f are actually printed)
    b => 8 bit unsigned hexadecimal integer
    g => GUID

### Expressions

Expressions in Wine Debugger are mostly written in a C form. However, there are a few discrepancies:

- Identifiers can take a '.' in their names. This allow mainly to access symbols from different DLLs like `USER32.DLL.CreateWindowA`.

- The debugger will try to distinguish this writing with structure operations. Therefore, you can only use the previous writing in operations manipulating symbols ({break|watch}points, type information command...).

### Debug channels

It is possible to turn on and off debug messages as you are debugging using the set command.

    set + warn win	=> turn on warn on 'win' channel
    set + win	=> turn on warn/fixme/err/trace on 'win' channel
    set - win	=> turn off warn/fixme/err/trace on 'win' channel
    set - fixme	=> turn off the 'fixme' class

## Other debuggers

### GDB mode

WineDbg can act as a remote monitor for GDB. This allows to use all the power of GDB, but while debugging wine and/or any Win32 application. To enable this mode, just add `--gdb` to winedbg command line. You'll end up on a GDB prompt. You'll have to use the GDB commands (not the wine nes).

However, some limitation in GDB while debugging wine (see below) don't appear in this mode:

- GDB will correctly present Win32 thread information and breakpoint behavior

- Moreover, it also provides support for the Dwarf II debug format (which became the default format (instead of stabs) in gcc 3.1).

A few wine extensions available through the monitor command.

    monitor wnd           lists all window in the Wine session
    monitor proc          lists all processes in the Wine session
    monitor mem           displays memory mapping of debugged process
                          (doesn't work)

### Graphical frontends to gdb

This section will describe how you can debug wine using the GDB mode of winedbg and some graphical front ends to GDB for those of you who really like graphical debuggers.

#### DDD

Use the following steps, in this order:

1. Start the wine debugger with a command line like:

       	winedbg -- --gdb --no-start <name_of_exe_to_debug.exe>

2. Start ddd

3. In ddd, use the 'Open File' or 'Open Program' to point to the wine executable

4. In the output of 1/, there's a line like

       	target remote localhost:32878

   copy that line and paste into ddd command pane (the one with the (gdb) prompt)

The program should now be loaded and up and running. If you want, you can also add in 1/ after the name of the exec all the needed parameters

#### kdbg

Use the following steps, in this order:

1. Start the wine debugger with a command line like:

       	winedbg -- --gdb --no-start <name_of_exe_to_debug.exe>

2. In the output of 1/, there's a line like

       	target remote localhost:32878

   Start kdbg with

       kdbg -r localhost:32878 wine

   localhost:32878 is not a fixed value, but has been printed in step 1/. 'wine' should also be the full path to the wine executable.

The program should now be loaded and up and running. If you want, you can also add in 1/ after the name of the exec all the needed parameters

### Using other Unix debuggers

You can also use other debuggers (like `gdb`), but you must be aware of a few items:

You need to attach the unix debugger to the correct unix process (representing the correct windows thread) (you can "guess" it from a `ps fax` for example: When running the emulator, usually the first two `upids` are for the Windows' application running the desktop, the first thread of the application is generally the third `upid`; when running a Winelib program, the first thread of the application is generally the first `upid`)

Even if latest `gdb` implements the notion of threads, it won't work with Wine because the thread abstraction used for implementing Windows' thread is not 100% mapped onto the Linux POSIX threads implementation. It means that you'll have to spawn a different `gdb` session for each Windows' thread you wish to debug.

Here's how to get info about the current execution status of a certain Wine process:

Change into your Wine source dir and enter:

    $ gdb wine

Switch to another console and enter `ps ax | grep wine` to find all wine processes. Inside `gdb`, repeat for all Wine processes:

    (gdb) attach PID

with `PID` being the process ID of one of the Wine processes. Use

    (gdb) bt

to get the backtrace of the current Wine process, i.e. the function call history. That way you can find out what the current process is doing right now. And then you can use several times:

    (gdb) n

or maybe even

    (gdb) b SomeFunction

and

    (gdb) c

to set a breakpoint at a certain function and continue up to that function. Finally you can enter

    (gdb) detach

to detach from the Wine process.

### Using other Windows debuggers

You can use any Windows' debugging API compliant debugger with Wine. Some reports have been made of success with VisualStudio debugger (in remote mode, only the hub runs in Wine). GoVest fully runs in Wine.

### Main differences between winedbg and regular Unix debuggers

### Debuggers comparison

WineDbg | gdb
WineDbg debugs a Windows' process: the various threads will be handled by the same WineDbg session, and a breakpoint will be triggered for any thread of the W-process | gdb debugs a Windows' thread: a separate gdb session is needed for each thread of a Windows' process and a breakpoint will be triggered only for the w-thread debugged
WineDbg supports debug information from stabs (standard Unix format) and Microsoft's C, CodeView, .DBG | GDB supports debug information from stabs (standard Unix format) and Dwarf II.

## Limitations

- 16 bit processes are not supported (but calls to 16 bit code in 32 bit applications are).

- Function call in expression is no longer supported