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