winefile: Fix the French translation (with some help from Michael Stefaniuc).
[wine] / programs / winedbg / tgt_active.c
1 /*
2  * Wine debugger - back-end for an active target
3  *
4  * Copyright 2000-2006 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdarg.h>
27
28 #include "debugger.h"
29 #include "psapi.h"
30 #include "winternl.h"
31 #include "wine/debug.h"
32 #include "wine/exception.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
35
36 static char*            dbg_last_cmd_line;
37 static struct be_process_io be_process_active_io;
38
39 static void dbg_init_current_process(void)
40 {
41 }
42
43 static void dbg_init_current_thread(void* start)
44 {
45     if (start)
46     {
47         if (dbg_curr_process->threads && 
48             !dbg_curr_process->threads->next && /* first thread ? */
49             DBG_IVAR(BreakAllThreadsStartup)) 
50         {
51             ADDRESS64   addr;
52
53             break_set_xpoints(FALSE);
54             addr.Mode   = AddrModeFlat;
55             addr.Offset = (DWORD)start;
56             break_add_break(&addr, TRUE, TRUE);
57             break_set_xpoints(TRUE);
58         }
59     } 
60 }
61
62 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de);
63
64 /******************************************************************
65  *              dbg_attach_debuggee
66  *
67  * Sets the debuggee to <pid>
68  * cofe instructs winedbg what to do when first exception is received 
69  * (break=FALSE, continue=TRUE)
70  * wfe is set to TRUE if dbg_attach_debuggee should also proceed with all debug events
71  * until the first exception is received (aka: attach to an already running process)
72  */
73 BOOL dbg_attach_debuggee(DWORD pid, BOOL cofe)
74 {
75     if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, pid, 0))) return FALSE;
76
77     if (!DebugActiveProcess(pid)) 
78     {
79         dbg_printf("Can't attach process %04x: error %u\n", pid, GetLastError());
80         dbg_del_process(dbg_curr_process);
81         return FALSE;
82     }
83     dbg_curr_process->continue_on_first_exception = cofe;
84
85     SetEnvironmentVariableA("DBGHELP_NOLIVE", NULL);
86
87     dbg_curr_process->active_debuggee = TRUE;
88     return TRUE;
89 }
90
91 static unsigned dbg_fetch_context(void)
92 {
93     dbg_context.ContextFlags = CONTEXT_CONTROL
94         | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT
95 #ifdef CONTEXT_SEGMENTS
96         | CONTEXT_SEGMENTS
97 #endif
98 #ifdef CONTEXT_DEBUG_REGISTERS
99         | CONTEXT_DEBUG_REGISTERS
100 #endif
101         ;
102     if (!GetThreadContext(dbg_curr_thread->handle, &dbg_context))
103     {
104         WINE_WARN("Can't get thread's context\n");
105         return FALSE;
106     }
107     return TRUE;
108 }
109
110 /***********************************************************************
111  *              dbg_exception_prolog
112  *
113  * Examine exception and decide if interactive mode is entered(return TRUE)
114  * or exception is silently continued(return FALSE)
115  * is_debug means the exception is a breakpoint or single step exception
116  */
117 static unsigned dbg_exception_prolog(BOOL is_debug, BOOL first_chance, const EXCEPTION_RECORD* rec)
118 {
119     ADDRESS64   addr;
120     BOOL        is_break;
121     char        hexbuf[MAX_OFFSET_TO_STR_LEN];
122
123     memory_get_current_pc(&addr);
124     break_suspend_execution();
125     dbg_curr_thread->excpt_record = *rec;
126     dbg_curr_thread->in_exception = TRUE;
127
128     if (!is_debug)
129     {
130         switch (addr.Mode)
131         {
132         case AddrModeFlat:
133             dbg_printf(" in 32-bit code (%s)",
134                        memory_offset_to_string(hexbuf, addr.Offset, 0));
135             break;
136         case AddrModeReal:
137             dbg_printf(" in vm86 code (%04x:%04x)", addr.Segment, (unsigned) addr.Offset);
138             break;
139         case AddrMode1616:
140             dbg_printf(" in 16-bit code (%04x:%04x)", addr.Segment, (unsigned) addr.Offset);
141             break;
142         case AddrMode1632:
143             dbg_printf(" in 32-bit code (%04x:%08lx)", addr.Segment, (unsigned long) addr.Offset);
144             break;
145         default: dbg_printf(" bad address");
146         }
147         dbg_printf(".\n");
148     }
149
150     /* this will resynchronize builtin dbghelp's internal ELF module list */
151     SymLoadModule(dbg_curr_process->handle, 0, 0, 0, 0, 0);
152
153     if (is_debug) break_adjust_pc(&addr, rec->ExceptionCode, first_chance, &is_break);
154     /*
155      * Do a quiet backtrace so that we have an idea of what the situation
156      * is WRT the source files.
157      */
158     stack_fetch_frames();
159
160     if (is_debug && !is_break && break_should_continue(&addr, rec->ExceptionCode))
161         return FALSE;
162
163     if (addr.Mode != dbg_curr_thread->addr_mode)
164     {
165         const char* name = NULL;
166         
167         switch (addr.Mode)
168         {
169         case AddrMode1616: name = "16 bit";     break;
170         case AddrMode1632: name = "32 bit";     break;
171         case AddrModeReal: name = "vm86";       break;
172         case AddrModeFlat: name = "32 bit";     break;
173         }
174         
175         dbg_printf("In %s mode.\n", name);
176         dbg_curr_thread->addr_mode = addr.Mode;
177     }
178     display_print();
179
180     if (!is_debug)
181     {
182         /* This is a real crash, dump some info */
183         be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
184         stack_info();
185         be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
186         stack_backtrace(dbg_curr_tid);
187     }
188     else
189     {
190         static char*        last_name;
191         static char*        last_file;
192
193         char                buffer[sizeof(SYMBOL_INFO) + 256];
194         SYMBOL_INFO*        si = (SYMBOL_INFO*)buffer;
195         void*               lin = memory_to_linear_addr(&addr);
196         DWORD64             disp64;
197         IMAGEHLP_LINE       il;
198         DWORD               disp;
199
200         si->SizeOfStruct = sizeof(*si);
201         si->MaxNameLen   = 256;
202         il.SizeOfStruct = sizeof(il);
203         if (SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si) &&
204             SymGetLineFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
205         {
206             if ((!last_name || strcmp(last_name, si->Name)) ||
207                 (!last_file || strcmp(last_file, il.FileName)))
208             {
209                 HeapFree(GetProcessHeap(), 0, last_name);
210                 HeapFree(GetProcessHeap(), 0, last_file);
211                 last_name = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(si->Name) + 1), si->Name);
212                 last_file = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(il.FileName) + 1), il.FileName);
213                 dbg_printf("%s () at %s:%u\n", last_name, last_file, il.LineNumber);
214             }
215         }
216     }
217     if (!is_debug || is_break ||
218         dbg_curr_thread->exec_mode == dbg_exec_step_over_insn ||
219         dbg_curr_thread->exec_mode == dbg_exec_step_into_insn)
220     {
221         ADDRESS64 tmp = addr;
222         /* Show where we crashed */
223         memory_disasm_one_insn(&tmp);
224     }
225     source_list_from_addr(&addr, 0);
226
227     return TRUE;
228 }
229
230 static void dbg_exception_epilog(void)
231 {
232     break_restart_execution(dbg_curr_thread->exec_count);
233     /*
234      * This will have gotten absorbed into the breakpoint info
235      * if it was used.  Otherwise it would have been ignored.
236      * In any case, we don't mess with it any more.
237      */
238     if (dbg_curr_thread->exec_mode == dbg_exec_cont)
239         dbg_curr_thread->exec_count = 0;
240     dbg_curr_thread->in_exception = FALSE;
241 }
242
243 static DWORD dbg_handle_exception(const EXCEPTION_RECORD* rec, BOOL first_chance)
244 {
245     BOOL                is_debug = FALSE;
246     THREADNAME_INFO*    pThreadName;
247     struct dbg_thread*  pThread;
248
249     assert(dbg_curr_thread);
250
251     WINE_TRACE("exception=%x first_chance=%c\n",
252                rec->ExceptionCode, first_chance ? 'Y' : 'N');
253
254     switch (rec->ExceptionCode)
255     {
256     case EXCEPTION_BREAKPOINT:
257     case EXCEPTION_SINGLE_STEP:
258         is_debug = TRUE;
259         break;
260     case EXCEPTION_NAME_THREAD:
261         pThreadName = (THREADNAME_INFO*)(rec->ExceptionInformation);
262         if (pThreadName->dwThreadID == -1)
263             pThread = dbg_curr_thread;
264         else
265             pThread = dbg_get_thread(dbg_curr_process, pThreadName->dwThreadID);
266         if(!pThread)
267         {
268             dbg_printf("Thread ID=%04x not in our list of threads -> can't rename\n", pThreadName->dwThreadID);
269             return DBG_CONTINUE;
270         }
271         if (dbg_read_memory(pThreadName->szName, pThread->name, 9))
272             dbg_printf("Thread ID=%04x renamed using MS VC6 extension (name==\"%s\")\n",
273                        pThread->tid, pThread->name);
274         return DBG_CONTINUE;
275     }
276
277     if (first_chance && !is_debug && !DBG_IVAR(BreakOnFirstChance) &&
278         !(rec->ExceptionFlags & EH_STACK_INVALID))
279     {
280         /* pass exception to program except for debug exceptions */
281         return DBG_EXCEPTION_NOT_HANDLED;
282     }
283
284     if (!is_debug)
285     {
286         /* print some infos */
287         dbg_printf("%s: ",
288                    first_chance ? "First chance exception" : "Unhandled exception");
289         switch (rec->ExceptionCode)
290         {
291         case EXCEPTION_INT_DIVIDE_BY_ZERO:
292             dbg_printf("divide by zero");
293             break;
294         case EXCEPTION_INT_OVERFLOW:
295             dbg_printf("overflow");
296             break;
297         case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
298             dbg_printf("array bounds");
299             break;
300         case EXCEPTION_ILLEGAL_INSTRUCTION:
301             dbg_printf("illegal instruction");
302             break;
303         case EXCEPTION_STACK_OVERFLOW:
304             dbg_printf("stack overflow");
305             break;
306         case EXCEPTION_PRIV_INSTRUCTION:
307             dbg_printf("privileged instruction");
308             break;
309         case EXCEPTION_ACCESS_VIOLATION:
310             if (rec->NumberParameters == 2)
311                 dbg_printf("page fault on %s access to 0x%08lx",
312                            rec->ExceptionInformation[0] == EXCEPTION_WRITE_FAULT ? "write" :
313                            rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT ? "execute" : "read",
314                            rec->ExceptionInformation[1]);
315             else
316                 dbg_printf("page fault");
317             break;
318         case EXCEPTION_DATATYPE_MISALIGNMENT:
319             dbg_printf("Alignment");
320             break;
321         case DBG_CONTROL_C:
322             dbg_printf("^C");
323             break;
324         case CONTROL_C_EXIT:
325             dbg_printf("^C");
326             break;
327         case STATUS_POSSIBLE_DEADLOCK:
328         {
329             ADDRESS64       addr;
330
331             addr.Mode   = AddrModeFlat;
332             addr.Offset = rec->ExceptionInformation[0];
333
334             dbg_printf("wait failed on critical section ");
335             print_address(&addr, FALSE);
336         }
337         if (!DBG_IVAR(BreakOnCritSectTimeOut))
338         {
339             dbg_printf("\n");
340             return DBG_EXCEPTION_NOT_HANDLED;
341         }
342         break;
343         case EXCEPTION_WINE_STUB:
344         {
345             char dll[32], name[64];
346             memory_get_string(dbg_curr_process,
347                               (void*)rec->ExceptionInformation[0], TRUE, FALSE,
348                               dll, sizeof(dll));
349             if (HIWORD(rec->ExceptionInformation[1]))
350                 memory_get_string(dbg_curr_process,
351                                   (void*)rec->ExceptionInformation[1], TRUE, FALSE,
352                                   name, sizeof(name));
353             else
354                 sprintf( name, "%ld", rec->ExceptionInformation[1] );
355             dbg_printf("unimplemented function %s.%s called", dll, name);
356         }
357         break;
358         case EXCEPTION_WINE_ASSERTION:
359             dbg_printf("assertion failed");
360             break;
361         case EXCEPTION_VM86_INTx:
362             dbg_printf("interrupt %02lx in vm86 mode", rec->ExceptionInformation[0]);
363             break;
364         case EXCEPTION_VM86_STI:
365             dbg_printf("sti in vm86 mode");
366             break;
367         case EXCEPTION_VM86_PICRETURN:
368             dbg_printf("PIC return in vm86 mode");
369             break;
370         case EXCEPTION_FLT_DENORMAL_OPERAND:
371             dbg_printf("denormal float operand");
372             break;
373         case EXCEPTION_FLT_DIVIDE_BY_ZERO:
374             dbg_printf("divide by zero");
375             break;
376         case EXCEPTION_FLT_INEXACT_RESULT:
377             dbg_printf("inexact float result");
378             break;
379         case EXCEPTION_FLT_INVALID_OPERATION:
380             dbg_printf("invalid float operation");
381             break;
382         case EXCEPTION_FLT_OVERFLOW:
383             dbg_printf("floating pointer overflow");
384             break;
385         case EXCEPTION_FLT_UNDERFLOW:
386             dbg_printf("floating pointer underflow");
387             break;
388         case EXCEPTION_FLT_STACK_CHECK:
389             dbg_printf("floating point stack check");
390             break;
391         case CXX_EXCEPTION:
392             if(rec->NumberParameters == 3 && rec->ExceptionInformation[0] == CXX_FRAME_MAGIC)
393                 dbg_printf("C++ exception(object = 0x%08lx, type = 0x%08lx)",
394                            rec->ExceptionInformation[1], rec->ExceptionInformation[2]);
395             else
396                 dbg_printf("C++ exception with strange parameter count %d or magic 0x%08lx",
397                            rec->NumberParameters, rec->ExceptionInformation[0]);
398             break;
399         default:
400             dbg_printf("0x%08x", rec->ExceptionCode);
401             break;
402         }
403     }
404     if( (rec->ExceptionFlags & EH_STACK_INVALID) ) {
405         dbg_printf( ", invalid program stack" );
406     }
407
408     if (dbg_exception_prolog(is_debug, first_chance, rec))
409     {
410         dbg_interactiveP = TRUE;
411         return 0;
412     }
413     dbg_exception_epilog();
414
415     return DBG_CONTINUE;
416 }
417
418 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill);
419
420 static void fetch_module_name(void* name_addr, BOOL unicode, void* mod_addr,
421                               char* buffer, size_t bufsz, BOOL is_pcs)
422 {
423     memory_get_string_indirect(dbg_curr_process, name_addr, unicode, buffer, bufsz);
424     if (!buffer[0] &&
425         !GetModuleFileNameExA(dbg_curr_process->handle, mod_addr, buffer, bufsz))
426     {
427         if (is_pcs)
428         {
429             HMODULE h;
430             WORD (WINAPI *gpif)(HANDLE, LPSTR, DWORD);
431
432             /* On Windows, when we get the process creation debug event for a process
433              * created by winedbg, the modules' list is not initialized yet. Hence,
434              * GetModuleFileNameExA (on the main module) will generate an error.
435              * Psapi (starting on XP) provides GetProcessImageFileName() which should
436              * give us the expected result
437              */
438             if (!(h = GetModuleHandleA("psapi")) ||
439                 !(gpif = (void*)GetProcAddress(h, "GetProcessImageFileName")) ||
440                 !(gpif)(dbg_curr_process->handle, buffer, bufsz))
441                 snprintf(buffer, bufsz, "Process_%08x", dbg_curr_pid);
442         }
443         else
444             snprintf(buffer, bufsz, "DLL_%p", mod_addr);
445     }
446 }
447
448 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de)
449 {
450     char        buffer[256];
451     DWORD       cont = DBG_CONTINUE;
452
453     dbg_curr_pid = de->dwProcessId;
454     dbg_curr_tid = de->dwThreadId;
455
456     if ((dbg_curr_process = dbg_get_process(de->dwProcessId)) != NULL)
457         dbg_curr_thread = dbg_get_thread(dbg_curr_process, de->dwThreadId);
458     else
459         dbg_curr_thread = NULL;
460
461     switch (de->dwDebugEventCode)
462     {
463     case EXCEPTION_DEBUG_EVENT:
464         if (!dbg_curr_thread)
465         {
466             WINE_ERR("%04x:%04x: not a registered process or thread (perhaps a 16 bit one ?)\n",
467                      de->dwProcessId, de->dwThreadId);
468             break;
469         }
470
471         WINE_TRACE("%04x:%04x: exception code=%08x\n",
472                    de->dwProcessId, de->dwThreadId,
473                    de->u.Exception.ExceptionRecord.ExceptionCode);
474
475         if (dbg_curr_process->continue_on_first_exception)
476         {
477             dbg_curr_process->continue_on_first_exception = FALSE;
478             if (!DBG_IVAR(BreakOnAttach)) break;
479         }
480         if (dbg_fetch_context())
481         {
482             cont = dbg_handle_exception(&de->u.Exception.ExceptionRecord,
483                                         de->u.Exception.dwFirstChance);
484             if (cont && dbg_curr_thread)
485             {
486                 SetThreadContext(dbg_curr_thread->handle, &dbg_context);
487             }
488         }
489         break;
490
491     case CREATE_PROCESS_DEBUG_EVENT:
492         dbg_curr_process = dbg_add_process(&be_process_active_io, de->dwProcessId,
493                                            de->u.CreateProcessInfo.hProcess);
494         if (dbg_curr_process == NULL)
495         {
496             WINE_ERR("Couldn't create process\n");
497             break;
498         }
499         fetch_module_name(de->u.CreateProcessInfo.lpImageName,
500                           de->u.CreateProcessInfo.fUnicode,
501                           de->u.CreateProcessInfo.lpBaseOfImage,
502                           buffer, sizeof(buffer), TRUE);
503
504         WINE_TRACE("%04x:%04x: create process '%s'/%p @%p (%u<%u>)\n",
505                    de->dwProcessId, de->dwThreadId,
506                    buffer, de->u.CreateProcessInfo.lpImageName,
507                    de->u.CreateProcessInfo.lpStartAddress,
508                    de->u.CreateProcessInfo.dwDebugInfoFileOffset,
509                    de->u.CreateProcessInfo.nDebugInfoSize);
510         dbg_set_process_name(dbg_curr_process, buffer);
511
512         if (!SymInitialize(dbg_curr_process->handle, NULL, FALSE))
513             dbg_printf("Couldn't initiate DbgHelp\n");
514         if (!SymLoadModule(dbg_curr_process->handle, de->u.CreateProcessInfo.hFile, buffer, NULL,
515                            (unsigned long)de->u.CreateProcessInfo.lpBaseOfImage, 0))
516             dbg_printf("couldn't load main module (%u)\n", GetLastError());
517
518         WINE_TRACE("%04x:%04x: create thread I @%p\n",
519                    de->dwProcessId, de->dwThreadId, de->u.CreateProcessInfo.lpStartAddress);
520
521         dbg_curr_thread = dbg_add_thread(dbg_curr_process,
522                                          de->dwThreadId,
523                                          de->u.CreateProcessInfo.hThread,
524                                          de->u.CreateProcessInfo.lpThreadLocalBase);
525         if (!dbg_curr_thread)
526         {
527             WINE_ERR("Couldn't create thread\n");
528             break;
529         }
530         dbg_init_current_process();
531         dbg_init_current_thread(de->u.CreateProcessInfo.lpStartAddress);
532         break;
533
534     case EXIT_PROCESS_DEBUG_EVENT:
535         WINE_TRACE("%04x:%04x: exit process (%d)\n",
536                    de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
537
538         if (dbg_curr_process == NULL)
539         {
540             WINE_ERR("Unknown process\n");
541             break;
542         }
543         tgt_process_active_close_process(dbg_curr_process, FALSE);
544         dbg_printf("Process of pid=%04x has terminated\n", de->dwProcessId);
545         break;
546
547     case CREATE_THREAD_DEBUG_EVENT:
548         WINE_TRACE("%04x:%04x: create thread D @%p\n",
549                    de->dwProcessId, de->dwThreadId, de->u.CreateThread.lpStartAddress);
550
551         if (dbg_curr_process == NULL)
552         {
553             WINE_ERR("Unknown process\n");
554             break;
555         }
556         if (dbg_get_thread(dbg_curr_process, de->dwThreadId) != NULL)
557         {
558             WINE_TRACE("Thread already listed, skipping\n");
559             break;
560         }
561
562         dbg_curr_thread = dbg_add_thread(dbg_curr_process,
563                                          de->dwThreadId,
564                                          de->u.CreateThread.hThread,
565                                          de->u.CreateThread.lpThreadLocalBase);
566         if (!dbg_curr_thread)
567         {
568             WINE_ERR("Couldn't create thread\n");
569             break;
570         }
571         dbg_init_current_thread(de->u.CreateThread.lpStartAddress);
572         break;
573
574     case EXIT_THREAD_DEBUG_EVENT:
575         WINE_TRACE("%04x:%04x: exit thread (%d)\n",
576                    de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
577
578         if (dbg_curr_thread == NULL)
579         {
580             WINE_ERR("Unknown thread\n");
581             break;
582         }
583         /* FIXME: remove break point set on thread startup */
584         dbg_del_thread(dbg_curr_thread);
585         break;
586
587     case LOAD_DLL_DEBUG_EVENT:
588         if (dbg_curr_thread == NULL)
589         {
590             WINE_ERR("Unknown thread\n");
591             break;
592         }
593         fetch_module_name(de->u.LoadDll.lpImageName,
594                           de->u.LoadDll.fUnicode,
595                           de->u.LoadDll.lpBaseOfDll,
596                           buffer, sizeof(buffer), FALSE);
597
598         WINE_TRACE("%04x:%04x: loads DLL %s @%p (%u<%u>)\n",
599                    de->dwProcessId, de->dwThreadId,
600                    buffer, de->u.LoadDll.lpBaseOfDll,
601                    de->u.LoadDll.dwDebugInfoFileOffset,
602                    de->u.LoadDll.nDebugInfoSize);
603         SymLoadModule(dbg_curr_process->handle, de->u.LoadDll.hFile, buffer, NULL,
604                       (unsigned long)de->u.LoadDll.lpBaseOfDll, 0);
605         break_set_xpoints(FALSE);
606         break_check_delayed_bp();
607         break_set_xpoints(TRUE);
608         if (DBG_IVAR(BreakOnDllLoad))
609         {
610             dbg_printf("Stopping on DLL %s loading at 0x%08lx\n",
611                        buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll);
612             if (dbg_fetch_context()) cont = 0;
613         }
614         break;
615
616     case UNLOAD_DLL_DEBUG_EVENT:
617         WINE_TRACE("%04x:%04x: unload DLL @%p\n",
618                    de->dwProcessId, de->dwThreadId,
619                    de->u.UnloadDll.lpBaseOfDll);
620         break_delete_xpoints_from_module((unsigned long)de->u.UnloadDll.lpBaseOfDll);
621         SymUnloadModule(dbg_curr_process->handle, 
622                         (unsigned long)de->u.UnloadDll.lpBaseOfDll);
623         break;
624
625     case OUTPUT_DEBUG_STRING_EVENT:
626         if (dbg_curr_thread == NULL)
627         {
628             WINE_ERR("Unknown thread\n");
629             break;
630         }
631
632         memory_get_string(dbg_curr_process,
633                           de->u.DebugString.lpDebugStringData, TRUE,
634                           de->u.DebugString.fUnicode, buffer, sizeof(buffer));
635         WINE_TRACE("%04x:%04x: output debug string (%s)\n",
636                    de->dwProcessId, de->dwThreadId, buffer);
637         break;
638
639     case RIP_EVENT:
640         WINE_TRACE("%04x:%04x: rip error=%u type=%u\n",
641                    de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
642                    de->u.RipInfo.dwType);
643         break;
644
645     default:
646         WINE_TRACE("%04x:%04x: unknown event (%x)\n",
647                    de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
648     }
649     if (!cont) return TRUE;  /* stop execution */
650     ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
651     return FALSE;  /* continue execution */
652 }
653
654 static void dbg_resume_debuggee(DWORD cont)
655 {
656     if (dbg_curr_thread->in_exception)
657     {
658         ADDRESS64       addr;
659         char            hexbuf[MAX_OFFSET_TO_STR_LEN];
660
661         dbg_exception_epilog();
662         memory_get_current_pc(&addr);
663         WINE_TRACE("Exiting debugger      PC=%s mode=%d count=%d\n",
664                    memory_offset_to_string(hexbuf, addr.Offset, 0),
665                    dbg_curr_thread->exec_mode,
666                    dbg_curr_thread->exec_count);
667         if (dbg_curr_thread)
668         {
669             if (!SetThreadContext(dbg_curr_thread->handle, &dbg_context))
670                 dbg_printf("Cannot set ctx on %04x\n", dbg_curr_tid);
671         }
672     }
673     dbg_interactiveP = FALSE;
674     if (!ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, cont))
675         dbg_printf("Cannot continue on %04x (%08x)\n", dbg_curr_tid, cont);
676 }
677
678 static void wait_exception(void)
679 {
680     DEBUG_EVENT         de;
681
682     while (dbg_num_processes() && WaitForDebugEvent(&de, INFINITE))
683     {
684         if (dbg_handle_debug_event(&de)) break;
685     }
686     dbg_interactiveP = TRUE;
687 }
688
689 void dbg_wait_next_exception(DWORD cont, int count, int mode)
690 {
691     ADDRESS64           addr;
692     char                hexbuf[MAX_OFFSET_TO_STR_LEN];
693
694     if (cont == DBG_CONTINUE)
695     {
696         dbg_curr_thread->exec_count = count;
697         dbg_curr_thread->exec_mode = mode;
698     }
699     dbg_resume_debuggee(cont);
700
701     wait_exception();
702     if (!dbg_curr_process) return;
703
704     memory_get_current_pc(&addr);
705     WINE_TRACE("Entering debugger     PC=%s mode=%d count=%d\n",
706                memory_offset_to_string(hexbuf, addr.Offset, 0),
707                dbg_curr_thread->exec_mode,
708                dbg_curr_thread->exec_count);
709 }
710
711 void     dbg_active_wait_for_first_exception(void)
712 {
713     dbg_interactiveP = FALSE;
714     /* wait for first exception */
715     wait_exception();
716 }
717
718 static  unsigned dbg_start_debuggee(LPSTR cmdLine)
719 {
720     PROCESS_INFORMATION info;
721     STARTUPINFOA        startup, current;
722     DWORD               flags;
723
724     GetStartupInfoA(&current);
725
726     memset(&startup, 0, sizeof(startup));
727     startup.cb = sizeof(startup);
728     startup.dwFlags = STARTF_USESHOWWINDOW;
729
730     startup.wShowWindow = (current.dwFlags & STARTF_USESHOWWINDOW) ?
731         current.wShowWindow : SW_SHOWNORMAL;
732
733     /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUI:s need it
734      * while GUI:s don't
735      */
736     flags = DEBUG_PROCESS | CREATE_NEW_CONSOLE;
737     if (!DBG_IVAR(AlsoDebugProcChild)) flags |= DEBUG_ONLY_THIS_PROCESS;
738
739     if (!CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, flags,
740                        NULL, NULL, &startup, &info))
741     {
742         dbg_printf("Couldn't start process '%s'\n", cmdLine);
743         return FALSE;
744     }
745     if (!info.dwProcessId)
746     {
747         /* this happens when the program being run is not a Wine binary
748          * (for example, a shell wrapper around a WineLib app)
749          */
750         /* Current fix: list running processes and let the user attach
751          * to one of them (sic)
752          * FIXME: implement a real fix => grab the process (from the
753          * running processes) from its name
754          */
755         dbg_printf("Debuggee has been started (%s)\n"
756                    "But WineDbg isn't attached to it. Maybe you're trying to debug a winelib wrapper ??\n"
757                    "Try to attach to one of those processes:\n", cmdLine);
758         /* FIXME: (HACK) we need some time before the wrapper executes the winelib app */
759         Sleep(100);
760         info_win32_processes();
761         return TRUE;
762     }
763     dbg_curr_pid = info.dwProcessId;
764     if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, dbg_curr_pid, 0))) return FALSE;
765     dbg_curr_process->active_debuggee = TRUE;
766
767     return TRUE;
768 }
769
770 void    dbg_run_debuggee(const char* args)
771 {
772     if (args)
773     {
774         WINE_FIXME("Re-running current program with %s as args is broken\n", args);
775         return;
776     }
777     else 
778     {
779         if (!dbg_last_cmd_line)
780         {
781             dbg_printf("Cannot find previously used command line.\n");
782             return;
783         }
784         dbg_start_debuggee(dbg_last_cmd_line);
785         dbg_active_wait_for_first_exception();
786         source_list_from_addr(NULL, 0);
787     }
788 }
789
790 static BOOL     str2int(const char* str, DWORD* val)
791 {
792     char*   ptr;
793
794     *val = strtol(str, &ptr, 10);
795     return str < ptr && !*ptr;
796 }
797
798
799 /******************************************************************
800  *              dbg_active_attach
801  *
802  * Tries to attach to a running process
803  * Handles the <pid> or <pid> <evt> forms
804  */
805 enum dbg_start  dbg_active_attach(int argc, char* argv[])
806 {
807     DWORD       pid, evt;
808
809     /* try the form <myself> pid */
810     if (argc == 1 && str2int(argv[0], &pid) && pid != 0)
811     {
812         if (!dbg_attach_debuggee(pid, FALSE))
813             return start_error_init;
814     }
815     /* try the form <myself> pid evt (Win32 JIT debugger) */
816     else if (argc == 2 && str2int(argv[0], &pid) && pid != 0 &&
817              str2int(argv[1], &evt) && evt != 0)
818     {
819         if (!dbg_attach_debuggee(pid, TRUE))
820         {
821             /* don't care about result */
822             SetEvent((HANDLE)evt);
823             return start_error_init;
824         }
825         if (!SetEvent((HANDLE)evt))
826         {
827             WINE_ERR("Invalid event handle: %x\n", evt);
828             return start_error_init;
829         }
830         CloseHandle((HANDLE)evt);
831     }
832     else return start_error_parse;
833
834     dbg_curr_pid = pid;
835     return start_ok;
836 }
837
838 /******************************************************************
839  *              dbg_active_launch
840  *
841  * Launches a debuggee (with its arguments) from argc/argv
842  */
843 enum dbg_start    dbg_active_launch(int argc, char* argv[])
844 {
845     int         i, len;
846     LPSTR       cmd_line;
847
848     if (argc == 0) return start_error_parse;
849
850     if (!(cmd_line = HeapAlloc(GetProcessHeap(), 0, len = 1)))
851     {
852     oom_leave:
853         dbg_printf("Out of memory\n");
854         return start_error_init;
855     }
856     cmd_line[0] = '\0';
857
858     for (i = 0; i < argc; i++)
859     {
860         len += strlen(argv[i]) + 1;
861         if (!(cmd_line = HeapReAlloc(GetProcessHeap(), 0, cmd_line, len)))
862             goto oom_leave;
863         strcat(cmd_line, argv[i]);
864         cmd_line[len - 2] = ' ';
865         cmd_line[len - 1] = '\0';
866     }
867
868     if (!dbg_start_debuggee(cmd_line))
869     {
870         HeapFree(GetProcessHeap(), 0, cmd_line);
871         return start_error_init;
872     }
873     HeapFree(GetProcessHeap(), 0, dbg_last_cmd_line);
874     dbg_last_cmd_line = cmd_line;
875     return start_ok;
876 }
877
878 /******************************************************************
879  *              dbg_active_auto
880  *
881  * Starts (<pid> or <pid> <evt>) in automatic mode
882  */
883 enum dbg_start dbg_active_auto(int argc, char* argv[])
884 {
885     HANDLE              hFile;
886     enum dbg_start      ds = start_error_parse;
887
888     if (!strcmp(argv[0], "--auto"))
889     {
890         /* auto mode */
891         argc--; argv++;
892         ds = dbg_active_attach(argc, argv);
893         if (ds != start_ok) return ds;
894         hFile = parser_generate_command_file("echo Modules:", "info share",
895                                              "echo Threads:", "info threads",
896                                              "backtrace", "detach", NULL);
897     }
898     else if (!strcmp(argv[0], "--minidump"))
899     {
900         const char*     file = NULL;
901         char            tmp[8 + 1 + MAX_PATH]; /* minidump <file> */
902
903         argc--; argv++;
904         /* hard stuff now ; we can get things like:
905          * --minidump <pid>                     1 arg
906          * --minidump <pid> <evt>               2 args
907          * --minidump <file> <pid>              2 args
908          * --minidump <file> <pid> <evt>        3 args
909          */
910         switch (argc)
911         {
912         case 1:
913             ds = dbg_active_attach(argc, argv);
914             break;
915         case 2:
916             if ((ds = dbg_active_attach(argc, argv)) != start_ok)
917             {
918                 file = argv[0];
919                 ds = dbg_active_attach(argc - 1, argv + 1);
920             }
921             break;
922         case 3:
923             file = argv[0];
924             ds = dbg_active_attach(argc - 1, argv + 1);
925             break;
926         default:
927             return start_error_parse;
928         }
929         if (ds != start_ok) return ds;
930         memcpy(tmp, "minidump \"", 10);
931         if (!file)
932         {
933             char        path[MAX_PATH];
934
935             GetTempPath(sizeof(path), path);
936             GetTempFileName(path, "WD", 0, tmp + 10);
937         }
938         else strcpy(tmp + 10, file);
939         strcat(tmp, "\"");
940         if (!file)
941         {
942             /* FIXME: should generate unix name as well */
943             dbg_printf("Capturing program state in %s\n", tmp + 9);
944         }
945         hFile = parser_generate_command_file(tmp, "detach", NULL);
946     }
947     else return start_error_parse;
948     if (hFile == INVALID_HANDLE_VALUE) return start_error_parse;
949
950     if (dbg_curr_process->active_debuggee)
951         dbg_active_wait_for_first_exception();
952
953     dbg_interactiveP = TRUE;
954     parser_handle(hFile);
955
956     return start_ok;
957 }
958
959 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill)
960 {
961     if (pcs == dbg_curr_process)
962     {
963         /* remove all set breakpoints in debuggee code */
964         break_set_xpoints(FALSE);
965         /* needed for single stepping (ugly).
966          * should this be handled inside the server ??? 
967          */
968         be_cpu->single_step(&dbg_context, FALSE);
969         if (dbg_curr_thread->in_exception)
970         {
971             SetThreadContext(dbg_curr_thread->handle, &dbg_context);
972             ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, DBG_CONTINUE);
973         }
974         if (!kill && !DebugActiveProcessStop(dbg_curr_pid)) return FALSE;
975     }
976     SymCleanup(pcs->handle);
977     dbg_del_process(pcs);
978
979     return TRUE;
980 }
981
982 static struct be_process_io be_process_active_io =
983 {
984     tgt_process_active_close_process,
985     ReadProcessMemory,
986     WriteProcessMemory,
987     GetThreadSelectorEntry,
988 };