Add all needed accelerators to regedit. Cleanups.
[wine] / programs / winedbg / winedbg.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /* Wine internal debugger
4  * Interface to Windows debugger API
5  * Copyright 2000 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include "debugger.h"
30
31 #include "wincon.h"
32 #include "winreg.h"
33 #include "wingdi.h"
34 #include "winuser.h"
35 #include "winternl.h"
36 #include "excpt.h"
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "winnls.h"
40
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
44
45 DBG_PROCESS*    DEBUG_CurrProcess = NULL;
46 DBG_THREAD*     DEBUG_CurrThread = NULL;
47 DWORD           DEBUG_CurrTid;
48 DWORD           DEBUG_CurrPid;
49 CONTEXT         DEBUG_context;
50 BOOL            DEBUG_InteractiveP = FALSE;
51 static BOOL     DEBUG_InException = FALSE;
52 int             curr_frame = 0;
53 static char*    DEBUG_LastCmdLine = NULL;
54
55 static DBG_PROCESS* DEBUG_ProcessList = NULL;
56 static enum {none_mode = 0, winedbg_mode, automatic_mode, gdb_mode} local_mode;
57
58 DBG_INTVAR DEBUG_IntVars[DBG_IV_LAST];
59
60 void    DEBUG_OutputA(const char* buffer, int len)
61 {
62     WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, NULL, NULL);
63 }
64
65 void    DEBUG_OutputW(const WCHAR* buffer, int len)
66 {
67         char* ansi = NULL;
68         int newlen;
69         
70         /* do a serious Unicode to ANSI conversion
71            FIXME: should CP_ACP be GetConsoleCP()? */
72         newlen = WideCharToMultiByte(CP_ACP, 0, buffer, len, NULL, 0, NULL, NULL);
73         if(newlen)
74         {
75                 ansi = (char*)DBG_alloc(newlen);
76                 if(ansi)
77                 {
78                         WideCharToMultiByte(CP_ACP, 0, buffer, len, ansi, newlen, NULL, NULL);
79                 }
80         }
81         
82         /* fall back to a simple Unicode to ANSI conversion in case WC2MB failed */
83         if(!ansi)
84         {
85                 ansi = DBG_alloc(len);
86                 if(ansi)
87                 {
88                         int i;
89                         for(i = 0; i < len; i++)
90                         {
91                                 ansi[i] = (char)buffer[i];
92                         }
93                         
94                         newlen = len;
95                 }
96                 /* else we are having REALLY bad luck today */
97         }       
98         
99         if(ansi)
100         {
101                 DEBUG_OutputA(ansi, newlen);
102                 DBG_free(ansi);
103         }
104 }
105
106 int     DEBUG_Printf(const char* format, ...)
107 {
108 static    char  buf[4*1024];
109     va_list     valist;
110     int         len;
111
112     va_start(valist, format);
113     len = vsnprintf(buf, sizeof(buf), format, valist);
114     va_end(valist);
115
116     if (len <= -1 || len >= sizeof(buf)) {
117         len = sizeof(buf) - 1;
118         buf[len] = 0;
119         buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
120     }
121     DEBUG_OutputA(buf, len);
122     return len;
123 }
124
125 static  BOOL DEBUG_IntVarsRW(int read)
126 {
127     HKEY        hkey;
128     DWORD       type = REG_DWORD;
129     DWORD       val;
130     DWORD       count = sizeof(val);
131     int         i;
132     DBG_INTVAR* div = DEBUG_IntVars;
133
134     if (read) {
135 /* initializes internal vars table */
136 #define  INTERNAL_VAR(_var,_val,_ref,_typ)                      \
137         div->val = _val; div->name = #_var; div->pval = _ref;   \
138         div->type = DEBUG_GetBasicType(_typ); div++;
139 #include "intvar.h"
140 #undef   INTERNAL_VAR
141     }
142
143     if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) {
144         WINE_ERR("Cannot create WineDbg key in registry\n");
145         return FALSE;
146     }
147
148     for (i = 0; i < DBG_IV_LAST; i++) {
149         if (read) {
150             if (!DEBUG_IntVars[i].pval) {
151                 if (!RegQueryValueEx(hkey, DEBUG_IntVars[i].name, 0,
152                                      &type, (LPSTR)&val, &count))
153                     DEBUG_IntVars[i].val = val;
154                 DEBUG_IntVars[i].pval = &DEBUG_IntVars[i].val;
155             } else {
156                 *DEBUG_IntVars[i].pval = 0;
157             }
158         } else {
159             /* FIXME: type should be infered from basic type -if any- of intvar */
160             if (DEBUG_IntVars[i].pval == &DEBUG_IntVars[i].val)
161                 RegSetValueEx(hkey, DEBUG_IntVars[i].name, 0,
162                               type, (LPCVOID)DEBUG_IntVars[i].pval, count);
163         }
164     }
165     RegCloseKey(hkey);
166     return TRUE;
167 }
168
169 DBG_INTVAR*     DEBUG_GetIntVar(const char* name)
170 {
171     int         i;
172
173     for (i = 0; i < DBG_IV_LAST; i++) {
174         if (!strcmp(DEBUG_IntVars[i].name, name))
175             return &DEBUG_IntVars[i];
176     }
177     return NULL;
178 }
179
180 DBG_PROCESS*    DEBUG_GetProcess(DWORD pid)
181 {
182     DBG_PROCESS*        p;
183
184     for (p = DEBUG_ProcessList; p; p = p->next)
185         if (p->pid == pid) break;
186     return p;
187 }
188
189 DBG_PROCESS*    DEBUG_AddProcess(DWORD pid, HANDLE h, const char* imageName)
190 {
191     DBG_PROCESS*        p;
192
193     if ((p = DEBUG_GetProcess(pid)))
194     {
195         if (p->handle != 0)
196         {
197             WINE_ERR("Process (%lu) is already defined\n", pid);
198         }
199         else
200         {
201             p->handle = h;
202             p->imageName = imageName ? DBG_strdup(imageName) : NULL;
203         }
204         return p;
205     }
206
207     if (!(p = DBG_alloc(sizeof(DBG_PROCESS)))) return NULL;
208     p->handle = h;
209     p->pid = pid;
210     p->imageName = imageName ? DBG_strdup(imageName) : NULL;
211     p->threads = NULL;
212     p->num_threads = 0;
213     p->continue_on_first_exception = FALSE;
214     p->modules = NULL;
215     p->num_modules = 0;
216     p->next_index = 0;
217     p->dbg_hdr_addr = 0;
218     p->delayed_bp = NULL;
219     p->num_delayed_bp = 0;
220
221     p->next = DEBUG_ProcessList;
222     p->prev = NULL;
223     if (DEBUG_ProcessList) DEBUG_ProcessList->prev = p;
224     DEBUG_ProcessList = p;
225     return p;
226 }
227
228 void DEBUG_DelProcess(DBG_PROCESS* p)
229 {
230     int i;
231
232     while (p->threads) DEBUG_DelThread(p->threads);
233
234     for (i = 0; i < p->num_delayed_bp; i++)
235         if (p->delayed_bp[i].is_symbol)
236             DBG_free(p->delayed_bp[i].u.symbol.name);
237
238     DBG_free(p->delayed_bp);
239     if (p->prev) p->prev->next = p->next;
240     if (p->next) p->next->prev = p->prev;
241     if (p == DEBUG_ProcessList) DEBUG_ProcessList = p->next;
242     if (p == DEBUG_CurrProcess) DEBUG_CurrProcess = NULL;
243     DBG_free((char*)p->imageName);
244     DBG_free(p);
245 }
246
247 static  void                    DEBUG_InitCurrProcess(void)
248 {
249 }
250
251 BOOL DEBUG_ProcessGetString(char* buffer, int size, HANDLE hp, LPSTR addr)
252 {
253     DWORD sz;
254     *(WCHAR*)buffer = 0;
255     return (addr && ReadProcessMemory(hp, addr, buffer, size, &sz));
256 }
257
258 BOOL DEBUG_ProcessGetStringIndirect(char* buffer, int size, HANDLE hp, LPVOID addr, BOOL unicode)
259 {
260     LPVOID      ad;
261     DWORD       sz;
262
263     if (addr && ReadProcessMemory(hp, addr, &ad, sizeof(ad), &sz) && sz == sizeof(ad) && ad)
264     {
265         if (!unicode) ReadProcessMemory(hp, ad, buffer, size, &sz);
266         else
267         {
268             WCHAR *buffW = DBG_alloc( size * sizeof(WCHAR) );
269             ReadProcessMemory(hp, ad, buffW, size*sizeof(WCHAR), &sz);
270             WideCharToMultiByte( CP_ACP, 0, buffW, sz/sizeof(WCHAR), buffer, size, NULL, NULL );
271             DBG_free(buffW);
272         }
273         return TRUE;
274     }
275     *(WCHAR*)buffer = 0;
276     return FALSE;
277 }
278
279 DBG_THREAD*     DEBUG_GetThread(DBG_PROCESS* p, DWORD tid)
280 {
281     DBG_THREAD* t;
282
283     if (!p) return NULL;
284     for (t = p->threads; t; t = t->next)
285         if (t->tid == tid) break;
286     return t;
287 }
288
289 DBG_THREAD*     DEBUG_AddThread(DBG_PROCESS* p, DWORD tid,
290                                 HANDLE h, LPVOID start, LPVOID teb)
291 {
292     DBG_THREAD* t = DBG_alloc(sizeof(DBG_THREAD));
293     if (!t)
294         return NULL;
295
296     t->handle = h;
297     t->tid = tid;
298     t->start = start;
299     t->teb = teb;
300     t->process = p;
301     t->wait_for_first_exception = 0;
302     t->exec_mode = EXEC_CONT;
303     t->exec_count = 0;
304
305     snprintf(t->name, sizeof(t->name), "%08lx", tid);
306
307     p->num_threads++;
308     t->next = p->threads;
309     t->prev = NULL;
310     if (p->threads) p->threads->prev = t;
311     p->threads = t;
312
313     return t;
314 }
315
316 static  void                    DEBUG_InitCurrThread(void)
317 {
318     if (DEBUG_CurrThread->start) {
319         if (DEBUG_CurrThread->process->num_threads == 1 ||
320             DBG_IVAR(BreakAllThreadsStartup)) {
321             DBG_VALUE   value;
322
323             DEBUG_SetBreakpoints(FALSE);
324             value.type = NULL;
325             value.cookie = DV_TARGET;
326             value.addr.seg = 0;
327             value.addr.off = (DWORD)DEBUG_CurrThread->start;
328             DEBUG_AddBreakpointFromValue(&value);
329             DEBUG_SetBreakpoints(TRUE);
330         }
331     } else {
332         DEBUG_CurrThread->wait_for_first_exception = 1;
333     }
334 }
335
336 void                    DEBUG_DelThread(DBG_THREAD* t)
337 {
338     if (t->prev) t->prev->next = t->next;
339     if (t->next) t->next->prev = t->prev;
340     if (t == t->process->threads) t->process->threads = t->next;
341     t->process->num_threads--;
342     if (t == DEBUG_CurrThread) DEBUG_CurrThread = NULL;
343     DBG_free(t);
344 }
345
346 static  BOOL    DEBUG_HandleDebugEvent(DEBUG_EVENT* de);
347
348 /******************************************************************
349  *              DEBUG_Attach
350  *
351  * Sets the debuggee to <pid>
352  * cofe instructs winedbg what to do when first exception is received 
353  * (break=FALSE, continue=TRUE)
354  * wfe is set to TRUE if DEBUG_Attach should also proceed with all debug events
355  * until the first exception is received (aka: attach to an already running process)
356  */
357 BOOL                            DEBUG_Attach(DWORD pid, BOOL cofe, BOOL wfe)
358 {
359     DEBUG_EVENT         de;
360
361     if (!(DEBUG_CurrProcess = DEBUG_AddProcess(pid, 0, NULL))) return FALSE;
362
363     if (!DebugActiveProcess(pid)) {
364         DEBUG_Printf("Can't attach process %lx: error %ld\n", pid, GetLastError());
365         DEBUG_DelProcess(DEBUG_CurrProcess);
366         return FALSE;
367     }
368     DEBUG_CurrProcess->continue_on_first_exception = cofe;
369
370     if (wfe) /* shall we proceed all debug events until we get an exception ? */
371     {
372         DEBUG_InteractiveP = FALSE;
373         while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
374         {
375             if (DEBUG_HandleDebugEvent(&de)) break;
376         }
377         if (DEBUG_CurrProcess) DEBUG_InteractiveP = TRUE;
378     }
379     return TRUE;
380 }
381
382 BOOL                            DEBUG_Detach(void)
383 {
384     /* remove all set breakpoints in debuggee code */
385     DEBUG_SetBreakpoints(FALSE);
386     /* needed for single stepping (ugly).
387      * should this be handled inside the server ??? */
388 #ifdef __i386__
389     DEBUG_context.EFlags &= ~STEP_FLAG;
390 #endif
391     SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
392     DebugActiveProcessStop(DEBUG_CurrProcess->pid);
393     DEBUG_DelProcess(DEBUG_CurrProcess);
394     /* FIXME: should zero out the symbol table too */
395     return TRUE;
396 }
397
398 static BOOL                     DEBUG_FetchContext(void)
399 {
400     DEBUG_context.ContextFlags = CONTEXT_CONTROL
401                                | CONTEXT_INTEGER
402 #ifdef CONTEXT_SEGMENTS
403                                | CONTEXT_SEGMENTS
404 #endif
405 #ifdef CONTEXT_DEBUG_REGISTERS
406                                | CONTEXT_DEBUG_REGISTERS
407 #endif
408                                ;
409     if (!GetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
410     {
411         WINE_WARN("Can't get thread's context\n");
412         return FALSE;
413     }
414     return TRUE;
415 }
416
417 static  BOOL    DEBUG_ExceptionProlog(BOOL is_debug, BOOL force, DWORD code)
418 {
419     DBG_ADDR    addr;
420     int         newmode;
421
422     DEBUG_InException = TRUE;
423     DEBUG_GetCurrentAddress(&addr);
424     DEBUG_SuspendExecution();
425
426     if (!is_debug)
427     {
428         if (!addr.seg)
429             DEBUG_Printf(" in 32-bit code (0x%08lx)", addr.off);
430         else
431             switch (DEBUG_GetSelectorType(addr.seg))
432             {
433             case MODE_32:
434                 DEBUG_Printf(" in 32-bit code (%04lx:%08lx)", addr.seg, addr.off);
435                 break;
436             case MODE_16:
437                 DEBUG_Printf(" in 16-bit code (%04lx:%04lx)", addr.seg, addr.off);
438                 break;
439             case MODE_VM86:
440                 DEBUG_Printf(" in vm86 code (%04lx:%04lx)", addr.seg, addr.off);
441                 break;
442             case MODE_INVALID:
443                 DEBUG_Printf(" bad CS (%lx)", addr.seg);
444                 break;
445         }
446         DEBUG_Printf(".\n");
447     }
448
449     DEBUG_LoadEntryPoints("Loading new modules symbols:\n");
450     /*
451      * Do a quiet backtrace so that we have an idea of what the situation
452      * is WRT the source files.
453      */
454     DEBUG_BackTrace(DEBUG_CurrTid, FALSE);
455
456     if (!force && is_debug &&
457         DEBUG_ShouldContinue(&addr, code,
458                              &DEBUG_CurrThread->exec_count))
459         return FALSE;
460
461     if ((newmode = DEBUG_GetSelectorType(addr.seg)) == MODE_INVALID) newmode = MODE_32;
462     if (newmode != DEBUG_CurrThread->dbg_mode)
463     {
464         static const char * const names[] = { "???", "16-bit", "32-bit", "vm86" };
465         DEBUG_Printf("In %s mode.\n", names[newmode] );
466         DEBUG_CurrThread->dbg_mode = newmode;
467     }
468
469     DEBUG_DoDisplay();
470
471     if (!is_debug && !force) {
472         /* This is a real crash, dump some info */
473         DEBUG_InfoRegisters(&DEBUG_context);
474         DEBUG_InfoStack();
475 #ifdef __i386__
476         if (DEBUG_CurrThread->dbg_mode == MODE_16) {
477             DEBUG_InfoSegments(DEBUG_context.SegDs >> 3, 1);
478             if (DEBUG_context.SegEs != DEBUG_context.SegDs)
479                 DEBUG_InfoSegments(DEBUG_context.SegEs >> 3, 1);
480         }
481         DEBUG_InfoSegments(DEBUG_context.SegFs >> 3, 1);
482 #endif
483         DEBUG_BackTrace(DEBUG_CurrTid, TRUE);
484     }
485
486     if (!is_debug ||
487         (DEBUG_CurrThread->exec_mode == EXEC_STEPI_OVER) ||
488         (DEBUG_CurrThread->exec_mode == EXEC_STEPI_INSTR)) {
489
490         struct list_id list;
491
492         /* Show where we crashed */
493         curr_frame = 0;
494         DEBUG_DisassembleInstruction(&addr);
495
496         /* resets list internal arguments so we can look at source code when needed */
497         DEBUG_FindNearestSymbol(&addr, TRUE, NULL, 0, &list);
498         if (list.sourcefile) DEBUG_List(&list, NULL, 0);
499     }
500     return TRUE;
501 }
502
503 static  void    DEBUG_ExceptionEpilog(void)
504 {
505     DEBUG_RestartExecution(DEBUG_CurrThread->exec_count);
506     /*
507      * This will have gotten absorbed into the breakpoint info
508      * if it was used.  Otherwise it would have been ignored.
509      * In any case, we don't mess with it any more.
510      */
511     if (DEBUG_CurrThread->exec_mode == EXEC_CONT)
512         DEBUG_CurrThread->exec_count = 0;
513     DEBUG_InException = FALSE;
514 }
515
516 static DWORD DEBUG_HandleException(EXCEPTION_RECORD *rec, BOOL first_chance, BOOL force)
517 {
518     BOOL             is_debug = FALSE;
519     THREADNAME_INFO *pThreadName;
520     DBG_THREAD      *pThread;
521
522     assert(DEBUG_CurrThread);
523
524     switch (rec->ExceptionCode)
525     {
526     case EXCEPTION_BREAKPOINT:
527     case EXCEPTION_SINGLE_STEP:
528         is_debug = TRUE;
529         break;
530     case EXCEPTION_NAME_THREAD:
531         pThreadName = (THREADNAME_INFO*)(rec->ExceptionInformation);
532         if (pThreadName->dwThreadID == -1)
533             pThread = DEBUG_CurrThread;
534         else
535             pThread = DEBUG_GetThread(DEBUG_CurrProcess, pThreadName->dwThreadID);
536
537         if (ReadProcessMemory(DEBUG_CurrThread->process->handle, pThreadName->szName,
538                               pThread->name, 9, NULL))
539             DEBUG_Printf("Thread ID=0x%lx renamed using MS VC6 extension (name==\"%s\")\n",
540                          pThread->tid, pThread->name);
541         return DBG_CONTINUE;
542     }
543
544     if (first_chance && !is_debug && !force && !DBG_IVAR(BreakOnFirstChance))
545     {
546         /* pass exception to program except for debug exceptions */
547         return DBG_EXCEPTION_NOT_HANDLED;
548     }
549
550     if (!is_debug)
551     {
552         /* print some infos */
553         DEBUG_Printf("%s: ",
554                      first_chance ? "First chance exception" : "Unhandled exception");
555         switch (rec->ExceptionCode)
556         {
557         case EXCEPTION_INT_DIVIDE_BY_ZERO:
558             DEBUG_Printf("divide by zero");
559             break;
560         case EXCEPTION_INT_OVERFLOW:
561             DEBUG_Printf("overflow");
562             break;
563         case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
564             DEBUG_Printf("array bounds");
565             break;
566         case EXCEPTION_ILLEGAL_INSTRUCTION:
567             DEBUG_Printf("illegal instruction");
568             break;
569         case EXCEPTION_STACK_OVERFLOW:
570             DEBUG_Printf("stack overflow");
571             break;
572         case EXCEPTION_PRIV_INSTRUCTION:
573             DEBUG_Printf("privileged instruction");
574             break;
575         case EXCEPTION_ACCESS_VIOLATION:
576             if (rec->NumberParameters == 2)
577                 DEBUG_Printf("page fault on %s access to 0x%08lx",
578                              rec->ExceptionInformation[0] ? "write" : "read",
579                              rec->ExceptionInformation[1]);
580             else
581                 DEBUG_Printf("page fault");
582             break;
583         case EXCEPTION_DATATYPE_MISALIGNMENT:
584             DEBUG_Printf("Alignment");
585             break;
586         case DBG_CONTROL_C:
587             DEBUG_Printf("^C");
588             break;
589         case CONTROL_C_EXIT:
590             DEBUG_Printf("^C");
591             break;
592         case STATUS_POSSIBLE_DEADLOCK:
593             {
594                 DBG_ADDR        addr;
595
596                 addr.seg = 0;
597                 addr.off = rec->ExceptionInformation[0];
598
599                 DEBUG_Printf("wait failed on critical section ");
600                 DEBUG_PrintAddress(&addr, DEBUG_CurrThread->dbg_mode, FALSE);
601             }
602             if (!DBG_IVAR(BreakOnCritSectTimeOut))
603             {
604                 DEBUG_Printf("\n");
605                 return DBG_EXCEPTION_NOT_HANDLED;
606             }
607             break;
608         case EXCEPTION_WINE_STUB:
609             {
610                 char dll[32], name[64];
611                 DEBUG_ProcessGetString( dll, sizeof(dll), DEBUG_CurrThread->process->handle,
612                                         (char *)rec->ExceptionInformation[0] );
613                 DEBUG_ProcessGetString( name, sizeof(name), DEBUG_CurrThread->process->handle,
614                                         (char *)rec->ExceptionInformation[1] );
615                 DEBUG_Printf("unimplemented function %s.%s called", dll, name );
616             }
617             break;
618         case EXCEPTION_WINE_ASSERTION:
619             DEBUG_Printf("assertion failed");
620             break;
621         case EXCEPTION_VM86_INTx:
622             DEBUG_Printf("interrupt %02lx in vm86 mode",
623                          rec->ExceptionInformation[0]);
624             break;
625         case EXCEPTION_VM86_STI:
626             DEBUG_Printf("sti in vm86 mode");
627             break;
628         case EXCEPTION_VM86_PICRETURN:
629             DEBUG_Printf("PIC return in vm86 mode");
630             break;
631         case EXCEPTION_FLT_DENORMAL_OPERAND:
632             DEBUG_Printf("denormal float operand");
633             break;
634         case EXCEPTION_FLT_DIVIDE_BY_ZERO:
635             DEBUG_Printf("divide by zero");
636             break;
637         case EXCEPTION_FLT_INEXACT_RESULT:
638             DEBUG_Printf("inexact float result");
639             break;
640         case EXCEPTION_FLT_INVALID_OPERATION:
641             DEBUG_Printf("invalid float operation");
642             break;
643         case EXCEPTION_FLT_OVERFLOW:
644             DEBUG_Printf("floating pointer overflow");
645             break;
646         case EXCEPTION_FLT_UNDERFLOW:
647             DEBUG_Printf("floating pointer underflow");
648             break;
649         case EXCEPTION_FLT_STACK_CHECK:
650             DEBUG_Printf("floating point stack check");
651             break;
652         default:
653             DEBUG_Printf("%08lx", rec->ExceptionCode);
654             break;
655         }
656     }
657
658     if (local_mode == automatic_mode)
659     {
660         DEBUG_ExceptionProlog(is_debug, FALSE, rec->ExceptionCode);
661         DEBUG_ExceptionEpilog();
662         return 0;  /* terminate execution */
663     }
664
665     if (DEBUG_ExceptionProlog(is_debug, force, rec->ExceptionCode))
666     {
667         DEBUG_InteractiveP = TRUE;
668         return 0;
669     }
670     DEBUG_ExceptionEpilog();
671
672     return DBG_CONTINUE;
673 }
674
675 static  BOOL    DEBUG_HandleDebugEvent(DEBUG_EVENT* de)
676 {
677     char        buffer[256];
678     DWORD       cont = DBG_CONTINUE;
679
680     DEBUG_CurrPid = de->dwProcessId;
681     DEBUG_CurrTid = de->dwThreadId;
682
683     if ((DEBUG_CurrProcess = DEBUG_GetProcess(de->dwProcessId)) != NULL)
684         DEBUG_CurrThread = DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId);
685     else
686         DEBUG_CurrThread = NULL;
687
688     switch (de->dwDebugEventCode)
689     {
690     case EXCEPTION_DEBUG_EVENT:
691         if (!DEBUG_CurrThread)
692         {
693             WINE_ERR("%08lx:%08lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
694                      de->dwProcessId, de->dwThreadId);
695             break;
696         }
697
698         WINE_TRACE("%08lx:%08lx: exception code=%08lx\n",
699                    de->dwProcessId, de->dwThreadId,
700                    de->u.Exception.ExceptionRecord.ExceptionCode);
701
702         if (DEBUG_CurrProcess->continue_on_first_exception)
703         {
704             DEBUG_CurrProcess->continue_on_first_exception = FALSE;
705             if (!DBG_IVAR(BreakOnAttach)) break;
706         }
707
708         if (DEBUG_FetchContext())
709         {
710             cont = DEBUG_HandleException(&de->u.Exception.ExceptionRecord,
711                                         de->u.Exception.dwFirstChance,
712                                         DEBUG_CurrThread->wait_for_first_exception);
713             if (cont && DEBUG_CurrThread)
714             {
715                 DEBUG_CurrThread->wait_for_first_exception = 0;
716                 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
717             }
718         }
719         break;
720
721     case CREATE_THREAD_DEBUG_EVENT:
722         WINE_TRACE("%08lx:%08lx: create thread D @%08lx\n", de->dwProcessId, de->dwThreadId,
723                    (unsigned long)(LPVOID)de->u.CreateThread.lpStartAddress);
724
725         if (DEBUG_CurrProcess == NULL)
726         {
727             WINE_ERR("Unknown process\n");
728             break;
729         }
730         if (DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId) != NULL)
731         {
732             WINE_TRACE("Thread already listed, skipping\n");
733             break;
734         }
735
736         DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
737                                            de->dwThreadId,
738                                            de->u.CreateThread.hThread,
739                                            de->u.CreateThread.lpStartAddress,
740                                            de->u.CreateThread.lpThreadLocalBase);
741         if (!DEBUG_CurrThread)
742         {
743             WINE_ERR("Couldn't create thread\n");
744             break;
745         }
746         DEBUG_InitCurrThread();
747         break;
748
749     case CREATE_PROCESS_DEBUG_EVENT:
750         DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
751                                        de->u.CreateProcessInfo.hProcess,
752                                        de->u.CreateProcessInfo.lpImageName,
753                                        de->u.CreateProcessInfo.fUnicode);
754
755         WINE_TRACE("%08lx:%08lx: create process '%s'/%p @%08lx (%ld<%ld>)\n",
756                    de->dwProcessId, de->dwThreadId,
757                    buffer, de->u.CreateProcessInfo.lpImageName,
758                    (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress,
759                    de->u.CreateProcessInfo.dwDebugInfoFileOffset,
760                    de->u.CreateProcessInfo.nDebugInfoSize);
761
762         DEBUG_CurrProcess = DEBUG_AddProcess(de->dwProcessId,
763                                              de->u.CreateProcessInfo.hProcess,
764                                              buffer[0] ? buffer : "<Debugged Process>");
765         if (DEBUG_CurrProcess == NULL)
766         {
767             WINE_ERR("Couldn't create process\n");
768             break;
769         }
770
771         WINE_TRACE("%08lx:%08lx: create thread I @%08lx\n",
772                    de->dwProcessId, de->dwThreadId,
773                    (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress);
774
775         DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
776                                            de->dwThreadId,
777                                            de->u.CreateProcessInfo.hThread,
778                                            de->u.CreateProcessInfo.lpStartAddress,
779                                            de->u.CreateProcessInfo.lpThreadLocalBase);
780         if (!DEBUG_CurrThread)
781         {
782             WINE_ERR("Couldn't create thread\n");
783             break;
784         }
785         else
786         {
787             struct elf_info     elf_info;
788
789             DEBUG_InitCurrProcess();
790             DEBUG_InitCurrThread();
791
792             elf_info.flags = ELF_INFO_MODULE;
793
794             if (DEBUG_ReadWineLoaderDbgInfo(DEBUG_CurrProcess->handle, &elf_info) != DIL_ERROR &&
795                 DEBUG_SetElfSoLoadBreakpoint(&elf_info))
796             {
797                 /* then load the main module's symbols */
798                 DEBUG_LoadPEModule(DEBUG_CurrProcess->imageName, 
799                                    de->u.CreateProcessInfo.hFile,
800                                    de->u.CreateProcessInfo.lpBaseOfImage);
801             }
802             else
803             {
804                 DEBUG_DelThread(DEBUG_CurrProcess->threads);
805                 DEBUG_DelProcess(DEBUG_CurrProcess);
806                 DEBUG_Printf("Couldn't load process\n");
807             }
808         }
809         break;
810
811     case EXIT_THREAD_DEBUG_EVENT:
812         WINE_TRACE("%08lx:%08lx: exit thread (%ld)\n",
813                    de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
814
815         if (DEBUG_CurrThread == NULL)
816         {
817             WINE_ERR("Unknown thread\n");
818             break;
819         }
820         /* FIXME: remove break point set on thread startup */
821         DEBUG_DelThread(DEBUG_CurrThread);
822         break;
823
824     case EXIT_PROCESS_DEBUG_EVENT:
825         WINE_TRACE("%08lx:%08lx: exit process (%ld)\n",
826                    de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
827
828         if (DEBUG_CurrProcess == NULL)
829         {
830             WINE_ERR("Unknown process\n");
831             break;
832         }
833         /* just in case */
834         DEBUG_SetBreakpoints(FALSE);
835         /* kill last thread */
836         DEBUG_DelThread(DEBUG_CurrProcess->threads);
837         DEBUG_DelProcess(DEBUG_CurrProcess);
838
839         DEBUG_Printf("Process of pid=%08lx has terminated\n", DEBUG_CurrPid);
840         break;
841
842     case LOAD_DLL_DEBUG_EVENT:
843         if (DEBUG_CurrThread == NULL)
844         {
845             WINE_ERR("Unknown thread\n");
846             break;
847         }
848         DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
849                                        DEBUG_CurrThread->process->handle,
850                                        de->u.LoadDll.lpImageName,
851                                        de->u.LoadDll.fUnicode);
852
853         WINE_TRACE("%08lx:%08lx: loads DLL %s @%08lx (%ld<%ld>)\n",
854                    de->dwProcessId, de->dwThreadId,
855                    buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll,
856                    de->u.LoadDll.dwDebugInfoFileOffset,
857                    de->u.LoadDll.nDebugInfoSize);
858         _strupr(buffer);
859         DEBUG_LoadPEModule(buffer, de->u.LoadDll.hFile, de->u.LoadDll.lpBaseOfDll);
860         DEBUG_CheckDelayedBP();
861         if (DBG_IVAR(BreakOnDllLoad))
862         {
863             DEBUG_Printf("Stopping on DLL %s loading at %08lx\n",
864                          buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll);
865             if (DEBUG_FetchContext()) cont = 0;
866         }
867         break;
868
869     case UNLOAD_DLL_DEBUG_EVENT:
870         WINE_TRACE("%08lx:%08lx: unload DLL @%08lx\n", de->dwProcessId, de->dwThreadId,
871                    (unsigned long)de->u.UnloadDll.lpBaseOfDll);
872         break;
873
874     case OUTPUT_DEBUG_STRING_EVENT:
875         if (DEBUG_CurrThread == NULL)
876         {
877             WINE_ERR("Unknown thread\n");
878             break;
879         }
880
881         DEBUG_ProcessGetString(buffer, sizeof(buffer),
882                                DEBUG_CurrThread->process->handle,
883                                de->u.DebugString.lpDebugStringData);
884
885         /* FIXME unicode de->u.DebugString.fUnicode ? */
886         WINE_TRACE("%08lx:%08lx: output debug string (%s)\n",
887                    de->dwProcessId, de->dwThreadId, buffer);
888         break;
889
890     case RIP_EVENT:
891         WINE_TRACE("%08lx:%08lx: rip error=%ld type=%ld\n",
892                    de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
893                    de->u.RipInfo.dwType);
894         break;
895
896     default:
897         WINE_TRACE("%08lx:%08lx: unknown event (%ld)\n",
898                    de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
899     }
900     if (!cont) return TRUE;  /* stop execution */
901     ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
902     return FALSE;  /* continue execution */
903 }
904
905 static void                     DEBUG_ResumeDebuggee(DWORD cont)
906 {
907     if (DEBUG_InException)
908     {
909         DEBUG_ExceptionEpilog();
910 #ifdef __i386__
911         WINE_TRACE("Exiting debugger      PC=%lx EFL=%08lx mode=%d count=%d\n",
912                    DEBUG_context.Eip, DEBUG_context.EFlags,
913                    DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
914 #else
915         WINE_TRACE("Exiting debugger      PC=%lx EFL=%08lx mode=%d count=%d\n",
916                    0L, 0L,
917                    DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
918 #endif
919         if (DEBUG_CurrThread)
920         {
921             if (!SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
922                 DEBUG_Printf("Cannot set ctx on %lu\n", DEBUG_CurrTid);
923             DEBUG_CurrThread->wait_for_first_exception = 0;
924         }
925     }
926     DEBUG_InteractiveP = FALSE;
927     if (!ContinueDebugEvent(DEBUG_CurrPid, DEBUG_CurrTid, cont))
928         DEBUG_Printf("Cannot continue on %lu (%lu)\n", DEBUG_CurrTid, cont);
929 }
930
931 void                            DEBUG_WaitNextException(DWORD cont, int count, int mode)
932 {
933     DEBUG_EVENT         de;
934
935     if (cont == DBG_CONTINUE)
936     {
937         DEBUG_CurrThread->exec_count = count;
938         DEBUG_CurrThread->exec_mode = mode;
939     }
940     DEBUG_ResumeDebuggee(cont);
941
942     while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
943     {
944         if (DEBUG_HandleDebugEvent(&de)) break;
945     }
946     if (!DEBUG_CurrProcess) return;
947     DEBUG_InteractiveP = TRUE;
948 #ifdef __i386__
949     WINE_TRACE("Entering debugger     PC=%lx EFL=%08lx mode=%d count=%d\n",
950                DEBUG_context.Eip, DEBUG_context.EFlags,
951                DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
952 #else
953     WINE_TRACE("Entering debugger     PC=%lx EFL=%08lx mode=%d count=%d\n",
954                0L, 0L,
955                DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
956 #endif
957 }
958
959 static  DWORD   DEBUG_MainLoop(void)
960 {
961     DEBUG_EVENT         de;
962
963     DEBUG_Printf("WineDbg starting on pid %lx\n", DEBUG_CurrPid);
964
965     /* wait for first exception */
966     while (WaitForDebugEvent(&de, INFINITE))
967     {
968         if (DEBUG_HandleDebugEvent(&de)) break;
969     }
970     if (local_mode == automatic_mode)
971     {
972         /* print some extra information */
973         DEBUG_Printf("Modules:\n");
974         DEBUG_WalkModules();
975         DEBUG_Printf("Threads:\n");
976         DEBUG_WalkThreads();
977     }
978     else
979     {
980         DEBUG_InteractiveP = TRUE;
981         DEBUG_Parser(NULL);
982     }
983     DEBUG_Printf("WineDbg terminated on pid %lx\n", DEBUG_CurrPid);
984
985     return 0;
986 }
987
988 static  BOOL    DEBUG_Start(LPSTR cmdLine)
989 {
990     PROCESS_INFORMATION info;
991     STARTUPINFOA        startup;
992
993     memset(&startup, 0, sizeof(startup));
994     startup.cb = sizeof(startup);
995     startup.dwFlags = STARTF_USESHOWWINDOW;
996     startup.wShowWindow = SW_SHOWNORMAL;
997
998     /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUI:s need it
999      * while GUI:s don't
1000      */
1001     if (!CreateProcess(NULL, cmdLine, NULL, NULL,
1002                        FALSE, DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS|CREATE_NEW_CONSOLE,
1003                        NULL, NULL, &startup, &info))
1004     {
1005         DEBUG_Printf("Couldn't start process '%s'\n", cmdLine);
1006         return FALSE;
1007     }
1008     DEBUG_CurrPid = info.dwProcessId;
1009     if (!(DEBUG_CurrProcess = DEBUG_AddProcess(DEBUG_CurrPid, 0, NULL))) return FALSE;
1010
1011     return TRUE;
1012 }
1013
1014 void    DEBUG_Run(const char* args)
1015 {
1016     DBG_MODULE* wmod = DEBUG_GetProcessMainModule(DEBUG_CurrProcess);
1017     const char* pgm = (wmod) ? wmod->module_name : "none";
1018
1019     if (args) {
1020         DEBUG_Printf("Run (%s) with '%s'\n", pgm, args);
1021     } else {
1022         if (!DEBUG_LastCmdLine) {
1023             DEBUG_Printf("Cannot find previously used command line.\n");
1024             return;
1025         }
1026         DEBUG_Start(DEBUG_LastCmdLine);
1027     }
1028 }
1029
1030 BOOL DEBUG_InterruptDebuggee(void)
1031 {
1032     DEBUG_Printf("Ctrl-C: stopping debuggee\n");
1033     /* FIXME: since we likely have a single process, signal the first process
1034      * in list
1035      */
1036     if (!DEBUG_ProcessList) return FALSE;
1037     DEBUG_ProcessList->continue_on_first_exception = FALSE;
1038     return DebugBreakProcess(DEBUG_ProcessList->handle);
1039 }
1040
1041 static BOOL WINAPI DEBUG_CtrlCHandler(DWORD dwCtrlType)
1042 {
1043     if (dwCtrlType == CTRL_C_EVENT)
1044     {
1045         return DEBUG_InterruptDebuggee();
1046     }
1047     return FALSE;
1048 }
1049
1050 static void DEBUG_InitConsole(void)
1051 {
1052     /* set our control-C handler */
1053     SetConsoleCtrlHandler(DEBUG_CtrlCHandler, TRUE);
1054
1055     /* set our own title */
1056     SetConsoleTitle("Wine Debugger");
1057 }
1058
1059 static int DEBUG_Usage(void)
1060 {
1061     DEBUG_Printf("Usage: winedbg [--debugmsg dbgoptions] [--auto] [--gdb] cmdline\n" );
1062     return 1;
1063 }
1064
1065 int main(int argc, char** argv)
1066 {
1067     DWORD       retv = 0;
1068     unsigned    gdb_flags = 0;
1069
1070     /* Initialize the type handling stuff. */
1071     DEBUG_InitTypes();
1072     DEBUG_InitCVDataTypes();
1073
1074     /* Initialize internal vars (types must have been initialized before) */
1075     if (!DEBUG_IntVarsRW(TRUE)) return -1;
1076
1077     /* parse options */
1078     while (argc > 1 && argv[1][0] == '-')
1079     {
1080         if (!strcmp( argv[1], "--auto" ))
1081         {
1082             if (local_mode != none_mode) return DEBUG_Usage();
1083             local_mode = automatic_mode;
1084             /* force some internal variables */
1085             DBG_IVAR(BreakOnDllLoad) = 0;
1086             argc--; argv++;
1087             continue;
1088         }
1089         if (!strcmp( argv[1], "--gdb" ))
1090         {
1091             if (local_mode != none_mode) return DEBUG_Usage();
1092             local_mode = gdb_mode;
1093             argc--; argv++;
1094             continue;
1095         }
1096         if (strcmp( argv[1], "--no-start") == 0 && local_mode == gdb_mode)
1097         {
1098             gdb_flags |= 1;
1099             argc--; argv++; /* as we don't use argv[0] */
1100             continue;
1101         }
1102         if (strcmp(argv[1], "--with-xterm") == 0 && local_mode == gdb_mode)
1103         {
1104             gdb_flags |= 2;
1105             argc--; argv++; /* as we don't use argv[0] */
1106             continue;
1107         }
1108         if (!strcmp( argv[1], "--debugmsg" ) && argv[2])
1109         {
1110             wine_dbg_parse_options( argv[2] );
1111             argc -= 2;
1112             argv += 2;
1113             continue;
1114         }
1115         return DEBUG_Usage();
1116     }
1117
1118     if (local_mode == none_mode) local_mode = winedbg_mode;
1119
1120     /* try the form <myself> pid */
1121     if (DEBUG_CurrPid == 0 && argc == 2)
1122     {
1123         char*   ptr;
1124
1125         DEBUG_CurrPid = strtol(argv[1], &ptr, 10);
1126         if (DEBUG_CurrPid == 0 || ptr == NULL ||
1127             !DEBUG_Attach(DEBUG_CurrPid, local_mode != gdb_mode, FALSE))
1128             DEBUG_CurrPid = 0;
1129     }
1130
1131     /* try the form <myself> pid evt (Win32 JIT debugger) */
1132     if (DEBUG_CurrPid == 0 && argc == 3)
1133     {
1134         HANDLE  hEvent;
1135         DWORD   pid;
1136         char*   ptr;
1137
1138         if ((pid = strtol(argv[1], &ptr, 10)) != 0 && ptr != NULL &&
1139             (hEvent = (HANDLE)strtol(argv[2], &ptr, 10)) != 0 && ptr != NULL)
1140         {
1141             if (!DEBUG_Attach(pid, TRUE, FALSE))
1142             {
1143                 /* don't care about result */
1144                 SetEvent(hEvent);
1145                 goto leave;
1146             }
1147             if (!SetEvent(hEvent))
1148             {
1149                 WINE_ERR("Invalid event handle: %p\n", hEvent);
1150                 goto leave;
1151             }
1152             CloseHandle(hEvent);
1153             DEBUG_CurrPid = pid;
1154         }
1155     }
1156
1157     if (DEBUG_CurrPid == 0 && argc > 1)
1158     {
1159         int     i, len;
1160         LPSTR   cmdLine;
1161
1162         if (!(cmdLine = DBG_alloc(len = 1))) goto oom_leave;
1163         cmdLine[0] = '\0';
1164
1165         for (i = 1; i < argc; i++)
1166         {
1167             len += strlen(argv[i]) + 1;
1168             if (!(cmdLine = DBG_realloc(cmdLine, len))) goto oom_leave;
1169             strcat(cmdLine, argv[i]);
1170             cmdLine[len - 2] = ' ';
1171             cmdLine[len - 1] = '\0';
1172         }
1173
1174         if (!DEBUG_Start(cmdLine))
1175         {
1176             DEBUG_Printf("Couldn't start process '%s'\n", cmdLine);
1177             goto leave;
1178         }
1179         DBG_free(DEBUG_LastCmdLine);
1180         DEBUG_LastCmdLine = cmdLine;
1181     }
1182     /* don't save local vars in gdb mode */
1183     if (local_mode == gdb_mode && DEBUG_CurrPid)
1184         return DEBUG_GdbRemote(gdb_flags);
1185
1186     DEBUG_InitConsole();
1187
1188     retv = DEBUG_MainLoop();
1189     /* don't save modified variables in auto mode */
1190     if (local_mode != automatic_mode) DEBUG_IntVarsRW(FALSE);
1191
1192  leave:
1193     return retv;
1194
1195  oom_leave:
1196     DEBUG_Printf("Out of memory\n");
1197     goto leave;
1198 }