- now detecting Dwarf debug information in ELF modules (but don't load
[wine.git] / programs / winedbg / winedbg.c
blob4724cac400dccba1d4e8cda105f526b366036b8d
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 "config.h"
23 #include "wine/port.h"
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include "debugger.h"
31 #include "wincon.h"
32 #include "winreg.h"
33 #include "wingdi.h"
34 #include "winuser.h"
35 #include "winternl.h"
36 #include "excpt.h"
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "winnls.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
45 DBG_PROCESS* DEBUG_CurrProcess = NULL;
46 DBG_THREAD* DEBUG_CurrThread = NULL;
47 DWORD DEBUG_CurrTid;
48 DWORD DEBUG_CurrPid;
49 CONTEXT DEBUG_context;
50 BOOL DEBUG_InteractiveP = FALSE;
51 static BOOL DEBUG_InException = FALSE;
52 int curr_frame = 0;
53 static char* DEBUG_LastCmdLine = NULL;
55 static DBG_PROCESS* DEBUG_ProcessList = NULL;
56 static enum {none_mode = 0, winedbg_mode, automatic_mode, gdb_mode} local_mode;
58 DBG_INTVAR DEBUG_IntVars[DBG_IV_LAST];
60 void DEBUG_OutputA(const char* buffer, int len)
62 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, NULL, NULL);
65 void DEBUG_OutputW(const WCHAR* buffer, int len)
67 char* ansi = NULL;
68 int newlen;
70 /* do a serious Unicode to ANSI conversion
71 FIXME: should CP_ACP be GetConsoleCP()? */
72 newlen = WideCharToMultiByte(CP_ACP, 0, buffer, len, NULL, 0, NULL, NULL);
73 if(newlen)
75 ansi = (char*)DBG_alloc(newlen);
76 if(ansi)
78 WideCharToMultiByte(CP_ACP, 0, buffer, len, ansi, newlen, NULL, NULL);
82 /* fall back to a simple Unicode to ANSI conversion in case WC2MB failed */
83 if(!ansi)
85 ansi = DBG_alloc(len);
86 if(ansi)
88 int i;
89 for(i = 0; i < len; i++)
91 ansi[i] = (char)buffer[i];
94 newlen = len;
96 /* else we are having REALLY bad luck today */
99 if(ansi)
101 DEBUG_OutputA(ansi, newlen);
102 DBG_free(ansi);
106 int DEBUG_Printf(const char* format, ...)
108 static char buf[4*1024];
109 va_list valist;
110 int len;
112 va_start(valist, format);
113 len = vsnprintf(buf, sizeof(buf), format, valist);
114 va_end(valist);
116 if (len <= -1 || len >= sizeof(buf)) {
117 len = sizeof(buf) - 1;
118 buf[len] = 0;
119 buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
121 DEBUG_OutputA(buf, len);
122 return len;
125 static BOOL DEBUG_IntVarsRW(int read)
127 HKEY hkey;
128 DWORD type = REG_DWORD;
129 DWORD val;
130 DWORD count = sizeof(val);
131 int i;
132 DBG_INTVAR* div = DEBUG_IntVars;
134 if (read) {
135 /* initializes internal vars table */
136 #define INTERNAL_VAR(_var,_val,_ref,_typ) \
137 div->val = _val; div->name = #_var; div->pval = _ref; \
138 div->type = DEBUG_GetBasicType(_typ); div++;
139 #include "intvar.h"
140 #undef INTERNAL_VAR
143 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) {
144 WINE_ERR("Cannot create WineDbg key in registry\n");
145 return FALSE;
148 for (i = 0; i < DBG_IV_LAST; i++) {
149 if (read) {
150 if (!DEBUG_IntVars[i].pval) {
151 if (!RegQueryValueEx(hkey, DEBUG_IntVars[i].name, 0,
152 &type, (LPSTR)&val, &count))
153 DEBUG_IntVars[i].val = val;
154 DEBUG_IntVars[i].pval = &DEBUG_IntVars[i].val;
155 } else {
156 *DEBUG_IntVars[i].pval = 0;
158 } else {
159 /* FIXME: type should be infered from basic type -if any- of intvar */
160 if (DEBUG_IntVars[i].pval == &DEBUG_IntVars[i].val)
161 RegSetValueEx(hkey, DEBUG_IntVars[i].name, 0,
162 type, (LPCVOID)DEBUG_IntVars[i].pval, count);
165 RegCloseKey(hkey);
166 return TRUE;
169 DBG_INTVAR* DEBUG_GetIntVar(const char* name)
171 int i;
173 for (i = 0; i < DBG_IV_LAST; i++) {
174 if (!strcmp(DEBUG_IntVars[i].name, name))
175 return &DEBUG_IntVars[i];
177 return NULL;
180 DBG_PROCESS* DEBUG_GetProcess(DWORD pid)
182 DBG_PROCESS* p;
184 for (p = DEBUG_ProcessList; p; p = p->next)
185 if (p->pid == pid) break;
186 return p;
189 DBG_PROCESS* DEBUG_AddProcess(DWORD pid, HANDLE h, const char* imageName)
191 DBG_PROCESS* p;
193 if ((p = DEBUG_GetProcess(pid)))
195 if (p->handle != 0)
197 WINE_ERR("Process (%lu) is already defined\n", pid);
199 else
201 p->handle = h;
202 p->imageName = imageName ? DBG_strdup(imageName) : NULL;
204 return p;
207 if (!(p = DBG_alloc(sizeof(DBG_PROCESS)))) return NULL;
208 p->handle = h;
209 p->pid = pid;
210 p->imageName = imageName ? DBG_strdup(imageName) : NULL;
211 p->threads = NULL;
212 p->num_threads = 0;
213 p->continue_on_first_exception = FALSE;
214 p->modules = NULL;
215 p->num_modules = 0;
216 p->next_index = 0;
217 p->dbg_hdr_addr = 0;
218 p->delayed_bp = NULL;
219 p->num_delayed_bp = 0;
221 p->next = DEBUG_ProcessList;
222 p->prev = NULL;
223 if (DEBUG_ProcessList) DEBUG_ProcessList->prev = p;
224 DEBUG_ProcessList = p;
225 return p;
228 void DEBUG_DelProcess(DBG_PROCESS* p)
230 int i;
232 while (p->threads) DEBUG_DelThread(p->threads);
234 for (i = 0; i < p->num_delayed_bp; i++)
235 if (p->delayed_bp[i].is_symbol)
236 DBG_free(p->delayed_bp[i].u.symbol.name);
238 DBG_free(p->delayed_bp);
239 if (p->prev) p->prev->next = p->next;
240 if (p->next) p->next->prev = p->prev;
241 if (p == DEBUG_ProcessList) DEBUG_ProcessList = p->next;
242 if (p == DEBUG_CurrProcess) DEBUG_CurrProcess = NULL;
243 DBG_free((char*)p->imageName);
244 DBG_free(p);
247 static void DEBUG_InitCurrProcess(void)
251 BOOL DEBUG_ProcessGetString(char* buffer, int size, HANDLE hp, LPSTR addr)
253 DWORD sz;
254 *(WCHAR*)buffer = 0;
255 return (addr && ReadProcessMemory(hp, addr, buffer, size, &sz));
258 BOOL DEBUG_ProcessGetStringIndirect(char* buffer, int size, HANDLE hp, LPVOID addr, BOOL unicode)
260 LPVOID ad;
261 DWORD sz;
263 if (addr && ReadProcessMemory(hp, addr, &ad, sizeof(ad), &sz) && sz == sizeof(ad) && ad)
265 if (!unicode) ReadProcessMemory(hp, ad, buffer, size, &sz);
266 else
268 WCHAR *buffW = DBG_alloc( size * sizeof(WCHAR) );
269 ReadProcessMemory(hp, ad, buffW, size*sizeof(WCHAR), &sz);
270 WideCharToMultiByte( CP_ACP, 0, buffW, sz/sizeof(WCHAR), buffer, size, NULL, NULL );
271 DBG_free(buffW);
273 return TRUE;
275 *(WCHAR*)buffer = 0;
276 return FALSE;
279 DBG_THREAD* DEBUG_GetThread(DBG_PROCESS* p, DWORD tid)
281 DBG_THREAD* t;
283 if (!p) return NULL;
284 for (t = p->threads; t; t = t->next)
285 if (t->tid == tid) break;
286 return t;
289 DBG_THREAD* DEBUG_AddThread(DBG_PROCESS* p, DWORD tid,
290 HANDLE h, LPVOID start, LPVOID teb)
292 DBG_THREAD* t = DBG_alloc(sizeof(DBG_THREAD));
293 if (!t)
294 return NULL;
296 t->handle = h;
297 t->tid = tid;
298 t->start = start;
299 t->teb = teb;
300 t->process = p;
301 t->wait_for_first_exception = 0;
302 t->exec_mode = EXEC_CONT;
303 t->exec_count = 0;
305 snprintf(t->name, sizeof(t->name), "%08lx", tid);
307 p->num_threads++;
308 t->next = p->threads;
309 t->prev = NULL;
310 if (p->threads) p->threads->prev = t;
311 p->threads = t;
313 return t;
316 static void DEBUG_InitCurrThread(void)
318 if (DEBUG_CurrThread->start) {
319 if (DEBUG_CurrThread->process->num_threads == 1 ||
320 DBG_IVAR(BreakAllThreadsStartup)) {
321 DBG_VALUE value;
323 DEBUG_SetBreakpoints(FALSE);
324 value.type = NULL;
325 value.cookie = DV_TARGET;
326 value.addr.seg = 0;
327 value.addr.off = (DWORD)DEBUG_CurrThread->start;
328 DEBUG_AddBreakpointFromValue(&value);
329 DEBUG_SetBreakpoints(TRUE);
331 } else {
332 DEBUG_CurrThread->wait_for_first_exception = 1;
336 void DEBUG_DelThread(DBG_THREAD* t)
338 if (t->prev) t->prev->next = t->next;
339 if (t->next) t->next->prev = t->prev;
340 if (t == t->process->threads) t->process->threads = t->next;
341 t->process->num_threads--;
342 if (t == DEBUG_CurrThread) DEBUG_CurrThread = NULL;
343 DBG_free(t);
346 static BOOL DEBUG_HandleDebugEvent(DEBUG_EVENT* de);
348 /******************************************************************
349 * DEBUG_Attach
351 * Sets the debuggee to <pid>
352 * cofe instructs winedbg what to do when first exception is received
353 * (break=FALSE, continue=TRUE)
354 * wfe is set to TRUE if DEBUG_Attach should also proceed with all debug events
355 * until the first exception is received (aka: attach to an already running process)
357 BOOL DEBUG_Attach(DWORD pid, BOOL cofe, BOOL wfe)
359 DEBUG_EVENT de;
361 if (!(DEBUG_CurrProcess = DEBUG_AddProcess(pid, 0, NULL))) return FALSE;
363 if (!DebugActiveProcess(pid)) {
364 DEBUG_Printf("Can't attach process %lx: error %ld\n", pid, GetLastError());
365 DEBUG_DelProcess(DEBUG_CurrProcess);
366 return FALSE;
368 DEBUG_CurrProcess->continue_on_first_exception = cofe;
370 if (wfe) /* shall we proceed all debug events until we get an exception ? */
372 DEBUG_InteractiveP = FALSE;
373 while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
375 if (DEBUG_HandleDebugEvent(&de)) break;
377 if (DEBUG_CurrProcess) DEBUG_InteractiveP = TRUE;
379 return TRUE;
382 BOOL DEBUG_Detach(void)
384 /* remove all set breakpoints in debuggee code */
385 DEBUG_SetBreakpoints(FALSE);
386 /* needed for single stepping (ugly).
387 * should this be handled inside the server ??? */
388 #ifdef __i386__
389 DEBUG_context.EFlags &= ~STEP_FLAG;
390 #endif
391 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
392 DebugActiveProcessStop(DEBUG_CurrProcess->pid);
393 DEBUG_DelProcess(DEBUG_CurrProcess);
394 /* FIXME: should zero out the symbol table too */
395 return TRUE;
398 static BOOL DEBUG_FetchContext(void)
400 DEBUG_context.ContextFlags = CONTEXT_CONTROL
401 | CONTEXT_INTEGER
402 #ifdef CONTEXT_SEGMENTS
403 | CONTEXT_SEGMENTS
404 #endif
405 #ifdef CONTEXT_DEBUG_REGISTERS
406 | CONTEXT_DEBUG_REGISTERS
407 #endif
409 if (!GetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
411 WINE_WARN("Can't get thread's context\n");
412 return FALSE;
414 return TRUE;
417 static BOOL DEBUG_ExceptionProlog(BOOL is_debug, BOOL force, DWORD code)
419 DBG_ADDR addr;
420 int newmode;
422 DEBUG_InException = TRUE;
423 DEBUG_GetCurrentAddress(&addr);
424 DEBUG_SuspendExecution();
426 if (!is_debug)
428 if (!addr.seg)
429 DEBUG_Printf(" in 32-bit code (0x%08lx)", addr.off);
430 else
431 switch (DEBUG_GetSelectorType(addr.seg))
433 case MODE_32:
434 DEBUG_Printf(" in 32-bit code (%04lx:%08lx)", addr.seg, addr.off);
435 break;
436 case MODE_16:
437 DEBUG_Printf(" in 16-bit code (%04lx:%04lx)", addr.seg, addr.off);
438 break;
439 case MODE_VM86:
440 DEBUG_Printf(" in vm86 code (%04lx:%04lx)", addr.seg, addr.off);
441 break;
442 case MODE_INVALID:
443 DEBUG_Printf(" bad CS (%lx)", addr.seg);
444 break;
446 DEBUG_Printf(".\n");
449 DEBUG_LoadEntryPoints("Loading new modules symbols:\n");
451 * Do a quiet backtrace so that we have an idea of what the situation
452 * is WRT the source files.
454 DEBUG_BackTrace(DEBUG_CurrTid, FALSE);
456 if (!force && is_debug &&
457 DEBUG_ShouldContinue(&addr, code,
458 &DEBUG_CurrThread->exec_count))
459 return FALSE;
461 if ((newmode = DEBUG_GetSelectorType(addr.seg)) == MODE_INVALID) newmode = MODE_32;
462 if (newmode != DEBUG_CurrThread->dbg_mode)
464 static const char * const names[] = { "???", "16-bit", "32-bit", "vm86" };
465 DEBUG_Printf("In %s mode.\n", names[newmode] );
466 DEBUG_CurrThread->dbg_mode = newmode;
469 DEBUG_DoDisplay();
471 if (!is_debug && !force) {
472 /* This is a real crash, dump some info */
473 DEBUG_InfoRegisters(&DEBUG_context);
474 DEBUG_InfoStack();
475 #ifdef __i386__
476 if (DEBUG_CurrThread->dbg_mode == MODE_16) {
477 DEBUG_InfoSegments(DEBUG_context.SegDs >> 3, 1);
478 if (DEBUG_context.SegEs != DEBUG_context.SegDs)
479 DEBUG_InfoSegments(DEBUG_context.SegEs >> 3, 1);
481 DEBUG_InfoSegments(DEBUG_context.SegFs >> 3, 1);
482 #endif
483 DEBUG_BackTrace(DEBUG_CurrTid, TRUE);
486 if (!is_debug ||
487 (DEBUG_CurrThread->exec_mode == EXEC_STEPI_OVER) ||
488 (DEBUG_CurrThread->exec_mode == EXEC_STEPI_INSTR)) {
490 struct list_id list;
492 /* Show where we crashed */
493 curr_frame = 0;
494 DEBUG_DisassembleInstruction(&addr);
496 /* resets list internal arguments so we can look at source code when needed */
497 DEBUG_FindNearestSymbol(&addr, TRUE, NULL, 0, &list);
498 if (list.sourcefile) DEBUG_List(&list, NULL, 0);
500 return TRUE;
503 static void DEBUG_ExceptionEpilog(void)
505 DEBUG_RestartExecution(DEBUG_CurrThread->exec_count);
507 * This will have gotten absorbed into the breakpoint info
508 * if it was used. Otherwise it would have been ignored.
509 * In any case, we don't mess with it any more.
511 if (DEBUG_CurrThread->exec_mode == EXEC_CONT)
512 DEBUG_CurrThread->exec_count = 0;
513 DEBUG_InException = FALSE;
516 static DWORD DEBUG_HandleException(EXCEPTION_RECORD *rec, BOOL first_chance, BOOL force)
518 BOOL is_debug = FALSE;
519 THREADNAME_INFO *pThreadName;
520 DBG_THREAD *pThread;
522 assert(DEBUG_CurrThread);
524 switch (rec->ExceptionCode)
526 case EXCEPTION_BREAKPOINT:
527 case EXCEPTION_SINGLE_STEP:
528 is_debug = TRUE;
529 break;
530 case EXCEPTION_NAME_THREAD:
531 pThreadName = (THREADNAME_INFO*)(rec->ExceptionInformation);
532 if (pThreadName->dwThreadID == -1)
533 pThread = DEBUG_CurrThread;
534 else
535 pThread = DEBUG_GetThread(DEBUG_CurrProcess, pThreadName->dwThreadID);
537 if (ReadProcessMemory(DEBUG_CurrThread->process->handle, pThreadName->szName,
538 pThread->name, 9, NULL))
539 DEBUG_Printf("Thread ID=0x%lx renamed using MS VC6 extension (name==\"%s\")\n",
540 pThread->tid, pThread->name);
541 return DBG_CONTINUE;
544 if (first_chance && !is_debug && !force && !DBG_IVAR(BreakOnFirstChance))
546 /* pass exception to program except for debug exceptions */
547 return DBG_EXCEPTION_NOT_HANDLED;
550 if (!is_debug)
552 /* print some infos */
553 DEBUG_Printf("%s: ",
554 first_chance ? "First chance exception" : "Unhandled exception");
555 switch (rec->ExceptionCode)
557 case EXCEPTION_INT_DIVIDE_BY_ZERO:
558 DEBUG_Printf("divide by zero");
559 break;
560 case EXCEPTION_INT_OVERFLOW:
561 DEBUG_Printf("overflow");
562 break;
563 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
564 DEBUG_Printf("array bounds");
565 break;
566 case EXCEPTION_ILLEGAL_INSTRUCTION:
567 DEBUG_Printf("illegal instruction");
568 break;
569 case EXCEPTION_STACK_OVERFLOW:
570 DEBUG_Printf("stack overflow");
571 break;
572 case EXCEPTION_PRIV_INSTRUCTION:
573 DEBUG_Printf("privileged instruction");
574 break;
575 case EXCEPTION_ACCESS_VIOLATION:
576 if (rec->NumberParameters == 2)
577 DEBUG_Printf("page fault on %s access to 0x%08lx",
578 rec->ExceptionInformation[0] ? "write" : "read",
579 rec->ExceptionInformation[1]);
580 else
581 DEBUG_Printf("page fault");
582 break;
583 case EXCEPTION_DATATYPE_MISALIGNMENT:
584 DEBUG_Printf("Alignment");
585 break;
586 case DBG_CONTROL_C:
587 DEBUG_Printf("^C");
588 break;
589 case CONTROL_C_EXIT:
590 DEBUG_Printf("^C");
591 break;
592 case STATUS_POSSIBLE_DEADLOCK:
594 DBG_ADDR addr;
596 addr.seg = 0;
597 addr.off = rec->ExceptionInformation[0];
599 DEBUG_Printf("wait failed on critical section ");
600 DEBUG_PrintAddress(&addr, DEBUG_CurrThread->dbg_mode, FALSE);
602 if (!DBG_IVAR(BreakOnCritSectTimeOut))
604 DEBUG_Printf("\n");
605 return DBG_EXCEPTION_NOT_HANDLED;
607 break;
608 case EXCEPTION_WINE_STUB:
610 char dll[32], name[64];
611 DEBUG_ProcessGetString( dll, sizeof(dll), DEBUG_CurrThread->process->handle,
612 (char *)rec->ExceptionInformation[0] );
613 DEBUG_ProcessGetString( name, sizeof(name), DEBUG_CurrThread->process->handle,
614 (char *)rec->ExceptionInformation[1] );
615 DEBUG_Printf("unimplemented function %s.%s called", dll, name );
617 break;
618 case EXCEPTION_WINE_ASSERTION:
619 DEBUG_Printf("assertion failed");
620 break;
621 case EXCEPTION_VM86_INTx:
622 DEBUG_Printf("interrupt %02lx in vm86 mode",
623 rec->ExceptionInformation[0]);
624 break;
625 case EXCEPTION_VM86_STI:
626 DEBUG_Printf("sti in vm86 mode");
627 break;
628 case EXCEPTION_VM86_PICRETURN:
629 DEBUG_Printf("PIC return in vm86 mode");
630 break;
631 case EXCEPTION_FLT_DENORMAL_OPERAND:
632 DEBUG_Printf("denormal float operand");
633 break;
634 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
635 DEBUG_Printf("divide by zero");
636 break;
637 case EXCEPTION_FLT_INEXACT_RESULT:
638 DEBUG_Printf("inexact float result");
639 break;
640 case EXCEPTION_FLT_INVALID_OPERATION:
641 DEBUG_Printf("invalid float operation");
642 break;
643 case EXCEPTION_FLT_OVERFLOW:
644 DEBUG_Printf("floating pointer overflow");
645 break;
646 case EXCEPTION_FLT_UNDERFLOW:
647 DEBUG_Printf("floating pointer underflow");
648 break;
649 case EXCEPTION_FLT_STACK_CHECK:
650 DEBUG_Printf("floating point stack check");
651 break;
652 default:
653 DEBUG_Printf("%08lx", rec->ExceptionCode);
654 break;
658 if (local_mode == automatic_mode)
660 DEBUG_ExceptionProlog(is_debug, FALSE, rec->ExceptionCode);
661 DEBUG_ExceptionEpilog();
662 return 0; /* terminate execution */
665 if (DEBUG_ExceptionProlog(is_debug, force, rec->ExceptionCode))
667 DEBUG_InteractiveP = TRUE;
668 return 0;
670 DEBUG_ExceptionEpilog();
672 return DBG_CONTINUE;
675 static BOOL DEBUG_HandleDebugEvent(DEBUG_EVENT* de)
677 char buffer[256];
678 DWORD cont = DBG_CONTINUE;
680 DEBUG_CurrPid = de->dwProcessId;
681 DEBUG_CurrTid = de->dwThreadId;
683 if ((DEBUG_CurrProcess = DEBUG_GetProcess(de->dwProcessId)) != NULL)
684 DEBUG_CurrThread = DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId);
685 else
686 DEBUG_CurrThread = NULL;
688 switch (de->dwDebugEventCode)
690 case EXCEPTION_DEBUG_EVENT:
691 if (!DEBUG_CurrThread)
693 WINE_ERR("%08lx:%08lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
694 de->dwProcessId, de->dwThreadId);
695 break;
698 WINE_TRACE("%08lx:%08lx: exception code=%08lx\n",
699 de->dwProcessId, de->dwThreadId,
700 de->u.Exception.ExceptionRecord.ExceptionCode);
702 if (DEBUG_CurrProcess->continue_on_first_exception)
704 DEBUG_CurrProcess->continue_on_first_exception = FALSE;
705 if (!DBG_IVAR(BreakOnAttach)) break;
708 if (DEBUG_FetchContext())
710 cont = DEBUG_HandleException(&de->u.Exception.ExceptionRecord,
711 de->u.Exception.dwFirstChance,
712 DEBUG_CurrThread->wait_for_first_exception);
713 if (cont && DEBUG_CurrThread)
715 DEBUG_CurrThread->wait_for_first_exception = 0;
716 SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context);
719 break;
721 case CREATE_THREAD_DEBUG_EVENT:
722 WINE_TRACE("%08lx:%08lx: create thread D @%08lx\n", de->dwProcessId, de->dwThreadId,
723 (unsigned long)(LPVOID)de->u.CreateThread.lpStartAddress);
725 if (DEBUG_CurrProcess == NULL)
727 WINE_ERR("Unknown process\n");
728 break;
730 if (DEBUG_GetThread(DEBUG_CurrProcess, de->dwThreadId) != NULL)
732 WINE_TRACE("Thread already listed, skipping\n");
733 break;
736 DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
737 de->dwThreadId,
738 de->u.CreateThread.hThread,
739 de->u.CreateThread.lpStartAddress,
740 de->u.CreateThread.lpThreadLocalBase);
741 if (!DEBUG_CurrThread)
743 WINE_ERR("Couldn't create thread\n");
744 break;
746 DEBUG_InitCurrThread();
747 break;
749 case CREATE_PROCESS_DEBUG_EVENT:
750 DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
751 de->u.CreateProcessInfo.hProcess,
752 de->u.CreateProcessInfo.lpImageName,
753 de->u.CreateProcessInfo.fUnicode);
755 WINE_TRACE("%08lx:%08lx: create process '%s'/%p @%08lx (%ld<%ld>)\n",
756 de->dwProcessId, de->dwThreadId,
757 buffer, de->u.CreateProcessInfo.lpImageName,
758 (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress,
759 de->u.CreateProcessInfo.dwDebugInfoFileOffset,
760 de->u.CreateProcessInfo.nDebugInfoSize);
762 DEBUG_CurrProcess = DEBUG_AddProcess(de->dwProcessId,
763 de->u.CreateProcessInfo.hProcess,
764 buffer[0] ? buffer : "<Debugged Process>");
765 if (DEBUG_CurrProcess == NULL)
767 WINE_ERR("Couldn't create process\n");
768 break;
771 WINE_TRACE("%08lx:%08lx: create thread I @%08lx\n",
772 de->dwProcessId, de->dwThreadId,
773 (unsigned long)(LPVOID)de->u.CreateProcessInfo.lpStartAddress);
775 DEBUG_CurrThread = DEBUG_AddThread(DEBUG_CurrProcess,
776 de->dwThreadId,
777 de->u.CreateProcessInfo.hThread,
778 de->u.CreateProcessInfo.lpStartAddress,
779 de->u.CreateProcessInfo.lpThreadLocalBase);
780 if (!DEBUG_CurrThread)
782 WINE_ERR("Couldn't create thread\n");
783 break;
785 else
787 struct elf_info elf_info;
789 DEBUG_InitCurrProcess();
790 DEBUG_InitCurrThread();
792 elf_info.flags = ELF_INFO_MODULE;
794 if (DEBUG_ReadWineLoaderDbgInfo(DEBUG_CurrProcess->handle, &elf_info) != DIL_ERROR &&
795 DEBUG_SetElfSoLoadBreakpoint(&elf_info))
797 /* then load the main module's symbols */
798 DEBUG_LoadPEModule(DEBUG_CurrProcess->imageName,
799 de->u.CreateProcessInfo.hFile,
800 de->u.CreateProcessInfo.lpBaseOfImage);
802 else
804 DEBUG_DelThread(DEBUG_CurrProcess->threads);
805 DEBUG_DelProcess(DEBUG_CurrProcess);
806 DEBUG_Printf("Couldn't load process\n");
809 break;
811 case EXIT_THREAD_DEBUG_EVENT:
812 WINE_TRACE("%08lx:%08lx: exit thread (%ld)\n",
813 de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
815 if (DEBUG_CurrThread == NULL)
817 WINE_ERR("Unknown thread\n");
818 break;
820 /* FIXME: remove break point set on thread startup */
821 DEBUG_DelThread(DEBUG_CurrThread);
822 break;
824 case EXIT_PROCESS_DEBUG_EVENT:
825 WINE_TRACE("%08lx:%08lx: exit process (%ld)\n",
826 de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
828 if (DEBUG_CurrProcess == NULL)
830 WINE_ERR("Unknown process\n");
831 break;
833 /* just in case */
834 DEBUG_SetBreakpoints(FALSE);
835 /* kill last thread */
836 DEBUG_DelThread(DEBUG_CurrProcess->threads);
837 DEBUG_DelProcess(DEBUG_CurrProcess);
839 DEBUG_Printf("Process of pid=%08lx has terminated\n", DEBUG_CurrPid);
840 break;
842 case LOAD_DLL_DEBUG_EVENT:
843 if (DEBUG_CurrThread == NULL)
845 WINE_ERR("Unknown thread\n");
846 break;
848 DEBUG_ProcessGetStringIndirect(buffer, sizeof(buffer),
849 DEBUG_CurrThread->process->handle,
850 de->u.LoadDll.lpImageName,
851 de->u.LoadDll.fUnicode);
853 WINE_TRACE("%08lx:%08lx: loads DLL %s @%08lx (%ld<%ld>)\n",
854 de->dwProcessId, de->dwThreadId,
855 buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll,
856 de->u.LoadDll.dwDebugInfoFileOffset,
857 de->u.LoadDll.nDebugInfoSize);
858 _strupr(buffer);
859 DEBUG_LoadPEModule(buffer, de->u.LoadDll.hFile, de->u.LoadDll.lpBaseOfDll);
860 DEBUG_CheckDelayedBP();
861 if (DBG_IVAR(BreakOnDllLoad))
863 DEBUG_Printf("Stopping on DLL %s loading at %08lx\n",
864 buffer, (unsigned long)de->u.LoadDll.lpBaseOfDll);
865 if (DEBUG_FetchContext()) cont = 0;
867 break;
869 case UNLOAD_DLL_DEBUG_EVENT:
870 WINE_TRACE("%08lx:%08lx: unload DLL @%08lx\n", de->dwProcessId, de->dwThreadId,
871 (unsigned long)de->u.UnloadDll.lpBaseOfDll);
872 break;
874 case OUTPUT_DEBUG_STRING_EVENT:
875 if (DEBUG_CurrThread == NULL)
877 WINE_ERR("Unknown thread\n");
878 break;
881 DEBUG_ProcessGetString(buffer, sizeof(buffer),
882 DEBUG_CurrThread->process->handle,
883 de->u.DebugString.lpDebugStringData);
885 /* FIXME unicode de->u.DebugString.fUnicode ? */
886 WINE_TRACE("%08lx:%08lx: output debug string (%s)\n",
887 de->dwProcessId, de->dwThreadId, buffer);
888 break;
890 case RIP_EVENT:
891 WINE_TRACE("%08lx:%08lx: rip error=%ld type=%ld\n",
892 de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
893 de->u.RipInfo.dwType);
894 break;
896 default:
897 WINE_TRACE("%08lx:%08lx: unknown event (%ld)\n",
898 de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
900 if (!cont) return TRUE; /* stop execution */
901 ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
902 return FALSE; /* continue execution */
905 static void DEBUG_ResumeDebuggee(DWORD cont)
907 if (DEBUG_InException)
909 DEBUG_ExceptionEpilog();
910 #ifdef __i386__
911 WINE_TRACE("Exiting debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
912 DEBUG_context.Eip, DEBUG_context.EFlags,
913 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
914 #else
915 WINE_TRACE("Exiting debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
916 0L, 0L,
917 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
918 #endif
919 if (DEBUG_CurrThread)
921 if (!SetThreadContext(DEBUG_CurrThread->handle, &DEBUG_context))
922 DEBUG_Printf("Cannot set ctx on %lu\n", DEBUG_CurrTid);
923 DEBUG_CurrThread->wait_for_first_exception = 0;
926 DEBUG_InteractiveP = FALSE;
927 if (!ContinueDebugEvent(DEBUG_CurrPid, DEBUG_CurrTid, cont))
928 DEBUG_Printf("Cannot continue on %lu (%lu)\n", DEBUG_CurrTid, cont);
931 void DEBUG_WaitNextException(DWORD cont, int count, int mode)
933 DEBUG_EVENT de;
935 if (cont == DBG_CONTINUE)
937 DEBUG_CurrThread->exec_count = count;
938 DEBUG_CurrThread->exec_mode = mode;
940 DEBUG_ResumeDebuggee(cont);
942 while (DEBUG_CurrProcess && WaitForDebugEvent(&de, INFINITE))
944 if (DEBUG_HandleDebugEvent(&de)) break;
946 if (!DEBUG_CurrProcess) return;
947 DEBUG_InteractiveP = TRUE;
948 #ifdef __i386__
949 WINE_TRACE("Entering debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
950 DEBUG_context.Eip, DEBUG_context.EFlags,
951 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
952 #else
953 WINE_TRACE("Entering debugger PC=%lx EFL=%08lx mode=%d count=%d\n",
954 0L, 0L,
955 DEBUG_CurrThread->exec_mode, DEBUG_CurrThread->exec_count);
956 #endif
959 static DWORD DEBUG_MainLoop(void)
961 DEBUG_EVENT de;
963 DEBUG_Printf("WineDbg starting on pid %lx\n", DEBUG_CurrPid);
965 /* wait for first exception */
966 while (WaitForDebugEvent(&de, INFINITE))
968 if (DEBUG_HandleDebugEvent(&de)) break;
970 if (local_mode == automatic_mode)
972 /* print some extra information */
973 DEBUG_Printf("Modules:\n");
974 DEBUG_WalkModules();
975 DEBUG_Printf("Threads:\n");
976 DEBUG_WalkThreads();
978 else
980 DEBUG_InteractiveP = TRUE;
981 DEBUG_Parser(NULL);
983 DEBUG_Printf("WineDbg terminated on pid %lx\n", DEBUG_CurrPid);
985 return 0;
988 static BOOL DEBUG_Start(LPSTR cmdLine)
990 PROCESS_INFORMATION info;
991 STARTUPINFOA startup;
993 memset(&startup, 0, sizeof(startup));
994 startup.cb = sizeof(startup);
995 startup.dwFlags = STARTF_USESHOWWINDOW;
996 startup.wShowWindow = SW_SHOWNORMAL;
998 /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUI:s need it
999 * while GUI:s don't
1001 if (!CreateProcess(NULL, cmdLine, NULL, NULL,
1002 FALSE, DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS|CREATE_NEW_CONSOLE,
1003 NULL, NULL, &startup, &info))
1005 DEBUG_Printf("Couldn't start process '%s'\n", cmdLine);
1006 return FALSE;
1008 DEBUG_CurrPid = info.dwProcessId;
1009 if (!(DEBUG_CurrProcess = DEBUG_AddProcess(DEBUG_CurrPid, 0, NULL))) return FALSE;
1011 return TRUE;
1014 void DEBUG_Run(const char* args)
1016 DBG_MODULE* wmod = DEBUG_GetProcessMainModule(DEBUG_CurrProcess);
1017 const char* pgm = (wmod) ? wmod->module_name : "none";
1019 if (args) {
1020 DEBUG_Printf("Run (%s) with '%s'\n", pgm, args);
1021 } else {
1022 if (!DEBUG_LastCmdLine) {
1023 DEBUG_Printf("Cannot find previously used command line.\n");
1024 return;
1026 DEBUG_Start(DEBUG_LastCmdLine);
1030 BOOL DEBUG_InterruptDebuggee(void)
1032 DEBUG_Printf("Ctrl-C: stopping debuggee\n");
1033 /* FIXME: since we likely have a single process, signal the first process
1034 * in list
1036 if (!DEBUG_ProcessList) return FALSE;
1037 DEBUG_ProcessList->continue_on_first_exception = FALSE;
1038 return DebugBreakProcess(DEBUG_ProcessList->handle);
1041 static BOOL WINAPI DEBUG_CtrlCHandler(DWORD dwCtrlType)
1043 if (dwCtrlType == CTRL_C_EVENT)
1045 return DEBUG_InterruptDebuggee();
1047 return FALSE;
1050 static void DEBUG_InitConsole(void)
1052 /* set our control-C handler */
1053 SetConsoleCtrlHandler(DEBUG_CtrlCHandler, TRUE);
1055 /* set our own title */
1056 SetConsoleTitle("Wine Debugger");
1059 static int DEBUG_Usage(void)
1061 DEBUG_Printf("Usage: winedbg [--debugmsg dbgoptions] [--auto] [--gdb] cmdline\n" );
1062 return 1;
1065 int main(int argc, char** argv)
1067 DWORD retv = 0;
1068 unsigned gdb_flags = 0;
1070 /* Initialize the type handling stuff. */
1071 DEBUG_InitTypes();
1072 DEBUG_InitCVDataTypes();
1074 /* Initialize internal vars (types must have been initialized before) */
1075 if (!DEBUG_IntVarsRW(TRUE)) return -1;
1077 /* parse options */
1078 while (argc > 1 && argv[1][0] == '-')
1080 if (!strcmp( argv[1], "--auto" ))
1082 if (local_mode != none_mode) return DEBUG_Usage();
1083 local_mode = automatic_mode;
1084 /* force some internal variables */
1085 DBG_IVAR(BreakOnDllLoad) = 0;
1086 argc--; argv++;
1087 continue;
1089 if (!strcmp( argv[1], "--gdb" ))
1091 if (local_mode != none_mode) return DEBUG_Usage();
1092 local_mode = gdb_mode;
1093 argc--; argv++;
1094 continue;
1096 if (strcmp( argv[1], "--no-start") == 0 && local_mode == gdb_mode)
1098 gdb_flags |= 1;
1099 argc--; argv++; /* as we don't use argv[0] */
1100 continue;
1102 if (strcmp(argv[1], "--with-xterm") == 0 && local_mode == gdb_mode)
1104 gdb_flags |= 2;
1105 argc--; argv++; /* as we don't use argv[0] */
1106 continue;
1108 if (!strcmp( argv[1], "--debugmsg" ) && argv[2])
1110 wine_dbg_parse_options( argv[2] );
1111 argc -= 2;
1112 argv += 2;
1113 continue;
1115 return DEBUG_Usage();
1118 if (local_mode == none_mode) local_mode = winedbg_mode;
1120 /* try the form <myself> pid */
1121 if (DEBUG_CurrPid == 0 && argc == 2)
1123 char* ptr;
1125 DEBUG_CurrPid = strtol(argv[1], &ptr, 10);
1126 if (DEBUG_CurrPid == 0 || ptr == NULL ||
1127 !DEBUG_Attach(DEBUG_CurrPid, local_mode != gdb_mode, FALSE))
1128 DEBUG_CurrPid = 0;
1131 /* try the form <myself> pid evt (Win32 JIT debugger) */
1132 if (DEBUG_CurrPid == 0 && argc == 3)
1134 HANDLE hEvent;
1135 DWORD pid;
1136 char* ptr;
1138 if ((pid = strtol(argv[1], &ptr, 10)) != 0 && ptr != NULL &&
1139 (hEvent = (HANDLE)strtol(argv[2], &ptr, 10)) != 0 && ptr != NULL)
1141 if (!DEBUG_Attach(pid, TRUE, FALSE))
1143 /* don't care about result */
1144 SetEvent(hEvent);
1145 goto leave;
1147 if (!SetEvent(hEvent))
1149 WINE_ERR("Invalid event handle: %p\n", hEvent);
1150 goto leave;
1152 CloseHandle(hEvent);
1153 DEBUG_CurrPid = pid;
1157 if (DEBUG_CurrPid == 0 && argc > 1)
1159 int i, len;
1160 LPSTR cmdLine;
1162 if (!(cmdLine = DBG_alloc(len = 1))) goto oom_leave;
1163 cmdLine[0] = '\0';
1165 for (i = 1; i < argc; i++)
1167 len += strlen(argv[i]) + 1;
1168 if (!(cmdLine = DBG_realloc(cmdLine, len))) goto oom_leave;
1169 strcat(cmdLine, argv[i]);
1170 cmdLine[len - 2] = ' ';
1171 cmdLine[len - 1] = '\0';
1174 if (!DEBUG_Start(cmdLine))
1176 DEBUG_Printf("Couldn't start process '%s'\n", cmdLine);
1177 goto leave;
1179 DBG_free(DEBUG_LastCmdLine);
1180 DEBUG_LastCmdLine = cmdLine;
1182 /* don't save local vars in gdb mode */
1183 if (local_mode == gdb_mode && DEBUG_CurrPid)
1184 return DEBUG_GdbRemote(gdb_flags);
1186 DEBUG_InitConsole();
1188 retv = DEBUG_MainLoop();
1189 /* don't save modified variables in auto mode */
1190 if (local_mode != automatic_mode) DEBUG_IntVarsRW(FALSE);
1192 leave:
1193 return retv;
1195 oom_leave:
1196 DEBUG_Printf("Out of memory\n");
1197 goto leave;