Added some missing prototypes.
[wine] / debugger / winedbg.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /* Wine internal debugger
4  * Interface to Windows debugger API
5  * Eric Pouech (c) 2000
6  */
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include "debugger.h"
12
13 #include "thread.h"
14 #include "process.h"
15 #include "file.h"
16 #include "wincon.h"
17 #include "wingdi.h"
18 #include "winuser.h"
19
20 #include "winreg.h"
21
22 #ifdef DBG_need_heap
23 HANDLE dbg_heap = 0;
24 #endif
25
26 DBG_PROCESS*    DEBUG_CurrProcess = NULL;
27 DBG_THREAD*     DEBUG_CurrThread = NULL;
28 DWORD           DEBUG_CurrTid;
29 DWORD           DEBUG_CurrPid;
30 CONTEXT         DEBUG_context;
31
32 static DBG_PROCESS* proc = NULL;
33 DBG_INTVAR DEBUG_IntVars[DBG_IV_LAST];
34
35 void    DEBUG_Output(int chn, const char* buffer, int len)
36 {
37     if (DBG_IVAR(ConChannelMask) & chn)
38         WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, NULL, NULL);
39     if (DBG_IVAR(StdChannelMask) & chn)
40         fwrite(buffer, len, 1, stderr);
41 }
42
43 int     DEBUG_Printf(int chn, const char* format, ...)
44 {
45     char        buf[1024];
46     va_list     valist;
47     int         len;
48
49     va_start(valist, format);
50     len = wvsnprintf(buf, sizeof(buf), format, valist);
51     va_end(valist);
52
53     if (len <= -1) {
54         len = sizeof(buf) - 1;
55         buf[len] = 0;
56         buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
57     }
58     DEBUG_Output(chn, buf, len);
59     return len;
60 }
61
62 static  BOOL DEBUG_IntVarsRW(int read)
63 {
64     HKEY        hkey;
65     DWORD       type = REG_DWORD;
66     DWORD       val;
67     DWORD       count = sizeof(val);
68     int         i;
69     DBG_INTVAR* div = DEBUG_IntVars;
70
71     if (read) {
72 /* initializes internal vars table */
73 #define  INTERNAL_VAR(_var,_val,_ref,_typ)                      \
74         div->val = _val; div->name = #_var; div->pval = _ref;   \
75         div->type = _typ; div++;
76 #include "intvar.h"
77 #undef   INTERNAL_VAR
78     }
79
80     if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) {
81         /* since the IVars are not yet setup, DEBUG_Printf doesn't work,
82          * so don't use it */
83         fprintf(stderr, "Cannot create WineDbg key in registry\n");
84         return FALSE;
85     }
86
87     for (i = 0; i < DBG_IV_LAST; i++) {
88         if (read) {
89             if (!DEBUG_IntVars[i].pval) {
90                 if (!RegQueryValueEx(hkey, DEBUG_IntVars[i].name, 0, 
91                                      &type, (LPSTR)&val, &count))
92                     DEBUG_IntVars[i].val = val;
93                 DEBUG_IntVars[i].pval = &DEBUG_IntVars[i].val;
94             } else {
95                 *DEBUG_IntVars[i].pval = 0;
96             }
97         } else {
98             /* FIXME: type should be infered from basic type -if any- of intvar */
99             if (DEBUG_IntVars[i].pval == &DEBUG_IntVars[i].val)
100                 RegSetValueEx(hkey, DEBUG_IntVars[i].name, 0, 
101                               type, (LPCVOID)DEBUG_IntVars[i].pval, count);
102         }
103     }
104     RegCloseKey(hkey);
105     return TRUE;
106 }
107
108 DBG_INTVAR*     DEBUG_GetIntVar(const char* name)
109 {
110     int         i;
111
112     for (i = 0; i < DBG_IV_LAST; i++) {
113         if (!strcmp(DEBUG_IntVars[i].name, name))
114             return &DEBUG_IntVars[i];
115     }
116     return NULL;
117 }
118                        
119 static WINE_EXCEPTION_FILTER(wine_dbg)
120 {
121     DEBUG_Printf(DBG_CHN_MESG, "\nwine_dbg: Exception (%lx) inside debugger, continuing...\n", GetExceptionCode());
122     DEBUG_ExternalDebugger();
123     return EXCEPTION_EXECUTE_HANDLER;
124 }
125
126 static  DBG_PROCESS*    DEBUG_GetProcess(DWORD pid)
127 {
128     DBG_PROCESS*        p;
129     
130     for (p = proc; p; p = p->next)
131         if (p->pid == pid) break;
132     return p;
133 }
134
135 static  DBG_PROCESS*    DEBUG_AddProcess(DWORD pid, HANDLE h)
136 {
137     DBG_PROCESS*        p = DBG_alloc(sizeof(DBG_PROCESS));
138     if (!p)
139         return NULL;
140     p->handle = h;
141     p->pid = pid;
142     p->threads = NULL;
143     p->num_threads = 0;
144     p->continue_on_first_exception = FALSE;
145     p->modules = NULL;
146     p->next_index = 0;
147     p->dbg_hdr_addr = 0;
148
149     p->next = proc;
150     p->prev = NULL;
151     if (proc) proc->prev = p;
152     proc = p;
153     return p;
154 }
155
156 static  void                    DEBUG_DelThread(DBG_THREAD* p);
157
158 static  void                    DEBUG_DelProcess(DBG_PROCESS* p)
159 {
160     if (p->threads != NULL) {
161         DEBUG_Printf(DBG_CHN_ERR, "Shouldn't happen\n");
162         while (p->threads) DEBUG_DelThread(p->threads);
163     }
164     if (p->prev) p->prev->next = p->next;
165     if (p->next) p->next->prev = p->prev;
166     if (p == proc) proc = p->next;
167     DBG_free(p);
168 }
169
170 static  void                    DEBUG_InitCurrProcess(void)
171 {
172 }
173
174 static BOOL DEBUG_ProcessGetString(char* buffer, int size, HANDLE hp, LPSTR addr)
175 {
176     DWORD sz;
177     *(WCHAR*)buffer = 0;
178     return (addr && ReadProcessMemory(hp, addr, buffer, size, &sz));
179 }
180
181 static BOOL DEBUG_ProcessGetStringIndirect(char* buffer, int size, HANDLE hp, LPVOID addr)
182 {
183     LPVOID      ad;
184     DWORD       sz;
185     
186     if (   addr 
187         && ReadProcessMemory(hp, addr, &ad, sizeof(ad), &sz) 
188         && sz == sizeof(ad) 
189         && ad 
190         && ReadProcessMemory(hp, ad, buffer, size, &sz))
191         return TRUE;
192     *(WCHAR*)buffer = 0;
193     return FALSE;
194 }
195
196 static  DBG_THREAD*     DEBUG_GetThread(DBG_PROCESS* p, DWORD tid)
197 {
198     DBG_THREAD* t;
199     
200     for (t = p->threads; t; t = t->next)
201         if (t->tid == tid) break;
202     return t;
203 }
204
205 static  DBG_THREAD*     DEBUG_AddThread(DBG_PROCESS* p, DWORD tid, 
206                                         HANDLE h, LPVOID start, LPVOID teb)
207 {
208     DBG_THREAD* t = DBG_alloc(sizeof(DBG_THREAD));
209     if (!t)
210         return NULL;
211     
212     t->handle = h;
213     t->tid = tid;
214     t->start = start;
215     t->teb = teb;
216     t->process = p;
217     t->wait_for_first_exception = 0;
218     t->dbg_exec_mode = EXEC_CONT;
219     t->dbg_exec_count = 0;
220
221     p->num_threads++;
222     t->next = p->threads;
223     t->prev = NULL;
224     if (p->threads) p->threads->prev = t;
225     p->threads = t;
226
227     return t;
228 }
229
230 static  void                    DEBUG_InitCurrThread(void)
231 {
232     if (DEBUG_CurrThread->start) {
233         if (DEBUG_CurrThread->process->num_threads == 1 || 
234             DBG_IVAR(BreakAllThreadsStartup)) {
235             DBG_VALUE   value;
236             
237             DEBUG_SetBreakpoints(FALSE);
238             value.type = NULL;
239             value.cookie = DV_TARGET;
240             value.addr.seg = 0;
241             value.addr.off = (DWORD)DEBUG_CurrThread->start;
242             DEBUG_AddBreakpoint(&value, NULL);
243             DEBUG_SetBreakpoints(TRUE);
244         }
245     } else {
246         DEBUG_CurrThread->wait_for_first_exception = 1;
247     }
248 }
249
250 static  void                    DEBUG_DelThread(DBG_THREAD* t)
251 {
252     if (t->prev) t->prev->next = t->next;
253     if (t->next) t->next->prev = t->prev;
254     if (t == t->process->threads) t->process->threads = t->next;
255     t->process->num_threads--;
256     DBG_free(t);
257 }
258
259 static  BOOL    DEBUG_HandleException( EXCEPTION_RECORD *rec, BOOL first_chance, BOOL force )
260 {
261     BOOL        is_debug = FALSE;
262     BOOL        ret;
263
264     /* FIXME: need for a configuration var ? */
265     /* pass to app first ??? */
266     /* if (first_chance && !force) return 0; */
267
268     switch (rec->ExceptionCode)
269     {
270     case EXCEPTION_BREAKPOINT:
271     case EXCEPTION_SINGLE_STEP:
272         is_debug = TRUE;
273         break;
274     }
275
276     if (!is_debug)
277     {
278         /* print some infos */
279         DEBUG_Printf( DBG_CHN_MESG, "%s: ",
280                       first_chance ? "First chance exception" : "Unhandled exception" );
281         switch (rec->ExceptionCode)
282         {
283         case EXCEPTION_INT_DIVIDE_BY_ZERO:
284             DEBUG_Printf( DBG_CHN_MESG, "divide by zero" );
285             break;
286         case EXCEPTION_INT_OVERFLOW:
287             DEBUG_Printf( DBG_CHN_MESG, "overflow" );
288             break;
289         case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
290             DEBUG_Printf( DBG_CHN_MESG, "array bounds " );
291             break;
292         case EXCEPTION_ILLEGAL_INSTRUCTION:
293             DEBUG_Printf( DBG_CHN_MESG, "illegal instruction" );
294             break;
295         case EXCEPTION_STACK_OVERFLOW:
296             DEBUG_Printf( DBG_CHN_MESG, "stack overflow" );
297             break;
298         case EXCEPTION_PRIV_INSTRUCTION:
299             DEBUG_Printf( DBG_CHN_MESG, "priviledged instruction" );
300             break;
301         case EXCEPTION_ACCESS_VIOLATION:
302             if (rec->NumberParameters == 2)
303                 DEBUG_Printf( DBG_CHN_MESG, "page fault on %s access to 0x%08lx", 
304                               rec->ExceptionInformation[0] ? "write" : "read",
305                               rec->ExceptionInformation[1] );
306             else
307                 DEBUG_Printf( DBG_CHN_MESG, "page fault" );
308             break;
309         case EXCEPTION_DATATYPE_MISALIGNMENT:
310             DEBUG_Printf( DBG_CHN_MESG, "Alignment" );
311             break;
312         case CONTROL_C_EXIT:
313             DEBUG_Printf( DBG_CHN_MESG, "^C" );
314             break;
315         case EXCEPTION_CRITICAL_SECTION_WAIT:
316             DEBUG_Printf( DBG_CHN_MESG, "critical section %08lx wait failed", 
317                           rec->ExceptionInformation[0] );
318             if (!DBG_IVAR(BreakOnCritSectTimeOut))
319                 return DBG_CONTINUE;
320             break;
321         default:
322             DEBUG_Printf( DBG_CHN_MESG, "%08lx", rec->ExceptionCode );
323             break;
324         }
325         DEBUG_Printf(DBG_CHN_MESG, "\n");
326     }
327
328     DEBUG_Printf(DBG_CHN_TRACE, 
329                  "Entering debugger     PC=%lx EFL=%08lx mode=%d count=%d\n",
330 #ifdef __i386__
331                  DEBUG_context.Eip, DEBUG_context.EFlags, 
332 #else
333                  0L, 0L,
334 #endif
335                  DEBUG_CurrThread->dbg_exec_mode, DEBUG_CurrThread->dbg_exec_count);
336
337     ret = DEBUG_Main( is_debug, force, rec->ExceptionCode );
338
339     DEBUG_Printf(DBG_CHN_TRACE, 
340                  "Exiting debugger      PC=%lx EFL=%08lx mode=%d count=%d\n",
341 #ifdef __i386__
342                  DEBUG_context.Eip, DEBUG_context.EFlags, 
343 #else
344                  0L, 0L,
345 #endif
346                  DEBUG_CurrThread->dbg_exec_mode, DEBUG_CurrThread->dbg_exec_count);
347
348     return ret;
349 }
350
351 static  BOOL    DEBUG_HandleDebugEvent(DEBUG_EVENT* de, LPDWORD cont)
352 {
353     char                buffer[256];
354     BOOL                ret;
355     
356     DEBUG_CurrPid = de->dwProcessId;
357     DEBUG_CurrTid = de->dwThreadId;
358
359     __TRY {
360         ret = TRUE;
361         *cont = 0L;
362         
363         if ((DEBUG_CurrProcess = DEBUG_GetProcess(de->dwProcessId)) != NULL)
364             DEBUG_CurrThread = DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId);
365         else 
366             DEBUG_CurrThread = NULL;
367         
368         switch (de->dwDebugEventCode) {
369         case EXCEPTION_DEBUG_EVENT:
370             if (!DEBUG_CurrThread) {
371                 DEBUG_Printf(DBG_CHN_ERR, "%08lx:%08lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
372                              de->dwProcessId, de->dwThreadId);
373                 break;
374             }
375             
376             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exception code=%08lx\n", 
377                          de->dwProcessId, de->dwThreadId, 
378                          de->u.Exception.ExceptionRecord.ExceptionCode);
379
380             if (DEBUG_CurrProcess->continue_on_first_exception) {
381                 DEBUG_CurrProcess->continue_on_first_exception = FALSE;
382                 if (!DBG_IVAR(BreakOnAttach)) {
383                     *cont = DBG_CONTINUE;
384                     break;
385                 }
386             }
387
388             DEBUG_context.ContextFlags =  CONTEXT_CONTROL
389                                         | CONTEXT_INTEGER
390 #ifdef CONTEXT_SEGMENTS
391                                         | CONTEXT_SEGMENTS
392 #endif
393 #ifdef CONTEXT_DEBUG_REGISTERS
394                                         | CONTEXT_DEBUG_REGISTERS
395 #endif
396                                         ;
397
398             if (!GetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context)) {
399                 DEBUG_Printf(DBG_CHN_WARN, "Can't get thread's context\n");
400                 break;
401             }
402             
403             *cont = DEBUG_HandleException(&de->u.Exception.ExceptionRecord, 
404                                           de->u.Exception.dwFirstChance, 
405                                           DEBUG_CurrThread->wait_for_first_exception);
406             if (DEBUG_CurrThread->dbg_exec_mode == EXEC_KILL) {
407                 ret = FALSE;
408             } else {
409                 DEBUG_CurrThread->wait_for_first_exception = 0;
410                 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
411             }
412             break;
413             
414         case CREATE_THREAD_DEBUG_EVENT:
415             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create thread D @%08lx\n", de->dwProcessId, de->dwThreadId, 
416                          (unsigned long)(LPVOID)de->u.CreateThread.lpStartAddress);
417             
418             if (DEBUG_CurrProcess == NULL) {
419                 DEBUG_Printf(DBG_CHN_ERR, "Unknown process\n");
420                 break;
421             }
422             if (DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId) != NULL) {
423                 DEBUG_Printf(DBG_CHN_TRACE, "Thread already listed, skipping\n");
424                 break;
425             }
426             
427             DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess, 
428                                                de->dwThreadId, 
429                                                de->u.CreateThread.hThread, 
430                                                de->u.CreateThread.lpStartAddress, 
431                                                de->u.CreateThread.lpThreadLocalBase);
432             if (!DEBUG_CurrThread) {
433                 DEBUG_Printf(DBG_CHN_ERR, "Couldn't create thread\n");
434                 break;
435             }
436             DEBUG_InitCurrThread();
437             break;
438             
439         case CREATE_PROCESS_DEBUG_EVENT:
440             DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer), 
441                                            de->u.CreateProcessInfo.hProcess, 
442                                            de->u.CreateProcessInfo.lpImageName);
443             
444             /* FIXME unicode ? de->u.CreateProcessInfo.fUnicode */
445             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create process %s @%08lx (%ld<%ld>)\n", 
446                          de->dwProcessId, de->dwThreadId, 
447                          buffer,
448                          (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress,
449                          de->u.CreateProcessInfo.dwDebugInfoFileOffset,
450                          de->u.CreateProcessInfo.nDebugInfoSize);
451             
452             if ((DEBUG_CurrProcess = DEBUG_GetProcess(de->dwProcessId)) != NULL) {
453                 if (DEBUG_CurrProcess->handle) {
454                     DEBUG_Printf(DBG_CHN_ERR, "Skipping already defined process\n");
455                     break;
456                 }
457                 DEBUG_CurrProcess->handle = de->u.CreateProcessInfo.hProcess;
458             } else {
459                 DEBUG_CurrProcess = DEBUG_AddProcess(de->dwProcessId,
460                                                      de->u.CreateProcessInfo.hProcess);
461                 if (DEBUG_CurrProcess == NULL) {
462                     DEBUG_Printf(DBG_CHN_ERR, "Unknown process\n");
463                     break;
464                 }
465             }
466             
467             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create thread I @%08lx\n", 
468                          de->dwProcessId, de->dwThreadId, 
469                          (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress);
470             
471             DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,       
472                                                de->dwThreadId, 
473                                                de->u.CreateProcessInfo.hThread, 
474                                                de->u.CreateProcessInfo.lpStartAddress, 
475                                                de->u.CreateProcessInfo.lpThreadLocalBase);
476             if (!DEBUG_CurrThread) {
477                 DEBUG_Printf(DBG_CHN_ERR, "Couldn't create thread\n");
478                 break;
479             }
480             
481             DEBUG_InitCurrProcess();
482             DEBUG_InitCurrThread();
483
484             DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer), 
485                                            DEBUG_CurrThread->process->handle, 
486                                            de->u.CreateProcessInfo.lpImageName);
487             DEBUG_LoadModule32(buffer[0] ? buffer : "<Debugged process>",
488                                de->u.CreateProcessInfo.hFile, 
489                                (DWORD)de->u.CreateProcessInfo.lpBaseOfImage);
490
491             if (buffer[0])  /* we got a process name */
492             {
493                 DWORD type;
494                 if (!GetBinaryTypeA( buffer, &type ))
495                 {
496                     /* not a Windows binary, assume it's a Unix executable then */
497                     DOS_FULL_NAME fullname;
498                     /* HACK!! should fix DEBUG_ReadExecutableDbgInfo to accept DOS filenames */
499                     if (DOSFS_GetFullName( buffer, TRUE, &fullname ))
500                     {
501                         DEBUG_ReadExecutableDbgInfo( fullname.long_name );
502                         break;
503                     }
504                 }
505             }
506             /* if it is a Windows binary, or an invalid or missing file name,
507              * we use wine itself as the main executable */
508             DEBUG_ReadExecutableDbgInfo( "wine" );
509             break;
510             
511         case EXIT_THREAD_DEBUG_EVENT:
512             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exit thread (%ld)\n", 
513                          de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
514             
515             if (DEBUG_CurrThread == NULL) {
516                 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
517                 break;
518             }
519             /* FIXME: remove break point set on thread startup */
520             DEBUG_DelThread(DEBUG_CurrThread);
521             break;
522             
523         case EXIT_PROCESS_DEBUG_EVENT:
524             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exit process (%ld)\n", 
525                          de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
526             
527             if (DEBUG_CurrProcess == NULL) {
528                 DEBUG_Printf(DBG_CHN_ERR, "Unknown process\n");
529                 break;
530             }
531             /* just in case */
532             DEBUG_SetBreakpoints(FALSE);
533             /* kill last thread */
534             DEBUG_DelThread(DEBUG_CurrProcess->threads);
535             DEBUG_DelProcess(DEBUG_CurrProcess);
536             ret = FALSE;
537             break;
538             
539         case LOAD_DLL_DEBUG_EVENT:
540             if (DEBUG_CurrThread == NULL) {
541                 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
542                 break;
543             }
544             DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer), 
545                                            DEBUG_CurrThread->process->handle, 
546                                            de->u.LoadDll.lpImageName);
547             
548             /* FIXME unicode: de->u.LoadDll.fUnicode */
549             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: loads DLL %s @%08lx (%ld<%ld>)\n", 
550                          de->dwProcessId, de->dwThreadId, 
551                          buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll,
552                          de->u.LoadDll.dwDebugInfoFileOffset,
553                          de->u.LoadDll.nDebugInfoSize);
554             CharUpper(buffer);
555             DEBUG_LoadModule32(buffer, de->u.LoadDll.hFile, (DWORD)de->u.LoadDll.lpBaseOfDll);
556             break;
557             
558         case UNLOAD_DLL_DEBUG_EVENT:
559             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: unload DLL @%08lx\n", de->dwProcessId, de->dwThreadId, 
560                          (unsigned long)de->u.UnloadDll.lpBaseOfDll);
561             break;
562             
563         case OUTPUT_DEBUG_STRING_EVENT:
564             if (DEBUG_CurrThread == NULL) {
565                 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
566                 break;
567             }
568             
569             DEBUG_ProcessGetString(buffer, sizeof(buffer), 
570                                    DEBUG_CurrThread->process->handle, 
571                                    de->u.DebugString.lpDebugStringData);
572             
573             /* fixme unicode de->u.DebugString.fUnicode ? */
574             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: output debug string (%s)\n", 
575                          de->dwProcessId, de->dwThreadId, buffer);
576             break;
577             
578         case RIP_EVENT:
579             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: rip error=%ld type=%ld\n", 
580                          de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError, 
581                          de->u.RipInfo.dwType);
582             break;
583             
584         default:
585             DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: unknown event (%ld)\n", 
586                          de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
587         }
588         
589     } __EXCEPT(wine_dbg) {
590         *cont = 0;
591         ret = TRUE;
592     }
593     __ENDTRY;
594
595     return ret;
596 }
597
598 static  DWORD   DEBUG_MainLoop(DWORD pid)
599 {
600     DEBUG_EVENT         de;
601     DWORD               cont;
602     BOOL                ret = TRUE;
603
604     DEBUG_Printf(DBG_CHN_MESG, " on pid %ld\n", pid);
605     
606     while (ret && WaitForDebugEvent(&de, INFINITE)) {
607         ret = DEBUG_HandleDebugEvent(&de, &cont);
608         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, cont);
609     }
610     
611     DEBUG_Printf(DBG_CHN_MESG, "WineDbg terminated on pid %ld\n", pid);
612
613     return 0;
614 }
615
616 int DEBUG_main(int argc, char** argv)
617 {
618     DWORD       pid = 0, retv = 0;
619
620 #ifdef DBG_need_heap
621     /* Initialize the debugger heap. */
622     dbg_heap = HeapCreate(HEAP_NO_SERIALIZE, 0x1000, 0x8000000); /* 128MB */
623 #endif
624     
625     /* Initialize the type handling stuff. */
626     DEBUG_InitTypes();
627     DEBUG_InitCVDataTypes();    
628
629     /* Initialize internal vars (types must be initialized before) */
630     if (!DEBUG_IntVarsRW(TRUE)) return -1;
631
632     /* keep it as a guiexe for now, so that Wine won't touch the Unix stdin, 
633      * stdout and stderr streams
634      */
635     if (DBG_IVAR(UseXTerm)) {
636         COORD           pos;
637         
638         /* This is a hack: it forces creation of an xterm, not done by default */
639         pos.X = 0; pos.Y = 1;
640         SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
641     }
642
643     DEBUG_Printf(DBG_CHN_MESG, "Starting WineDbg... ");
644     if (argc == 3) {
645         HANDLE  hEvent;
646
647         if ((pid = atoi(argv[1])) != 0 && (hEvent = atoi(argv[2])) != 0) {
648             if (!(DEBUG_CurrProcess = DEBUG_AddProcess(pid, 0))) goto leave;
649             DEBUG_CurrProcess->continue_on_first_exception = TRUE;
650
651             if (!DebugActiveProcess(pid)) {
652                 DEBUG_Printf(DBG_CHN_ERR, "Can't attach process %ld: %ld\n", 
653                              pid, GetLastError());
654                 SetEvent(hEvent);
655                 goto leave;
656             }
657             SetEvent(hEvent);
658         } else {
659             pid = 0;
660         }
661     }
662     if (argc == 1) {
663         LPSTR   org, ptr;
664
665         DEBUG_Printf(DBG_CHN_MESG, "\n");
666         DEBUG_WalkProcess();
667         pid = strtol(org = readline("Enter pid to debug: "), &ptr, 0);
668         if (pid && ptr && ptr != org && *ptr == '\0') {
669             if (!(DEBUG_CurrProcess = DEBUG_AddProcess(pid, 0))) goto leave;
670
671             if (!DebugActiveProcess(pid)) {
672                 DEBUG_Printf(DBG_CHN_ERR, "Can't attach process %ld: %ld\n", 
673                              pid, GetLastError());
674                 goto leave;
675             }
676         } else {
677             pid = 0;
678         }
679     }
680         
681     if (pid == 0) {
682         PROCESS_INFORMATION     info;
683         STARTUPINFOA            startup;
684
685         memset(&startup, 0, sizeof(startup));
686         startup.cb = sizeof(startup);
687         startup.dwFlags = STARTF_USESHOWWINDOW;
688         startup.wShowWindow = SW_SHOWNORMAL;
689
690         if (!CreateProcess(NULL, argv[1], NULL, NULL, 
691                            FALSE, DEBUG_PROCESS, NULL, NULL, &startup, &info)) {
692             DEBUG_Printf(DBG_CHN_MESG, "Couldn't start process '%s'\n", argv[1]);
693             goto leave;
694         }
695         pid = info.dwProcessId;
696     }
697
698     if (pid) retv = DEBUG_MainLoop(pid);
699  leave:
700     /* saves modified variables */
701     DEBUG_IntVarsRW(FALSE);
702
703     return retv;
704 }
705
706