include: Specify calling convention explicitly in idl files where needed.
[wine/hramrach.git] / programs / winedbg / winedbg.c
blobaeef795a839f84649bf447c7bdf749e6259a073a
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 * - execution:
59 * + set a better fix for gdb (proxy mode) than the step-mode hack
60 * + implement function call in debuggee
61 * + trampoline management is broken when getting 16 <=> 32 thunk destination
62 * address
63 * + thunking of delayed imports doesn't work as expected (ie, when stepping,
64 * it currently stops at first insn with line number during the library
65 * loading). We should identify this (__wine_delay_import) and set a
66 * breakpoint instead of single stepping the library loading.
67 * + it's wrong to copy thread->step_over_bp into process->bp[0] (when
68 * we have a multi-thread debuggee). complete fix must include storing all
69 * thread's step-over bp in process-wide bp array, and not to handle bp
70 * when we have the wrong thread running into that bp
71 * + code in CREATE_PROCESS debug event doesn't work on Windows, as we cannot
72 * get the name of the main module this way. We should rewrite all this code
73 * and store in struct dbg_process as early as possible (before process
74 * creation or attachment), the name of the main module
75 * - global:
76 * + define a better way to enable the wine extensions (either DBG SDK function
77 * in dbghelp, or TLS variable, or environment variable or ...)
78 * + audit all files to ensure that we check all potential return values from
79 * every function call to catch the errors
80 * + BTW check also whether the exception mechanism is the best way to return
81 * errors (or find a proper fix for MinGW port)
84 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
86 struct dbg_process* dbg_curr_process = NULL;
87 struct dbg_thread* dbg_curr_thread = NULL;
88 DWORD_PTR dbg_curr_tid = 0;
89 DWORD_PTR dbg_curr_pid = 0;
90 CONTEXT dbg_context;
91 BOOL dbg_interactiveP = FALSE;
93 static struct list dbg_process_list = LIST_INIT(dbg_process_list);
95 struct dbg_internal_var dbg_internal_vars[DBG_IV_LAST];
96 static HANDLE dbg_houtput;
98 static void dbg_outputA(const char* buffer, int len)
100 static char line_buff[4096];
101 static unsigned int line_pos;
103 DWORD w, i;
105 while (len > 0)
107 unsigned int count = min( len, sizeof(line_buff) - line_pos );
108 memcpy( line_buff + line_pos, buffer, count );
109 buffer += count;
110 len -= count;
111 line_pos += count;
112 for (i = line_pos; i > 0; i--) if (line_buff[i-1] == '\n') break;
113 if (!i) /* no newline found */
115 if (len > 0) i = line_pos; /* buffer is full, flush anyway */
116 else break;
118 WriteFile(dbg_houtput, line_buff, i, &w, NULL);
119 memmove( line_buff, line_buff + i, line_pos - i );
120 line_pos -= i;
124 const char* dbg_W2A(const WCHAR* buffer, unsigned len)
126 static unsigned ansilen;
127 static char* ansi;
128 unsigned newlen;
130 newlen = WideCharToMultiByte(CP_ACP, 0, buffer, len, NULL, 0, NULL, NULL);
131 if (newlen > ansilen)
133 static char* newansi;
134 if (ansi)
135 newansi = HeapReAlloc(GetProcessHeap(), 0, ansi, newlen);
136 else
137 newansi = HeapAlloc(GetProcessHeap(), 0, newlen);
138 if (!newansi) return NULL;
139 ansilen = newlen;
140 ansi = newansi;
142 WideCharToMultiByte(CP_ACP, 0, buffer, len, ansi, newlen, NULL, NULL);
143 return ansi;
146 void dbg_outputW(const WCHAR* buffer, int len)
148 const char* ansi = dbg_W2A(buffer, len);
149 if (ansi) dbg_outputA(ansi, strlen(ansi));
150 /* FIXME: should CP_ACP be GetConsoleCP()? */
153 int dbg_printf(const char* format, ...)
155 static char buf[4*1024];
156 va_list valist;
157 int len;
159 va_start(valist, format);
160 len = vsnprintf(buf, sizeof(buf), format, valist);
161 va_end(valist);
163 if (len <= -1 || len >= sizeof(buf))
165 len = sizeof(buf) - 1;
166 buf[len] = 0;
167 buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
169 dbg_outputA(buf, len);
170 return len;
173 static unsigned dbg_load_internal_vars(void)
175 HKEY hkey;
176 DWORD type = REG_DWORD;
177 DWORD val;
178 DWORD count = sizeof(val);
179 int i;
180 struct dbg_internal_var* div = dbg_internal_vars;
182 /* initializes internal vars table */
183 #define INTERNAL_VAR(_var,_val,_ref,_tid) \
184 div->val = _val; div->name = #_var; div->pval = _ref; \
185 div->typeid = _tid; div++;
186 #include "intvar.h"
187 #undef INTERNAL_VAR
189 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
190 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
192 WINE_ERR("Cannot create WineDbg key in registry\n");
193 return FALSE;
196 for (i = 0; i < DBG_IV_LAST; i++)
198 if (!dbg_internal_vars[i].pval)
200 if (!RegQueryValueExA(hkey, dbg_internal_vars[i].name, 0,
201 &type, (LPBYTE)&val, &count))
202 dbg_internal_vars[i].val = val;
203 dbg_internal_vars[i].pval = &dbg_internal_vars[i].val;
206 RegCloseKey(hkey);
208 return TRUE;
211 static unsigned dbg_save_internal_vars(void)
213 HKEY hkey;
214 int i;
216 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
217 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
219 WINE_ERR("Cannot create WineDbg key in registry\n");
220 return FALSE;
223 for (i = 0; i < DBG_IV_LAST; i++)
225 /* FIXME: type should be inferred from basic type -if any- of intvar */
226 if (dbg_internal_vars[i].pval == &dbg_internal_vars[i].val)
228 DWORD val = dbg_internal_vars[i].val;
229 RegSetValueExA(hkey, dbg_internal_vars[i].name, 0, REG_DWORD, (BYTE *)&val, sizeof(val));
232 RegCloseKey(hkey);
233 return TRUE;
236 const struct dbg_internal_var* dbg_get_internal_var(const char* name)
238 const struct dbg_internal_var* div;
240 for (div = &dbg_internal_vars[DBG_IV_LAST - 1]; div >= dbg_internal_vars; div--)
242 if (!strcmp(div->name, name)) return div;
244 for (div = be_cpu->context_vars; div->name; div++)
246 if (!strcasecmp(div->name, name))
248 struct dbg_internal_var* ret = (void*)lexeme_alloc_size(sizeof(*ret));
249 /* relocate register's field against current context */
250 *ret = *div;
251 ret->pval = (DWORD_PTR*)((char*)&dbg_context + (DWORD_PTR)div->pval);
252 return ret;
256 return NULL;
259 unsigned dbg_num_processes(void)
261 return list_count(&dbg_process_list);
264 struct dbg_process* dbg_get_process(DWORD pid)
266 struct dbg_process* p;
268 LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
269 if (p->pid == pid) return p;
270 return NULL;
273 struct dbg_process* dbg_get_process_h(HANDLE h)
275 struct dbg_process* p;
277 LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
278 if (p->handle == h) return p;
279 return NULL;
282 struct dbg_process* dbg_add_process(const struct be_process_io* pio, DWORD pid, HANDLE h)
284 struct dbg_process* p;
286 if ((p = dbg_get_process(pid)))
288 if (p->handle != 0)
290 WINE_ERR("Process (%04x) is already defined\n", pid);
292 else
294 p->handle = h;
295 p->process_io = pio;
296 p->imageName = NULL;
298 return p;
301 if (!(p = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_process)))) return NULL;
302 p->handle = h;
303 p->pid = pid;
304 p->process_io = pio;
305 p->pio_data = NULL;
306 p->imageName = NULL;
307 list_init(&p->threads);
308 p->continue_on_first_exception = FALSE;
309 p->active_debuggee = FALSE;
310 p->next_bp = 1; /* breakpoint 0 is reserved for step-over */
311 memset(p->bp, 0, sizeof(p->bp));
312 p->delayed_bp = NULL;
313 p->num_delayed_bp = 0;
314 p->source_ofiles = NULL;
315 p->search_path = NULL;
316 p->source_current_file[0] = '\0';
317 p->source_start_line = -1;
318 p->source_end_line = -1;
320 list_add_head(&dbg_process_list, &p->entry);
321 return p;
324 void dbg_set_process_name(struct dbg_process* p, const WCHAR* imageName)
326 assert(p->imageName == NULL);
327 if (imageName)
329 WCHAR* tmp = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(imageName) + 1) * sizeof(WCHAR));
330 if (tmp) p->imageName = lstrcpyW(tmp, imageName);
334 void dbg_del_process(struct dbg_process* p)
336 struct dbg_thread* t;
337 struct dbg_thread* t2;
338 int i;
340 LIST_FOR_EACH_ENTRY_SAFE(t, t2, &p->threads, struct dbg_thread, entry)
341 dbg_del_thread(t);
343 for (i = 0; i < p->num_delayed_bp; i++)
344 if (p->delayed_bp[i].is_symbol)
345 HeapFree(GetProcessHeap(), 0, p->delayed_bp[i].u.symbol.name);
347 HeapFree(GetProcessHeap(), 0, p->delayed_bp);
348 source_nuke_path(p);
349 source_free_files(p);
350 list_remove(&p->entry);
351 if (p == dbg_curr_process) dbg_curr_process = NULL;
352 HeapFree(GetProcessHeap(), 0, (char*)p->imageName);
353 HeapFree(GetProcessHeap(), 0, p);
356 /******************************************************************
357 * dbg_init
359 * Initializes the dbghelp library, and also sets the application directory
360 * as a place holder for symbol searches.
362 BOOL dbg_init(HANDLE hProc, const WCHAR* in, BOOL invade)
364 BOOL ret;
366 ret = SymInitialize(hProc, NULL, invade);
367 if (ret && in)
369 const WCHAR* last;
371 for (last = in + lstrlenW(in) - 1; last >= in; last--)
373 if (*last == '/' || *last == '\\')
375 WCHAR* tmp;
376 tmp = HeapAlloc(GetProcessHeap(), 0, (1024 + 1 + (last - in) + 1) * sizeof(WCHAR));
377 if (tmp && SymGetSearchPathW(hProc, tmp, 1024))
379 WCHAR* x = tmp + lstrlenW(tmp);
381 *x++ = ';';
382 memcpy(x, in, (last - in) * sizeof(WCHAR));
383 x[last - in] = '\0';
384 ret = SymSetSearchPathW(hProc, tmp);
386 else ret = FALSE;
387 HeapFree(GetProcessHeap(), 0, tmp);
388 break;
392 return ret;
395 struct mod_loader_info
397 HANDLE handle;
398 IMAGEHLP_MODULE64* imh_mod;
401 static BOOL CALLBACK mod_loader_cb(PCSTR mod_name, DWORD64 base, PVOID ctx)
403 struct mod_loader_info* mli = ctx;
405 if (!strcmp(mod_name, "<wine-loader>"))
407 if (SymGetModuleInfo64(mli->handle, base, mli->imh_mod))
408 return FALSE; /* stop enum */
410 return TRUE;
413 BOOL dbg_get_debuggee_info(HANDLE hProcess, IMAGEHLP_MODULE64* imh_mod)
415 struct mod_loader_info mli;
416 DWORD opt;
418 /* this will resynchronize builtin dbghelp's internal ELF module list */
419 SymLoadModule(hProcess, 0, 0, 0, 0, 0);
420 mli.handle = hProcess;
421 mli.imh_mod = imh_mod;
422 imh_mod->SizeOfStruct = sizeof(*imh_mod);
423 imh_mod->BaseOfImage = 0;
424 /* this is a wine specific options to return also ELF modules in the
425 * enumeration
427 SymSetOptions((opt = SymGetOptions()) | 0x40000000);
428 SymEnumerateModules64(hProcess, mod_loader_cb, (void*)&mli);
429 SymSetOptions(opt);
431 return imh_mod->BaseOfImage != 0;
434 BOOL dbg_load_module(HANDLE hProc, HANDLE hFile, const WCHAR* name, DWORD_PTR base, DWORD size)
436 BOOL ret = SymLoadModuleExW(hProc, NULL, name, NULL, base, size, NULL, 0);
437 if (ret)
439 IMAGEHLP_MODULEW64 ihm;
440 ihm.SizeOfStruct = sizeof(ihm);
441 if (SymGetModuleInfoW64(hProc, base, &ihm) && (ihm.PdbUnmatched || ihm.DbgUnmatched))
442 dbg_printf("Loaded unmatched debug information for %s\n", wine_dbgstr_w(name));
444 return ret;
447 struct dbg_thread* dbg_get_thread(struct dbg_process* p, DWORD tid)
449 struct dbg_thread* t;
451 if (!p) return NULL;
452 LIST_FOR_EACH_ENTRY(t, &p->threads, struct dbg_thread, entry)
453 if (t->tid == tid) return t;
454 return NULL;
457 struct dbg_thread* dbg_add_thread(struct dbg_process* p, DWORD tid,
458 HANDLE h, void* teb)
460 struct dbg_thread* t = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_thread));
462 if (!t)
463 return NULL;
465 t->handle = h;
466 t->tid = tid;
467 t->teb = teb;
468 t->process = p;
469 t->exec_mode = dbg_exec_cont;
470 t->exec_count = 0;
471 t->step_over_bp.enabled = FALSE;
472 t->step_over_bp.refcount = 0;
473 t->stopped_xpoint = -1;
474 t->in_exception = FALSE;
475 t->frames = NULL;
476 t->num_frames = 0;
477 t->curr_frame = -1;
478 t->addr_mode = AddrModeFlat;
480 snprintf(t->name, sizeof(t->name), "%04x", tid);
482 list_add_head(&p->threads, &t->entry);
484 return t;
487 void dbg_del_thread(struct dbg_thread* t)
489 HeapFree(GetProcessHeap(), 0, t->frames);
490 list_remove(&t->entry);
491 if (t == dbg_curr_thread) dbg_curr_thread = NULL;
492 HeapFree(GetProcessHeap(), 0, t);
495 void dbg_set_option(const char* option, const char* val)
497 if (!strcasecmp(option, "module_load_mismatched"))
499 DWORD opt = SymGetOptions();
500 if (!val)
501 dbg_printf("Option: module_load_mismatched %s\n", opt & SYMOPT_LOAD_ANYTHING ? "true" : "false");
502 else if (!strcasecmp(val, "true")) opt |= SYMOPT_LOAD_ANYTHING;
503 else if (!strcasecmp(val, "false")) opt &= ~SYMOPT_LOAD_ANYTHING;
504 else
506 dbg_printf("Syntax: module_load_mismatched [true|false]\n");
507 return;
509 SymSetOptions(opt);
511 else if (!strcasecmp(option, "symbol_picker"))
513 if (!val)
514 dbg_printf("Option: symbol_picker %s\n",
515 symbol_current_picker == symbol_picker_interactive ? "interactive" : "scoped");
516 else if (!strcasecmp(val, "interactive"))
517 symbol_current_picker = symbol_picker_interactive;
518 else if (!strcasecmp(val, "scoped"))
519 symbol_current_picker = symbol_picker_scoped;
520 else
522 dbg_printf("Syntax: symbol_picker [interactive|scoped]\n");
523 return;
526 else dbg_printf("Unknown option '%s'\n", option);
529 BOOL dbg_interrupt_debuggee(void)
531 struct dbg_process* p;
532 if (list_empty(&dbg_process_list)) return FALSE;
533 /* FIXME: since we likely have a single process, signal the first process
534 * in list
536 p = LIST_ENTRY(list_head(&dbg_process_list), struct dbg_process, entry);
537 if (list_next(&dbg_process_list, &p->entry)) dbg_printf("Ctrl-C: only stopping the first process\n");
538 else dbg_printf("Ctrl-C: stopping debuggee\n");
539 p->continue_on_first_exception = FALSE;
540 return DebugBreakProcess(p->handle);
543 static BOOL WINAPI ctrl_c_handler(DWORD dwCtrlType)
545 if (dwCtrlType == CTRL_C_EVENT)
547 return dbg_interrupt_debuggee();
549 return FALSE;
552 void dbg_init_console(void)
554 /* set the output handle */
555 dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
557 /* set our control-C handler */
558 SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
560 /* set our own title */
561 SetConsoleTitleA("Wine Debugger");
564 static int dbg_winedbg_usage(BOOL advanced)
566 if (advanced)
568 dbg_printf("Usage:\n"
569 " winedbg cmdline launch process 'cmdline' (as if you were starting\n"
570 " it with wine) and run WineDbg on it\n"
571 " winedbg <num> attach to running process of pid <num> and run\n"
572 " WineDbg on it\n"
573 " winedbg --gdb cmdline launch process 'cmdline' (as if you were starting\n"
574 " wine) and run gdb (proxied) on it\n"
575 " winedbg --gdb <num> attach to running process of pid <num> and run\n"
576 " gdb (proxied) on it\n"
577 " winedbg file.mdmp reload the minidump file.mdmp into memory and run\n"
578 " WineDbg on it\n"
579 " winedbg --help prints advanced options\n");
581 else
582 dbg_printf("Usage:\n\twinedbg [ [ --gdb ] [ prog-name [ prog-args ] | <num> | file.mdmp | --help ]\n");
583 return 0;
586 void dbg_start_interactive(HANDLE hFile)
588 struct dbg_process* p;
589 struct dbg_process* p2;
591 if (dbg_curr_process)
593 dbg_printf("WineDbg starting on pid %04lx\n", dbg_curr_pid);
594 if (dbg_curr_process->active_debuggee) dbg_active_wait_for_first_exception();
597 dbg_interactiveP = TRUE;
598 parser_handle(hFile);
600 LIST_FOR_EACH_ENTRY_SAFE(p, p2, &dbg_process_list, struct dbg_process, entry)
601 p->process_io->close_process(p, FALSE);
603 dbg_save_internal_vars();
606 struct backend_cpu* be_cpu;
607 #ifdef __i386__
608 extern struct backend_cpu be_i386;
609 #elif defined(__powerpc__)
610 extern struct backend_cpu be_ppc;
611 #elif defined(__ALPHA__)
612 extern struct backend_cpu be_alpha;
613 #elif defined(__x86_64__)
614 extern struct backend_cpu be_x86_64;
615 #elif defined(__sparc__)
616 extern struct backend_cpu be_sparc;
617 #else
618 # error CPU unknown
619 #endif
621 int main(int argc, char** argv)
623 int retv = 0;
624 HANDLE hFile = INVALID_HANDLE_VALUE;
625 enum dbg_start ds;
627 #ifdef __i386__
628 be_cpu = &be_i386;
629 #elif defined(__powerpc__)
630 be_cpu = &be_ppc;
631 #elif defined(__ALPHA__)
632 be_cpu = &be_alpha;
633 #elif defined(__x86_64__)
634 be_cpu = &be_x86_64;
635 #elif defined(__sparc__)
636 be_cpu = &be_sparc;
637 #else
638 # error CPU unknown
639 #endif
640 /* Initialize the output */
641 dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
643 /* Initialize internal vars */
644 if (!dbg_load_internal_vars()) return -1;
646 /* as we don't care about exec name */
647 argc--; argv++;
649 if (argc && !strcmp(argv[0], "--help"))
650 return dbg_winedbg_usage(TRUE);
652 if (argc && !strcmp(argv[0], "--gdb"))
654 retv = gdb_main(argc, argv);
655 if (retv == -1) dbg_winedbg_usage(FALSE);
656 return retv;
658 dbg_init_console();
660 SymSetOptions((SymGetOptions() & ~(SYMOPT_UNDNAME)) |
661 SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_AUTO_PUBLICS);
663 if (argc && (!strcmp(argv[0], "--auto") || !strcmp(argv[0], "--minidump")))
665 /* force some internal variables */
666 DBG_IVAR(BreakOnDllLoad) = 0;
667 dbg_houtput = GetStdHandle(STD_ERROR_HANDLE);
668 switch (dbg_active_auto(argc, argv))
670 case start_ok: return 0;
671 case start_error_parse: return dbg_winedbg_usage(FALSE);
672 case start_error_init: return -1;
675 /* parse options */
676 while (argc > 0 && argv[0][0] == '-')
678 if (!strcmp(argv[0], "--command"))
680 argc--; argv++;
681 hFile = parser_generate_command_file(argv[0], NULL);
682 if (hFile == INVALID_HANDLE_VALUE)
684 dbg_printf("Couldn't open temp file (%u)\n", GetLastError());
685 return 1;
687 argc--; argv++;
688 continue;
690 if (!strcmp(argv[0], "--file"))
692 argc--; argv++;
693 hFile = CreateFileA(argv[0], GENERIC_READ|DELETE, 0,
694 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
695 if (hFile == INVALID_HANDLE_VALUE)
697 dbg_printf("Couldn't open file %s (%u)\n", argv[0], GetLastError());
698 return 1;
700 argc--; argv++;
701 continue;
703 if (!strcmp(argv[0], "--"))
705 argc--; argv++;
706 break;
708 return dbg_winedbg_usage(FALSE);
710 if (!argc) ds = start_ok;
711 else if ((ds = dbg_active_attach(argc, argv)) == start_error_parse &&
712 (ds = minidump_reload(argc, argv)) == start_error_parse)
713 ds = dbg_active_launch(argc, argv);
714 switch (ds)
716 case start_ok: break;
717 case start_error_parse: return dbg_winedbg_usage(FALSE);
718 case start_error_init: return -1;
721 dbg_start_interactive(hFile);
723 return 0;