push a2e7360632735b5a2be8f61a9725e4e6969c5533
[wine/hacks.git] / programs / winedbg / winedbg.c
blob5cbc68faf8fe5c3458c15024f885bf633c559f97
1 /* Wine internal debugger
2 * Interface to Windows debugger API
3 * Copyright 2000-2004 Eric Pouech
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include "debugger.h"
28 #include "winternl.h"
29 #include "wine/exception.h"
30 #include "wine/library.h"
32 #include "wine/debug.h"
34 /* TODO list:
36 * - minidump
37 * + ensure that all commands work as expected in minidump reload function
38 * (and reenable parser usager)
39 * - CPU adherence
40 * + we always assume the stack grows as on i386 (ie downwards)
41 * - UI
42 * + enable back the limited output (depth of structure printing and number of
43 * lines)
44 * + make the output as close as possible to what gdb does
45 * - symbol management:
46 * + symbol table loading is broken
47 * + in symbol_get_lvalue, we don't do any scoping (as C does) between local and
48 * global vars (we may need this to force some display for example). A solution
49 * would be always to return arrays with: local vars, global vars, thunks
50 * - type management:
51 * + some bits of internal types are missing (like type casts and the address
52 * operator)
53 * + the type for an enum's value is always inferred as int (winedbg & dbghelp)
54 * + most of the code implies that sizeof(void*) = sizeof(int)
55 * + all computations should be made on long long
56 * o expr computations are in int:s
57 * o bitfield size is on a 4-bytes
58 * + array_index and deref should be the same function (or should share the same
59 * core)
60 * - execution:
61 * + set a better fix for gdb (proxy mode) than the step-mode hack
62 * + implement function call in debuggee
63 * + trampoline management is broken when getting 16 <=> 32 thunk destination
64 * address
65 * + thunking of delayed imports doesn't work as expected (ie, when stepping,
66 * it currently stops at first insn with line number during the library
67 * loading). We should identify this (__wine_delay_import) and set a
68 * breakpoint instead of single stepping the library loading.
69 * + it's wrong to copy thread->step_over_bp into process->bp[0] (when
70 * we have a multi-thread debuggee). complete fix must include storing all
71 * thread's step-over bp in process-wide bp array, and not to handle bp
72 * when we have the wrong thread running into that bp
73 * + code in CREATE_PROCESS debug event doesn't work on Windows, as we cannot
74 * get the name of the main module this way. We should rewrite all this code
75 * and store in struct dbg_process as early as possible (before process
76 * creation or attachment), the name of the main module
77 * - global:
78 * + define a better way to enable the wine extensions (either DBG SDK function
79 * in dbghelp, or TLS variable, or environment variable or ...)
80 * + audit all files to ensure that we check all potential return values from
81 * every function call to catch the errors
82 * + BTW check also whether the exception mechanism is the best way to return
83 * errors (or find a proper fix for MinGW port)
84 * + use Wine standard list mechanism for all list handling
87 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
89 struct dbg_process* dbg_curr_process = NULL;
90 struct dbg_thread* dbg_curr_thread = NULL;
91 DWORD dbg_curr_tid;
92 DWORD dbg_curr_pid;
93 CONTEXT dbg_context;
94 BOOL dbg_interactiveP = FALSE;
96 static struct dbg_process* dbg_process_list = NULL;
98 struct dbg_internal_var dbg_internal_vars[DBG_IV_LAST];
99 const struct dbg_internal_var* dbg_context_vars;
100 static HANDLE dbg_houtput;
102 void dbg_outputA(const char* buffer, int len)
104 static char line_buff[4096];
105 static unsigned int line_pos;
107 DWORD w, i;
109 while (len > 0)
111 unsigned int count = min( len, sizeof(line_buff) - line_pos );
112 memcpy( line_buff + line_pos, buffer, count );
113 buffer += count;
114 len -= count;
115 line_pos += count;
116 for (i = line_pos; i > 0; i--) if (line_buff[i-1] == '\n') break;
117 if (!i) /* no newline found */
119 if (len > 0) i = line_pos; /* buffer is full, flush anyway */
120 else break;
122 WriteFile(dbg_houtput, line_buff, i, &w, NULL);
123 memmove( line_buff, line_buff + i, line_pos - i );
124 line_pos -= i;
128 void dbg_outputW(const WCHAR* buffer, int len)
130 char* ansi = NULL;
131 int newlen;
133 /* do a serious Unicode to ANSI conversion
134 * FIXME: should CP_ACP be GetConsoleCP()?
136 newlen = WideCharToMultiByte(CP_ACP, 0, buffer, len, NULL, 0, NULL, NULL);
137 if (newlen)
139 if (!(ansi = HeapAlloc(GetProcessHeap(), 0, newlen))) return;
140 WideCharToMultiByte(CP_ACP, 0, buffer, len, ansi, newlen, NULL, NULL);
141 dbg_outputA(ansi, newlen);
142 HeapFree(GetProcessHeap(), 0, ansi);
146 int dbg_printf(const char* format, ...)
148 static char buf[4*1024];
149 va_list valist;
150 int len;
152 va_start(valist, format);
153 len = vsnprintf(buf, sizeof(buf), format, valist);
154 va_end(valist);
156 if (len <= -1 || len >= sizeof(buf))
158 len = sizeof(buf) - 1;
159 buf[len] = 0;
160 buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
162 dbg_outputA(buf, len);
163 return len;
166 static unsigned dbg_load_internal_vars(void)
168 HKEY hkey;
169 DWORD type = REG_DWORD;
170 DWORD val;
171 DWORD count = sizeof(val);
172 int i;
173 struct dbg_internal_var* div = dbg_internal_vars;
175 /* initializes internal vars table */
176 #define INTERNAL_VAR(_var,_val,_ref,_tid) \
177 div->val = _val; div->name = #_var; div->pval = _ref; \
178 div->typeid = _tid; div++;
179 #include "intvar.h"
180 #undef INTERNAL_VAR
182 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
183 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
185 WINE_ERR("Cannot create WineDbg key in registry\n");
186 return FALSE;
189 for (i = 0; i < DBG_IV_LAST; i++)
191 if (!dbg_internal_vars[i].pval)
193 if (!RegQueryValueEx(hkey, dbg_internal_vars[i].name, 0,
194 &type, (LPBYTE)&val, &count))
195 dbg_internal_vars[i].val = val;
196 dbg_internal_vars[i].pval = &dbg_internal_vars[i].val;
199 RegCloseKey(hkey);
200 /* set up the debug variables for the CPU context */
201 dbg_context_vars = be_cpu->init_registers(&dbg_context);
202 return TRUE;
205 static unsigned dbg_save_internal_vars(void)
207 HKEY hkey;
208 int i;
210 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
211 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
213 WINE_ERR("Cannot create WineDbg key in registry\n");
214 return FALSE;
217 for (i = 0; i < DBG_IV_LAST; i++)
219 /* FIXME: type should be inferred from basic type -if any- of intvar */
220 if (dbg_internal_vars[i].pval == &dbg_internal_vars[i].val)
221 RegSetValueEx(hkey, dbg_internal_vars[i].name, 0,
222 REG_DWORD, (const void*)dbg_internal_vars[i].pval,
223 sizeof(*dbg_internal_vars[i].pval));
225 RegCloseKey(hkey);
226 return TRUE;
229 const struct dbg_internal_var* dbg_get_internal_var(const char* name)
231 const struct dbg_internal_var* div;
233 for (div = &dbg_internal_vars[DBG_IV_LAST - 1]; div >= dbg_internal_vars; div--)
235 if (!strcmp(div->name, name)) return div;
237 for (div = dbg_context_vars; div->name; div++)
239 if (!strcasecmp(div->name, name)) return div;
242 return NULL;
245 unsigned dbg_num_processes(void)
247 struct dbg_process* p;
248 unsigned num = 0;
250 for (p = dbg_process_list; p; p = p->next)
251 num++;
252 return num;
255 struct dbg_process* dbg_get_process(DWORD pid)
257 struct dbg_process* p;
259 for (p = dbg_process_list; p; p = p->next)
260 if (p->pid == pid) break;
261 return p;
264 struct dbg_process* dbg_get_process_h(HANDLE h)
266 struct dbg_process* p;
268 for (p = dbg_process_list; p; p = p->next)
269 if (p->handle == h) break;
270 return p;
273 struct dbg_process* dbg_add_process(const struct be_process_io* pio, DWORD pid, HANDLE h)
275 struct dbg_process* p;
277 if ((p = dbg_get_process(pid)))
279 if (p->handle != 0)
281 WINE_ERR("Process (%04x) is already defined\n", pid);
283 else
285 p->handle = h;
286 p->process_io = pio;
287 p->imageName = NULL;
289 return p;
292 if (!(p = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_process)))) return NULL;
293 p->handle = h;
294 p->pid = pid;
295 p->process_io = pio;
296 p->pio_data = NULL;
297 p->imageName = NULL;
298 p->threads = NULL;
299 p->continue_on_first_exception = FALSE;
300 p->active_debuggee = FALSE;
301 p->next_bp = 1; /* breakpoint 0 is reserved for step-over */
302 memset(p->bp, 0, sizeof(p->bp));
303 p->delayed_bp = NULL;
304 p->num_delayed_bp = 0;
305 p->source_ofiles = NULL;
306 p->search_path = NULL;
307 p->source_current_file[0] = '\0';
308 p->source_start_line = -1;
309 p->source_end_line = -1;
311 p->next = dbg_process_list;
312 p->prev = NULL;
313 if (dbg_process_list) dbg_process_list->prev = p;
314 dbg_process_list = p;
315 return p;
318 void dbg_set_process_name(struct dbg_process* p, const char* imageName)
320 assert(p->imageName == NULL);
321 if (imageName)
323 char* tmp = HeapAlloc(GetProcessHeap(), 0, strlen(imageName) + 1);
324 if (tmp) p->imageName = strcpy(tmp, imageName);
328 void dbg_del_process(struct dbg_process* p)
330 int i;
332 while (p->threads) dbg_del_thread(p->threads);
334 for (i = 0; i < p->num_delayed_bp; i++)
335 if (p->delayed_bp[i].is_symbol)
336 HeapFree(GetProcessHeap(), 0, p->delayed_bp[i].u.symbol.name);
338 HeapFree(GetProcessHeap(), 0, p->delayed_bp);
339 source_nuke_path(p);
340 source_free_files(p);
341 if (p->prev) p->prev->next = p->next;
342 if (p->next) p->next->prev = p->prev;
343 if (p == dbg_process_list) dbg_process_list = p->next;
344 if (p == dbg_curr_process) dbg_curr_process = NULL;
345 HeapFree(GetProcessHeap(), 0, (char*)p->imageName);
346 HeapFree(GetProcessHeap(), 0, p);
349 /******************************************************************
350 * dbg_init
352 * Initializes the dbghelp library, and also sets the application directory
353 * as a place holder for symbol searches.
355 BOOL dbg_init(HANDLE hProc, const char* in, BOOL invade)
357 BOOL ret;
359 ret = SymInitialize(hProc, NULL, invade);
360 if (ret && in)
362 const char* last;
364 for (last = in + strlen(in) - 1; last >= in; last--)
366 if (*last == '/' || *last == '\\')
368 char* tmp;
369 tmp = HeapAlloc(GetProcessHeap(), 0, 1024 + 1 + (last - in) + 1);
370 if (tmp && SymGetSearchPath(hProc, tmp, 1024))
372 char* x = tmp + strlen(tmp);
374 *x++ = ';';
375 memcpy(x, in, last - in);
376 x[last - in] = '\0';
377 ret = SymSetSearchPath(hProc, tmp);
379 else ret = FALSE;
380 HeapFree(GetProcessHeap(), 0, tmp);
381 break;
385 return ret;
388 struct mod_loader_info
390 HANDLE handle;
391 IMAGEHLP_MODULE* imh_mod;
394 static BOOL CALLBACK mod_loader_cb(PCSTR mod_name, ULONG base, PVOID ctx)
396 struct mod_loader_info* mli = (struct mod_loader_info*)ctx;
398 if (!strcmp(mod_name, "<wine-loader>"))
400 if (SymGetModuleInfo(mli->handle, base, mli->imh_mod))
401 return FALSE; /* stop enum */
403 return TRUE;
406 BOOL dbg_get_debuggee_info(HANDLE hProcess, IMAGEHLP_MODULE* imh_mod)
408 struct mod_loader_info mli;
409 DWORD opt;
411 /* this will resynchronize builtin dbghelp's internal ELF module list */
412 SymLoadModule(hProcess, 0, 0, 0, 0, 0);
413 mli.handle = hProcess;
414 mli.imh_mod = imh_mod;
415 imh_mod->SizeOfStruct = sizeof(*imh_mod);
416 imh_mod->BaseOfImage = 0;
417 /* this is a wine specific options to return also ELF modules in the
418 * enumeration
420 SymSetOptions((opt = SymGetOptions()) | 0x40000000);
421 SymEnumerateModules(hProcess, mod_loader_cb, (void*)&mli);
422 SymSetOptions(opt);
424 return imh_mod->BaseOfImage != 0;
427 struct dbg_thread* dbg_get_thread(struct dbg_process* p, DWORD tid)
429 struct dbg_thread* t;
431 if (!p) return NULL;
432 for (t = p->threads; t; t = t->next)
433 if (t->tid == tid) break;
434 return t;
437 struct dbg_thread* dbg_add_thread(struct dbg_process* p, DWORD tid,
438 HANDLE h, void* teb)
440 struct dbg_thread* t = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_thread));
442 if (!t)
443 return NULL;
445 t->handle = h;
446 t->tid = tid;
447 t->teb = teb;
448 t->process = p;
449 t->exec_mode = dbg_exec_cont;
450 t->exec_count = 0;
451 t->step_over_bp.enabled = FALSE;
452 t->step_over_bp.refcount = 0;
453 t->stopped_xpoint = -1;
454 t->in_exception = FALSE;
455 t->frames = NULL;
456 t->num_frames = 0;
457 t->curr_frame = -1;
458 t->addr_mode = AddrModeFlat;
460 snprintf(t->name, sizeof(t->name), "%04x", tid);
462 t->next = p->threads;
463 t->prev = NULL;
464 if (p->threads) p->threads->prev = t;
465 p->threads = t;
467 return t;
470 void dbg_del_thread(struct dbg_thread* t)
472 HeapFree(GetProcessHeap(), 0, t->frames);
473 if (t->prev) t->prev->next = t->next;
474 if (t->next) t->next->prev = t->prev;
475 if (t == t->process->threads) t->process->threads = t->next;
476 if (t == dbg_curr_thread) dbg_curr_thread = NULL;
477 HeapFree(GetProcessHeap(), 0, t);
480 BOOL dbg_interrupt_debuggee(void)
482 if (!dbg_process_list) return FALSE;
483 /* FIXME: since we likely have a single process, signal the first process
484 * in list
486 if (dbg_process_list->next) dbg_printf("Ctrl-C: only stopping the first process\n");
487 else dbg_printf("Ctrl-C: stopping debuggee\n");
488 dbg_process_list->continue_on_first_exception = FALSE;
489 return DebugBreakProcess(dbg_process_list->handle);
492 static BOOL WINAPI ctrl_c_handler(DWORD dwCtrlType)
494 if (dwCtrlType == CTRL_C_EVENT)
496 return dbg_interrupt_debuggee();
498 return FALSE;
501 static void dbg_init_console(void)
503 /* set our control-C handler */
504 SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
506 /* set our own title */
507 SetConsoleTitle("Wine Debugger");
510 static int dbg_winedbg_usage(BOOL advanced)
512 if (advanced)
514 dbg_printf("Usage:\n"
515 " winedbg cmdline launch process 'cmdline' (as if you were starting\n"
516 " it with wine) and run WineDbg on it\n"
517 " winedbg <num> attach to running process of pid <num> and run\n"
518 " WineDbg on it\n"
519 " winedbg --gdb cmdline launch process 'cmdline' (as if you were starting\n"
520 " wine) and run gdb (proxied) on it\n"
521 " winedbg --gdb <num> attach to running process of pid <num> and run\n"
522 " gdb (proxied) on it\n"
523 " winedbg file.mdmp reload the minidump file.mdmp into memory and run\n"
524 " WineDbg on it\n"
525 " winedbg --help prints advanced options\n");
527 else
528 dbg_printf("Usage:\n\twinedbg [ [ --gdb ] [ prog-name [ prog-args ] | <num> | file.mdmp | --help ]\n");
529 return -1;
532 struct backend_cpu* be_cpu;
533 #ifdef __i386__
534 extern struct backend_cpu be_i386;
535 #elif __powerpc__
536 extern struct backend_cpu be_ppc;
537 #elif __ALPHA__
538 extern struct backend_cpu be_alpha;
539 #elif __x86_64__
540 extern struct backend_cpu be_x86_64;
541 #else
542 # error CPU unknown
543 #endif
545 int main(int argc, char** argv)
547 int retv = 0;
548 HANDLE hFile = INVALID_HANDLE_VALUE;
549 enum dbg_start ds;
551 #ifdef __i386__
552 be_cpu = &be_i386;
553 #elif __powerpc__
554 be_cpu = &be_ppc;
555 #elif __ALPHA__
556 be_cpu = &be_alpha;
557 #elif __x86_64__
558 be_cpu = &be_x86_64;
559 #else
560 # error CPU unknown
561 #endif
562 /* Initialize the output */
563 dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
565 /* Initialize internal vars */
566 if (!dbg_load_internal_vars()) return -1;
568 /* as we don't care about exec name */
569 argc--; argv++;
571 if (argc && !strcmp(argv[0], "--help"))
572 return dbg_winedbg_usage(TRUE);
574 if (argc && !strcmp(argv[0], "--gdb"))
576 retv = gdb_main(argc, argv);
577 if (retv == -1) dbg_winedbg_usage(FALSE);
578 return retv;
580 dbg_init_console();
582 SymSetOptions((SymGetOptions() & ~(SYMOPT_UNDNAME)) |
583 SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_AUTO_PUBLICS);
585 if (argc && (!strcmp(argv[0], "--auto") || !strcmp(argv[0], "--minidump")))
587 /* force some internal variables */
588 DBG_IVAR(BreakOnDllLoad) = 0;
589 dbg_houtput = GetStdHandle(STD_ERROR_HANDLE);
590 switch (dbg_active_auto(argc, argv))
592 case start_ok: return 0;
593 case start_error_parse: return dbg_winedbg_usage(FALSE);
594 case start_error_init: return -1;
597 /* parse options */
598 while (argc > 0 && argv[0][0] == '-')
600 if (!strcmp(argv[0], "--command"))
602 argc--; argv++;
603 hFile = parser_generate_command_file(argv[0], NULL);
604 if (hFile == INVALID_HANDLE_VALUE)
606 dbg_printf("Couldn't open temp file (%u)\n", GetLastError());
607 return 1;
609 argc--; argv++;
610 continue;
612 if (!strcmp(argv[0], "--file"))
614 argc--; argv++;
615 hFile = CreateFileA(argv[0], GENERIC_READ|DELETE, 0,
616 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
617 if (hFile == INVALID_HANDLE_VALUE)
619 dbg_printf("Couldn't open file %s (%u)\n", argv[0], GetLastError());
620 return 1;
622 argc--; argv++;
623 continue;
625 if (!strcmp(argv[0], "--"))
627 argc--; argv++;
628 break;
630 return dbg_winedbg_usage(FALSE);
632 if (!argc) ds = start_ok;
633 else if ((ds = dbg_active_attach(argc, argv)) == start_error_parse &&
634 (ds = minidump_reload(argc, argv)) == start_error_parse)
635 ds = dbg_active_launch(argc, argv);
636 switch (ds)
638 case start_ok: break;
639 case start_error_parse: return dbg_winedbg_usage(FALSE);
640 case start_error_init: return -1;
643 if (dbg_curr_process)
645 dbg_printf("WineDbg starting on pid %04x\n", dbg_curr_pid);
646 if (dbg_curr_process->active_debuggee) dbg_active_wait_for_first_exception();
649 dbg_interactiveP = TRUE;
650 parser_handle(hFile);
652 while (dbg_process_list)
653 dbg_process_list->process_io->close_process(dbg_process_list, FALSE);
655 dbg_save_internal_vars();
657 return 0;