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