Attach command no longer worked as expected, fixed it.
[wine/multimedia.git] / programs / winedbg / winedbg.c
blobcf0e1f9bd62843ab86358dd74825187f1d3187d8
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
3 /* Wine internal debugger
4 * Interface to Windows debugger API
5 * Copyright 2000 Eric Pouech
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include "debugger.h"
28 #include "winternl.h"
29 #include "thread.h"
30 #include "wincon.h"
31 #include "winreg.h"
32 #include "wingdi.h"
33 #include "winuser.h"
34 #include "excpt.h"
35 #include "wine/library.h"
37 DBG_PROCESS* DEBUG_CurrProcess = NULL;
38 DBG_THREAD* DEBUG_CurrThread = NULL;
39 DWORD DEBUG_CurrTid;
40 DWORD DEBUG_CurrPid;
41 CONTEXT DEBUG_context;
42 BOOL DEBUG_InteractiveP = FALSE;
43 static BOOL DEBUG_InException = FALSE;
44 int curr_frame = 0;
45 static char* DEBUG_LastCmdLine = NULL;
47 static DBG_PROCESS* DEBUG_ProcessList = NULL;
48 static enum {none_mode = 0, winedbg_mode, automatic_mode, gdb_mode} local_mode;
50 DBG_INTVAR DEBUG_IntVars[DBG_IV_LAST];
52 void DEBUG_OutputA(int chn, const char* buffer, int len)
54 if (DBG_IVAR(ConChannelMask) & chn)
55 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, NULL, NULL);
56 if (DBG_IVAR(StdChannelMask) & chn)
57 fwrite(buffer, len, 1, stderr);
60 void DEBUG_OutputW(int chn, const WCHAR* buffer, int len)
62 /* FIXME: this won't work is std output isn't attached to a console */
63 if (DBG_IVAR(ConChannelMask) & chn)
64 WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, NULL, NULL);
65 /* simplistic Unicode to ANSI conversion */
66 if (DBG_IVAR(StdChannelMask) & chn)
67 while (len--) fputc((char)*buffer++, stderr);
70 int DEBUG_Printf(int chn, const char* format, ...)
72 static char buf[4*1024];
73 va_list valist;
74 int len;
76 va_start(valist, format);
77 len = vsnprintf(buf, sizeof(buf), format, valist);
78 va_end(valist);
80 if (len <= -1 || len >= sizeof(buf)) {
81 len = sizeof(buf) - 1;
82 buf[len] = 0;
83 buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
85 DEBUG_OutputA(chn, buf, len);
86 return len;
89 static BOOL DEBUG_IntVarsRW(int read)
91 HKEY hkey;
92 DWORD type = REG_DWORD;
93 DWORD val;
94 DWORD count = sizeof(val);
95 int i;
96 DBG_INTVAR* div = DEBUG_IntVars;
98 if (read) {
99 /* initializes internal vars table */
100 #define INTERNAL_VAR(_var,_val,_ref,_typ) \
101 div->val = _val; div->name = #_var; div->pval = _ref; \
102 div->type = DEBUG_GetBasicType(_typ); div++;
103 #include "intvar.h"
104 #undef INTERNAL_VAR
107 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) {
108 /* since the IVars are not yet setup, DEBUG_Printf doesn't work,
109 * so don't use it */
110 fprintf(stderr, "Cannot create WineDbg key in registry\n");
111 return FALSE;
114 for (i = 0; i < DBG_IV_LAST; i++) {
115 if (read) {
116 if (!DEBUG_IntVars[i].pval) {
117 if (!RegQueryValueEx(hkey, DEBUG_IntVars[i].name, 0,
118 &type, (LPSTR)&val, &count))
119 DEBUG_IntVars[i].val = val;
120 DEBUG_IntVars[i].pval = &DEBUG_IntVars[i].val;
121 } else {
122 *DEBUG_IntVars[i].pval = 0;
124 } else {
125 /* FIXME: type should be infered from basic type -if any- of intvar */
126 if (DEBUG_IntVars[i].pval == &DEBUG_IntVars[i].val)
127 RegSetValueEx(hkey, DEBUG_IntVars[i].name, 0,
128 type, (LPCVOID)DEBUG_IntVars[i].pval, count);
131 RegCloseKey(hkey);
132 return TRUE;
135 DBG_INTVAR* DEBUG_GetIntVar(const char* name)
137 int i;
139 for (i = 0; i < DBG_IV_LAST; i++) {
140 if (!strcmp(DEBUG_IntVars[i].name, name))
141 return &DEBUG_IntVars[i];
143 return NULL;
146 DBG_PROCESS* DEBUG_GetProcess(DWORD pid)
148 DBG_PROCESS* p;
150 for (p = DEBUG_ProcessList; p; p = p->next)
151 if (p->pid == pid) break;
152 return p;
155 DBG_PROCESS* DEBUG_AddProcess(DWORD pid, HANDLE h, const char* imageName)
157 DBG_PROCESS* p;
159 if ((p = DEBUG_GetProcess(pid)))
161 if (p->handle != 0)
163 DEBUG_Printf(DBG_CHN_ERR, "Process (%lu) is already defined\n", pid);
165 else
167 p->handle = h;
168 p->imageName = imageName ? DBG_strdup(imageName) : NULL;
170 return p;
173 if (!(p = DBG_alloc(sizeof(DBG_PROCESS)))) return NULL;
174 p->handle = h;
175 p->pid = pid;
176 p->imageName = imageName ? DBG_strdup(imageName) : NULL;
177 p->threads = NULL;
178 p->num_threads = 0;
179 p->continue_on_first_exception = FALSE;
180 p->modules = NULL;
181 p->num_modules = 0;
182 p->next_index = 0;
183 p->dbg_hdr_addr = 0;
184 p->delayed_bp = NULL;
185 p->num_delayed_bp = 0;
187 p->next = DEBUG_ProcessList;
188 p->prev = NULL;
189 if (DEBUG_ProcessList) DEBUG_ProcessList->prev = p;
190 DEBUG_ProcessList = p;
191 return p;
194 void DEBUG_DelProcess(DBG_PROCESS* p)
196 int i;
198 while (p->threads) DEBUG_DelThread(p->threads);
200 for (i = 0; i < p->num_delayed_bp; i++)
201 if (p->delayed_bp[i].is_symbol)
202 DBG_free(p->delayed_bp[i].u.symbol.name);
204 DBG_free(p->delayed_bp);
205 if (p->prev) p->prev->next = p->next;
206 if (p->next) p->next->prev = p->prev;
207 if (p == DEBUG_ProcessList) DEBUG_ProcessList = p->next;
208 if (p == DEBUG_CurrProcess) DEBUG_CurrProcess = NULL;
209 DBG_free((char*)p->imageName);
210 DBG_free(p);
213 static void DEBUG_InitCurrProcess(void)
217 BOOL DEBUG_ProcessGetString(char* buffer, int size, HANDLE hp, LPSTR addr)
219 DWORD sz;
220 *(WCHAR*)buffer = 0;
221 return (addr && ReadProcessMemory(hp, addr, buffer, size, &sz));
224 BOOL DEBUG_ProcessGetStringIndirect(char* buffer, int size, HANDLE hp, LPVOID addr)
226 LPVOID ad;
227 DWORD sz;
229 if ( addr
230 && ReadProcessMemory(hp, addr, &ad, sizeof(ad), &sz)
231 && sz == sizeof(ad)
232 && ad
233 && ReadProcessMemory(hp, ad, buffer, size, &sz))
234 return TRUE;
235 *(WCHAR*)buffer = 0;
236 return FALSE;
239 DBG_THREAD* DEBUG_GetThread(DBG_PROCESS* p, DWORD tid)
241 DBG_THREAD* t;
243 if (!p) return NULL;
244 for (t = p->threads; t; t = t->next)
245 if (t->tid == tid) break;
246 return t;
249 DBG_THREAD* DEBUG_AddThread(DBG_PROCESS* p, DWORD tid,
250 HANDLE h, LPVOID start, LPVOID teb)
252 DBG_THREAD* t = DBG_alloc(sizeof(DBG_THREAD));
253 if (!t)
254 return NULL;
256 t->handle = h;
257 t->tid = tid;
258 t->start = start;
259 t->teb = teb;
260 t->process = p;
261 t->wait_for_first_exception = 0;
262 t->exec_mode = EXEC_CONT;
263 t->exec_count = 0;
265 snprintf(t->name, sizeof(t->name), "%08lx", tid);
267 p->num_threads++;
268 t->next = p->threads;
269 t->prev = NULL;
270 if (p->threads) p->threads->prev = t;
271 p->threads = t;
273 return t;
276 static void DEBUG_InitCurrThread(void)
278 if (DEBUG_CurrThread->start) {
279 if (DEBUG_CurrThread->process->num_threads == 1 ||
280 DBG_IVAR(BreakAllThreadsStartup)) {
281 DBG_VALUE value;
283 DEBUG_SetBreakpoints(FALSE);
284 value.type = NULL;
285 value.cookie = DV_TARGET;
286 value.addr.seg = 0;
287 value.addr.off = (DWORD)DEBUG_CurrThread->start;
288 DEBUG_AddBreakpointFromValue(&value);
289 DEBUG_SetBreakpoints(TRUE);
291 } else {
292 DEBUG_CurrThread->wait_for_first_exception = 1;
296 void DEBUG_DelThread(DBG_THREAD* t)
298 if (t->prev) t->prev->next = t->next;
299 if (t->next) t->next->prev = t->prev;
300 if (t == t->process->threads) t->process->threads = t->next;
301 t->process->num_threads--;
302 if (t == DEBUG_CurrThread) DEBUG_CurrThread = NULL;
303 DBG_free(t);
306 static BOOL DEBUG_HandleDebugEvent(DEBUG_EVENT* de);
308 /******************************************************************
309 * DEBUG_Attach
311 * Sets the debuggee to <pid>
312 * cofe instructs winedbg what to do when first exception is received
313 * (break=FALSE, continue=TRUE)
314 * wfe is set to TRUE if DEBUG_Attach should also proceed with all debug events
315 * until the first exception is received (aka: attach to an already running process)
317 BOOL DEBUG_Attach(DWORD pid, BOOL cofe, BOOL wfe)
319 DEBUG_EVENT de;
321 if (!(DEBUG_CurrProcess = DEBUG_AddProcess(pid, 0, NULL))) return FALSE;
323 if (!DebugActiveProcess(pid)) {
324 DEBUG_Printf(DBG_CHN_MESG, "Can't attach process %lx: error %ld\n", pid, GetLastError());
325 DEBUG_DelProcess(DEBUG_CurrProcess);
326 return FALSE;
328 DEBUG_CurrProcess->continue_on_first_exception = cofe;
330 if (wfe) /* shall we proceed all debug events until we get an exception ? */
332 DEBUG_InteractiveP = FALSE;
333 while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
335 if (DEBUG_HandleDebugEvent(&de)) break;
336 ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
338 if (DEBUG_CurrProcess) DEBUG_InteractiveP = TRUE;
340 return TRUE;
343 BOOL DEBUG_Detach(void)
345 /* remove all set breakpoints in debuggee code */
346 DEBUG_SetBreakpoints(FALSE);
347 /* needed for single stepping (ugly).
348 * should this be handled inside the server ??? */
349 #ifdef __i386__
350 DEBUG_context.EFlags &= ~STEP_FLAG;
351 #endif
352 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
353 DebugActiveProcessStop(DEBUG_CurrProcess->pid);
354 DEBUG_DelProcess(DEBUG_CurrProcess);
355 /* FIXME: should zero out the symbol table too */
356 return TRUE;
359 static BOOL DEBUG_FetchContext(void)
361 DEBUG_context.ContextFlags = CONTEXT_CONTROL
362 | CONTEXT_INTEGER
363 #ifdef CONTEXT_SEGMENTS
364 | CONTEXT_SEGMENTS
365 #endif
366 #ifdef CONTEXT_DEBUG_REGISTERS
367 | CONTEXT_DEBUG_REGISTERS
368 #endif
370 if (!GetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
372 DEBUG_Printf(DBG_CHN_WARN, "Can't get thread's context\n");
373 return FALSE;
375 return TRUE;
378 static BOOL DEBUG_ExceptionProlog(BOOL is_debug, BOOL force, DWORD code)
380 DBG_ADDR addr;
381 int newmode;
383 DEBUG_InException = TRUE;
384 DEBUG_GetCurrentAddress(&addr);
385 DEBUG_SuspendExecution();
387 if (!is_debug)
389 if (!addr.seg)
390 DEBUG_Printf(DBG_CHN_MESG, " in 32-bit code (0x%08lx)", addr.off);
391 else
392 switch(DEBUG_GetSelectorType(addr.seg))
394 case MODE_32:
395 DEBUG_Printf(DBG_CHN_MESG, " in 32-bit code (%04lx:%08lx)", addr.seg, addr.off);
396 break;
397 case MODE_16:
398 DEBUG_Printf(DBG_CHN_MESG, " in 16-bit code (%04lx:%04lx)", addr.seg, addr.off);
399 break;
400 case MODE_VM86:
401 DEBUG_Printf(DBG_CHN_MESG, " in vm86 code (%04lx:%04lx)", addr.seg, addr.off);
402 break;
403 case MODE_INVALID:
404 DEBUG_Printf(DBG_CHN_MESG, " bad CS (%lx)", addr.seg);
405 break;
407 DEBUG_Printf(DBG_CHN_MESG, ".\n");
410 DEBUG_LoadEntryPoints("Loading new modules symbols:\n");
412 if (!force && is_debug &&
413 DEBUG_ShouldContinue(&addr, code,
414 &DEBUG_CurrThread->exec_count))
415 return FALSE;
417 if ((newmode = DEBUG_GetSelectorType(addr.seg)) == MODE_INVALID) newmode = MODE_32;
418 if (newmode != DEBUG_CurrThread->dbg_mode)
420 static const char * const names[] = { "???", "16-bit", "32-bit", "vm86" };
421 DEBUG_Printf(DBG_CHN_MESG,"In %s mode.\n", names[newmode] );
422 DEBUG_CurrThread->dbg_mode = newmode;
425 DEBUG_DoDisplay();
427 if (is_debug || force) {
429 * Do a quiet backtrace so that we have an idea of what the situation
430 * is WRT the source files.
432 DEBUG_BackTrace(DEBUG_CurrTid, FALSE);
433 } else {
434 /* This is a real crash, dump some info */
435 DEBUG_InfoRegisters(&DEBUG_context);
436 DEBUG_InfoStack();
437 #ifdef __i386__
438 if (DEBUG_CurrThread->dbg_mode == MODE_16) {
439 DEBUG_InfoSegments(DEBUG_context.SegDs >> 3, 1);
440 if (DEBUG_context.SegEs != DEBUG_context.SegDs)
441 DEBUG_InfoSegments(DEBUG_context.SegEs >> 3, 1);
443 DEBUG_InfoSegments(DEBUG_context.SegFs >> 3, 1);
444 #endif
445 DEBUG_BackTrace(DEBUG_CurrTid, TRUE);
448 if (!is_debug ||
449 (DEBUG_CurrThread->exec_mode == EXEC_STEPI_OVER) ||
450 (DEBUG_CurrThread->exec_mode == EXEC_STEPI_INSTR)) {
452 struct list_id list;
454 /* Show where we crashed */
455 curr_frame = 0;
456 DEBUG_DisassembleInstruction(&addr);
458 /* resets list internal arguments so we can look at source code when needed */
459 DEBUG_FindNearestSymbol(&addr, TRUE, NULL, 0, &list);
460 if (list.sourcefile) DEBUG_List(&list, NULL, 0);
462 return TRUE;
465 static void DEBUG_ExceptionEpilog(void)
467 DEBUG_RestartExecution(DEBUG_CurrThread->exec_count);
469 * This will have gotten absorbed into the breakpoint info
470 * if it was used. Otherwise it would have been ignored.
471 * In any case, we don't mess with it any more.
473 if (DEBUG_CurrThread->exec_mode == EXEC_CONT)
474 DEBUG_CurrThread->exec_count = 0;
475 DEBUG_InException = FALSE;
478 static BOOL DEBUG_HandleException(EXCEPTION_RECORD *rec, BOOL first_chance, BOOL force)
480 BOOL is_debug = FALSE;
481 THREADNAME_INFO *pThreadName;
482 DBG_THREAD *pThread;
484 assert(DEBUG_CurrThread);
486 switch (rec->ExceptionCode)
488 case EXCEPTION_BREAKPOINT:
489 case EXCEPTION_SINGLE_STEP:
490 is_debug = TRUE;
491 break;
492 case EXCEPTION_NAME_THREAD:
493 pThreadName = (THREADNAME_INFO*)(rec->ExceptionInformation);
494 if (pThreadName->dwThreadID == -1)
495 pThread = DEBUG_CurrThread;
496 else
497 pThread = DEBUG_GetThread(DEBUG_CurrProcess, pThreadName->dwThreadID);
499 if (ReadProcessMemory(DEBUG_CurrThread->process->handle, pThreadName->szName,
500 pThread->name, 9, NULL))
501 DEBUG_Printf (DBG_CHN_MESG,
502 "Thread ID=0x%lx renamed using MS VC6 extension (name==\"%s\")\n",
503 pThread->tid, pThread->name);
504 return FALSE;
507 if (first_chance && !is_debug && !force && !DBG_IVAR(BreakOnFirstChance))
509 /* pass exception to program except for debug exceptions */
510 return FALSE;
513 if (!is_debug)
515 /* print some infos */
516 DEBUG_Printf(DBG_CHN_MESG, "%s: ",
517 first_chance ? "First chance exception" : "Unhandled exception");
518 switch (rec->ExceptionCode)
520 case EXCEPTION_INT_DIVIDE_BY_ZERO:
521 DEBUG_Printf(DBG_CHN_MESG, "divide by zero");
522 break;
523 case EXCEPTION_INT_OVERFLOW:
524 DEBUG_Printf(DBG_CHN_MESG, "overflow");
525 break;
526 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
527 DEBUG_Printf(DBG_CHN_MESG, "array bounds ");
528 break;
529 case EXCEPTION_ILLEGAL_INSTRUCTION:
530 DEBUG_Printf(DBG_CHN_MESG, "illegal instruction");
531 break;
532 case EXCEPTION_STACK_OVERFLOW:
533 DEBUG_Printf(DBG_CHN_MESG, "stack overflow");
534 break;
535 case EXCEPTION_PRIV_INSTRUCTION:
536 DEBUG_Printf(DBG_CHN_MESG, "privileged instruction");
537 break;
538 case EXCEPTION_ACCESS_VIOLATION:
539 if (rec->NumberParameters == 2)
540 DEBUG_Printf(DBG_CHN_MESG, "page fault on %s access to 0x%08lx",
541 rec->ExceptionInformation[0] ? "write" : "read",
542 rec->ExceptionInformation[1]);
543 else
544 DEBUG_Printf(DBG_CHN_MESG, "page fault");
545 break;
546 case EXCEPTION_DATATYPE_MISALIGNMENT:
547 DEBUG_Printf(DBG_CHN_MESG, "Alignment");
548 break;
549 case DBG_CONTROL_C:
550 DEBUG_Printf(DBG_CHN_MESG, "^C");
551 break;
552 case CONTROL_C_EXIT:
553 DEBUG_Printf(DBG_CHN_MESG, "^C");
554 break;
555 case EXCEPTION_CRITICAL_SECTION_WAIT:
557 DBG_ADDR addr;
559 addr.seg = 0;
560 addr.off = rec->ExceptionInformation[0];
562 DEBUG_Printf(DBG_CHN_MESG, "wait failed on critical section ");
563 DEBUG_PrintAddress(&addr, DEBUG_CurrThread->dbg_mode, FALSE);
565 if (!DBG_IVAR(BreakOnCritSectTimeOut))
567 DEBUG_Printf(DBG_CHN_MESG, "\n");
568 return FALSE;
570 break;
571 case EXCEPTION_WINE_STUB:
573 char dll[32], name[64];
574 DEBUG_ProcessGetString( dll, sizeof(dll), DEBUG_CurrThread->process->handle,
575 (char *)rec->ExceptionInformation[0] );
576 DEBUG_ProcessGetString( name, sizeof(name), DEBUG_CurrThread->process->handle,
577 (char *)rec->ExceptionInformation[1] );
578 DEBUG_Printf(DBG_CHN_MESG, "unimplemented function %s.%s called", dll, name );
580 break;
581 case EXCEPTION_WINE_ASSERTION:
582 DEBUG_Printf(DBG_CHN_MESG, "assertion failed");
583 break;
584 case EXCEPTION_VM86_INTx:
585 DEBUG_Printf(DBG_CHN_MESG, "interrupt %02lx in vm86 mode",
586 rec->ExceptionInformation[0]);
587 break;
588 case EXCEPTION_VM86_STI:
589 DEBUG_Printf(DBG_CHN_MESG, "sti in vm86 mode");
590 break;
591 case EXCEPTION_VM86_PICRETURN:
592 DEBUG_Printf(DBG_CHN_MESG, "PIC return in vm86 mode");
593 break;
594 default:
595 DEBUG_Printf(DBG_CHN_MESG, "%08lx", rec->ExceptionCode);
596 break;
600 if (local_mode == automatic_mode)
602 DEBUG_ExceptionProlog(is_debug, FALSE, rec->ExceptionCode);
603 DEBUG_ExceptionEpilog();
604 return TRUE; /* terminate execution */
607 if (DEBUG_ExceptionProlog(is_debug, force, rec->ExceptionCode))
609 DEBUG_InteractiveP = TRUE;
610 return TRUE;
612 DEBUG_ExceptionEpilog();
614 return FALSE;
617 static BOOL DEBUG_HandleDebugEvent(DEBUG_EVENT* de)
619 char buffer[256];
620 BOOL ret = FALSE;
622 DEBUG_CurrPid = de->dwProcessId;
623 DEBUG_CurrTid = de->dwThreadId;
625 if ((DEBUG_CurrProcess = DEBUG_GetProcess(de->dwProcessId)) != NULL)
626 DEBUG_CurrThread = DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId);
627 else
628 DEBUG_CurrThread = NULL;
630 switch (de->dwDebugEventCode)
632 case EXCEPTION_DEBUG_EVENT:
633 if (!DEBUG_CurrThread)
635 DEBUG_Printf(DBG_CHN_ERR, "%08lx:%08lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
636 de->dwProcessId, de->dwThreadId);
637 break;
640 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exception code=%08lx\n",
641 de->dwProcessId, de->dwThreadId,
642 de->u.Exception.ExceptionRecord.ExceptionCode);
644 if (DEBUG_CurrProcess->continue_on_first_exception)
646 DEBUG_CurrProcess->continue_on_first_exception = FALSE;
647 if (!DBG_IVAR(BreakOnAttach)) break;
650 if (DEBUG_FetchContext())
652 ret = DEBUG_HandleException(&de->u.Exception.ExceptionRecord,
653 de->u.Exception.dwFirstChance,
654 DEBUG_CurrThread->wait_for_first_exception);
655 if (!ret && DEBUG_CurrThread)
657 DEBUG_CurrThread->wait_for_first_exception = 0;
658 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
661 break;
663 case CREATE_THREAD_DEBUG_EVENT:
664 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create thread D @%08lx\n", de->dwProcessId, de->dwThreadId,
665 (unsigned long)(LPVOID)de->u.CreateThread.lpStartAddress);
667 if (DEBUG_CurrProcess == NULL)
669 DEBUG_Printf(DBG_CHN_ERR, "Unknown process\n");
670 break;
672 if (DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId) != NULL)
674 DEBUG_Printf(DBG_CHN_TRACE, "Thread already listed, skipping\n");
675 break;
678 DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
679 de->dwThreadId,
680 de->u.CreateThread.hThread,
681 de->u.CreateThread.lpStartAddress,
682 de->u.CreateThread.lpThreadLocalBase);
683 if (!DEBUG_CurrThread)
685 DEBUG_Printf(DBG_CHN_ERR, "Couldn't create thread\n");
686 break;
688 DEBUG_InitCurrThread();
689 break;
691 case CREATE_PROCESS_DEBUG_EVENT:
692 DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
693 de->u.CreateProcessInfo.hProcess,
694 de->u.CreateProcessInfo.lpImageName);
696 /* FIXME unicode ? de->u.CreateProcessInfo.fUnicode */
697 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create process '%s'/%p @%08lx (%ld<%ld>)\n",
698 de->dwProcessId, de->dwThreadId,
699 buffer, de->u.CreateProcessInfo.lpImageName,
700 (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress,
701 de->u.CreateProcessInfo.dwDebugInfoFileOffset,
702 de->u.CreateProcessInfo.nDebugInfoSize);
704 DEBUG_CurrProcess = DEBUG_AddProcess(de->dwProcessId,
705 de->u.CreateProcessInfo.hProcess,
706 buffer[0] ? buffer : "<Debugged Process>");
707 if (DEBUG_CurrProcess == NULL)
709 DEBUG_Printf(DBG_CHN_ERR, "Couldn't create process\n");
710 break;
713 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: create thread I @%08lx\n",
714 de->dwProcessId, de->dwThreadId,
715 (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress);
717 DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
718 de->dwThreadId,
719 de->u.CreateProcessInfo.hThread,
720 de->u.CreateProcessInfo.lpStartAddress,
721 de->u.CreateProcessInfo.lpThreadLocalBase);
722 if (!DEBUG_CurrThread)
724 DEBUG_Printf(DBG_CHN_ERR, "Couldn't create thread\n");
725 break;
728 DEBUG_InitCurrProcess();
729 DEBUG_InitCurrThread();
731 /* module is either PE, NE or ELF module (for WineLib), but all
732 * are loaded with wine, so load its symbols, then the main module
736 char* ptr = getenv("WINELOADER");
738 if (!ptr || DEBUG_ReadExecutableDbgInfo( ptr ) == DIL_ERROR)
739 DEBUG_ReadExecutableDbgInfo( "wine" );
740 } while (0);
742 DEBUG_LoadModule32(DEBUG_CurrProcess->imageName, de->u.CreateProcessInfo.hFile,
743 (DWORD)de->u.CreateProcessInfo.lpBaseOfImage);
745 break;
747 case EXIT_THREAD_DEBUG_EVENT:
748 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exit thread (%ld)\n",
749 de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
751 if (DEBUG_CurrThread == NULL)
753 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
754 break;
756 /* FIXME: remove break point set on thread startup */
757 DEBUG_DelThread(DEBUG_CurrThread);
758 break;
760 case EXIT_PROCESS_DEBUG_EVENT:
761 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: exit process (%ld)\n",
762 de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
764 if (DEBUG_CurrProcess == NULL)
766 DEBUG_Printf(DBG_CHN_ERR, "Unknown process\n");
767 break;
769 /* just in case */
770 DEBUG_SetBreakpoints(FALSE);
771 /* kill last thread */
772 DEBUG_DelThread(DEBUG_CurrProcess->threads);
773 DEBUG_DelProcess(DEBUG_CurrProcess);
775 DEBUG_Printf(DBG_CHN_MESG, "Process of pid=%08lx has terminated\n", DEBUG_CurrPid);
776 break;
778 case LOAD_DLL_DEBUG_EVENT:
779 if (DEBUG_CurrThread == NULL)
781 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
782 break;
784 DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
785 DEBUG_CurrThread->process->handle,
786 de->u.LoadDll.lpImageName);
788 /* FIXME unicode: de->u.LoadDll.fUnicode */
789 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: loads DLL %s @%08lx (%ld<%ld>)\n",
790 de->dwProcessId, de->dwThreadId,
791 buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll,
792 de->u.LoadDll.dwDebugInfoFileOffset,
793 de->u.LoadDll.nDebugInfoSize);
794 _strupr(buffer);
795 DEBUG_LoadModule32(buffer, de->u.LoadDll.hFile, (DWORD)de->u.LoadDll.lpBaseOfDll);
796 DEBUG_CheckDelayedBP();
797 if (DBG_IVAR(BreakOnDllLoad))
799 DEBUG_Printf(DBG_CHN_MESG, "Stopping on DLL %s loading at %08lx\n",
800 buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll);
801 ret = DEBUG_FetchContext();
803 break;
805 case UNLOAD_DLL_DEBUG_EVENT:
806 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: unload DLL @%08lx\n", de->dwProcessId, de->dwThreadId,
807 (unsigned long)de->u.UnloadDll.lpBaseOfDll);
808 break;
810 case OUTPUT_DEBUG_STRING_EVENT:
811 if (DEBUG_CurrThread == NULL)
813 DEBUG_Printf(DBG_CHN_ERR, "Unknown thread\n");
814 break;
817 DEBUG_ProcessGetString(buffer, sizeof(buffer),
818 DEBUG_CurrThread->process->handle,
819 de->u.DebugString.lpDebugStringData);
821 /* FIXME unicode de->u.DebugString.fUnicode ? */
822 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: output debug string (%s)\n",
823 de->dwProcessId, de->dwThreadId, buffer);
824 break;
826 case RIP_EVENT:
827 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: rip error=%ld type=%ld\n",
828 de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
829 de->u.RipInfo.dwType);
830 break;
832 default:
833 DEBUG_Printf(DBG_CHN_TRACE, "%08lx:%08lx: unknown event (%ld)\n",
834 de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
837 return ret;
840 static void DEBUG_ResumeDebuggee(DWORD cont)
842 if (DEBUG_InException)
844 DEBUG_ExceptionEpilog();
845 #if 1
846 DEBUG_Printf(DBG_CHN_TRACE,
847 "Exiting debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
848 #ifdef __i386__
849 DEBUG_context.Eip, DEBUG_context.EFlags,
850 #else
851 0L, 0L,
852 #endif
853 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
854 #endif
855 if (DEBUG_CurrThread)
857 if (!SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
858 DEBUG_Printf(DBG_CHN_MESG, "Cannot set ctx on %lu\n", DEBUG_CurrTid);
859 DEBUG_CurrThread->wait_for_first_exception = 0;
862 DEBUG_InteractiveP = FALSE;
863 if (!ContinueDebugEvent(DEBUG_CurrPid, DEBUG_CurrTid, cont))
864 DEBUG_Printf(DBG_CHN_MESG, "Cannot continue on %lu (%lu)\n",
865 DEBUG_CurrTid, cont);
868 void DEBUG_WaitNextException(DWORD cont, int count, int mode)
870 DEBUG_EVENT de;
872 if (cont == DBG_CONTINUE)
874 DEBUG_CurrThread->exec_count = count;
875 DEBUG_CurrThread->exec_mode = mode;
877 DEBUG_ResumeDebuggee(cont);
879 while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
881 if (DEBUG_HandleDebugEvent(&de)) break;
882 ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
884 if (!DEBUG_CurrProcess) return;
885 DEBUG_InteractiveP = TRUE;
886 #if 1
887 DEBUG_Printf(DBG_CHN_TRACE,
888 "Entering debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
889 #ifdef __i386__
890 DEBUG_context.Eip, DEBUG_context.EFlags,
891 #else
892 0L, 0L,
893 #endif
894 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
895 #endif
898 static DWORD DEBUG_MainLoop(void)
900 DEBUG_EVENT de;
902 DEBUG_Printf(DBG_CHN_MESG, "WineDbg starting on pid %lx\n", DEBUG_CurrPid);
904 /* wait for first exception */
905 while (WaitForDebugEvent(&de, INFINITE))
907 if (DEBUG_HandleDebugEvent(&de)) break;
908 ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
910 if (local_mode == automatic_mode)
912 /* print some extra information */
913 DEBUG_Printf(DBG_CHN_MESG, "Modules:\n");
914 DEBUG_WalkModules();
915 DEBUG_Printf(DBG_CHN_MESG, "Threads:\n");
916 DEBUG_WalkThreads();
918 else
920 DEBUG_InteractiveP = TRUE;
921 DEBUG_Parser(NULL);
923 DEBUG_Printf(DBG_CHN_MESG, "WineDbg terminated on pid %lx\n", DEBUG_CurrPid);
925 return 0;
928 static BOOL DEBUG_Start(LPSTR cmdLine)
930 PROCESS_INFORMATION info;
931 STARTUPINFOA startup;
933 memset(&startup, 0, sizeof(startup));
934 startup.cb = sizeof(startup);
935 startup.dwFlags = STARTF_USESHOWWINDOW;
936 startup.wShowWindow = SW_SHOWNORMAL;
938 /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUI:s need it
939 * while GUI:s don't
941 if (!CreateProcess(NULL, cmdLine, NULL, NULL,
942 FALSE, DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS|CREATE_NEW_CONSOLE,
943 NULL, NULL, &startup, &info))
945 DEBUG_Printf(DBG_CHN_MESG, "Couldn't start process '%s'\n", cmdLine);
946 return FALSE;
948 DEBUG_CurrPid = info.dwProcessId;
949 if (!(DEBUG_CurrProcess = DEBUG_AddProcess(DEBUG_CurrPid, 0, NULL))) return FALSE;
951 return TRUE;
954 void DEBUG_Run(const char* args)
956 DBG_MODULE* wmod = DEBUG_GetProcessMainModule(DEBUG_CurrProcess);
957 const char* pgm = (wmod) ? wmod->module_name : "none";
959 if (args) {
960 DEBUG_Printf(DBG_CHN_MESG, "Run (%s) with '%s'\n", pgm, args);
961 } else {
962 if (!DEBUG_LastCmdLine) {
963 DEBUG_Printf(DBG_CHN_MESG, "Cannot find previously used command line.\n");
964 return;
966 DEBUG_Start(DEBUG_LastCmdLine);
970 static BOOL WINAPI DEBUG_CtrlCHandler(DWORD dwCtrlType)
972 if (dwCtrlType == CTRL_C_EVENT)
974 DEBUG_Printf(DBG_CHN_MESG, "Ctrl-C: stopping debuggee\n");
975 /* FIXME: since we likely have a single process, signal the first process
976 * in list
978 return DEBUG_ProcessList && DebugBreakProcess(DEBUG_ProcessList->handle);
980 return FALSE;
983 static void DEBUG_InitConsole(void)
985 /* keep it as a cuiexe for now, so that Wine won't touch the Unix stdin,
986 * stdout and stderr streams
988 if (DBG_IVAR(UseXTerm))
990 FreeConsole();
991 AllocConsole();
994 /* set our control-C handler */
995 SetConsoleCtrlHandler(DEBUG_CtrlCHandler, TRUE);
997 /* set our own title */
998 SetConsoleTitle("Wine Debugger");
1001 static int DEBUG_Usage(void)
1003 DEBUG_Printf(DBG_CHN_MESG, "Usage: winedbg [--debugmsg dbgoptions] [--auto] [--gdb] cmdline\n" );
1004 return 1;
1007 int main(int argc, char** argv)
1009 DWORD retv = 0;
1010 unsigned gdb_flags = 0;
1012 /* Initialize the type handling stuff. */
1013 DEBUG_InitTypes();
1014 DEBUG_InitCVDataTypes();
1016 /* Initialize internal vars (types must have been initialized before) */
1017 if (!DEBUG_IntVarsRW(TRUE)) return -1;
1019 /* parse options */
1020 while (argc > 1 && argv[1][0] == '-')
1022 if (!strcmp( argv[1], "--auto" ))
1024 if (local_mode != none_mode) return DEBUG_Usage();
1025 local_mode = automatic_mode;
1026 /* force some internal variables */
1027 DBG_IVAR(UseXTerm) = 0;
1028 DBG_IVAR(BreakOnDllLoad) = 0;
1029 DBG_IVAR(ConChannelMask) = 0;
1030 DBG_IVAR(StdChannelMask) = DBG_CHN_MESG;
1031 argc--; argv++;
1032 continue;
1034 if (!strcmp( argv[1], "--gdb" ))
1036 if (local_mode != none_mode) return DEBUG_Usage();
1037 local_mode = gdb_mode;
1038 argc--; argv++;
1039 continue;
1041 if (strcmp( argv[1], "--no-start") == 0 && local_mode == gdb_mode)
1043 gdb_flags |= 1;
1044 argc--; argv++; /* as we don't use argv[0] */
1045 continue;
1047 if (strcmp(argv[1], "--with-xterm") == 0 && local_mode == gdb_mode)
1049 gdb_flags |= 2;
1050 argc--; argv++; /* as we don't use argv[0] */
1051 continue;
1053 if (!strcmp( argv[1], "--debugmsg" ) && argv[2])
1055 wine_dbg_parse_options( argv[2] );
1056 argc -= 2;
1057 argv += 2;
1058 continue;
1060 return DEBUG_Usage();
1063 if (local_mode == none_mode) local_mode = winedbg_mode;
1065 /* try the form <myself> pid */
1066 if (DEBUG_CurrPid == 0 && argc == 2)
1068 char* ptr;
1070 DEBUG_CurrPid = strtol(argv[1], &ptr, 10);
1071 if (DEBUG_CurrPid == 0 || ptr == NULL ||
1072 !DEBUG_Attach(DEBUG_CurrPid, local_mode != gdb_mode, FALSE))
1073 DEBUG_CurrPid = 0;
1076 /* try the form <myself> pid evt (Win32 JIT debugger) */
1077 if (DEBUG_CurrPid == 0 && argc == 3)
1079 HANDLE hEvent;
1080 DWORD pid;
1081 char* ptr;
1083 if ((pid = strtol(argv[1], &ptr, 10)) != 0 && ptr != NULL &&
1084 (hEvent = (HANDLE)strtol(argv[2], &ptr, 10)) != 0 && ptr != NULL)
1086 if (!DEBUG_Attach(pid, TRUE, FALSE))
1088 /* don't care about result */
1089 SetEvent(hEvent);
1090 goto leave;
1092 if (!SetEvent(hEvent))
1094 DEBUG_Printf(DBG_CHN_ERR, "Invalid event handle: %p\n", hEvent);
1095 goto leave;
1097 CloseHandle(hEvent);
1098 DEBUG_CurrPid = pid;
1102 if (DEBUG_CurrPid == 0 && argc > 1)
1104 int i, len;
1105 LPSTR cmdLine;
1107 if (!(cmdLine = DBG_alloc(len = 1))) goto oom_leave;
1108 cmdLine[0] = '\0';
1110 for (i = 1; i < argc; i++)
1112 len += strlen(argv[i]) + 1;
1113 if (!(cmdLine = DBG_realloc(cmdLine, len))) goto oom_leave;
1114 strcat(cmdLine, argv[i]);
1115 cmdLine[len - 2] = ' ';
1116 cmdLine[len - 1] = '\0';
1119 if (!DEBUG_Start(cmdLine))
1121 DEBUG_Printf(DBG_CHN_MESG, "Couldn't start process '%s'\n", cmdLine);
1122 goto leave;
1124 DBG_free(DEBUG_LastCmdLine);
1125 DEBUG_LastCmdLine = cmdLine;
1127 /* don't save local vars in gdb mode */
1128 if (local_mode == gdb_mode && DEBUG_CurrPid)
1129 return DEBUG_GdbRemote(gdb_flags);
1131 DEBUG_InitConsole();
1133 retv = DEBUG_MainLoop();
1134 /* don't save modified variables in auto mode */
1135 if (local_mode != automatic_mode) DEBUG_IntVarsRW(FALSE);
1137 leave:
1138 return retv;
1140 oom_leave:
1141 DEBUG_Printf(DBG_CHN_MESG, "Out of memory\n");
1142 goto leave;