kernelbase: Reimplement Internal_EnumCalendarInfo() using the locale.nls data.
[wine.git] / programs / winedbg / winedbg.c
blobd11b68ec432e047f323df5d06bdfdaa76c43123e
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 <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include "debugger.h"
25 #include "winternl.h"
26 #include "wine/debug.h"
28 /* TODO list:
30 * - minidump
31 * + ensure that all commands work as expected in minidump reload function
32 * (and re-enable parser usage)
33 * - CPU adherence
34 * + we always assume the stack grows as on i386 (i.e. downwards)
35 * - UI
36 * + re-enable the limited output (depth of structure printing and number of
37 * lines)
38 * + make the output as close as possible to what gdb does
39 * - symbol management:
40 * + symbol table loading is broken
41 * + in symbol_get_lvalue, we don't do any scoping (as C does) between local and
42 * global vars (we may need this to force some display for example). A solution
43 * would be always to return arrays with: local vars, global vars, thunks
44 * - type management:
45 * + some bits of internal types are missing (like type casts and the address
46 * operator)
47 * + all computations should be made on 64bit
48 * o bitfield spreading on more bytes than dbg_lgint_t isn't supported
49 * (can happen on 128bit integers, of an ELF build...)
50 * - execution:
51 * + set a better fix for gdb (proxy mode) than the step-mode hack
52 * + implement function call in debuggee
53 * + trampoline management is broken when getting 16 <=> 32 thunk destination
54 * address
55 * + thunking of delayed imports doesn't work as expected (ie, when stepping,
56 * it currently stops at first insn with line number during the library
57 * loading). We should identify this (__wine_delay_import) and set a
58 * breakpoint instead of single stepping the library loading.
59 * + it's wrong to copy thread->step_over_bp into process->bp[0] (when
60 * we have a multi-thread debuggee). complete fix must include storing all
61 * thread's step-over bp in process-wide bp array, and not to handle bp
62 * when we have the wrong thread running into that bp
63 * + code in CREATE_PROCESS debug event doesn't work on Windows, as we cannot
64 * get the name of the main module this way. We should rewrite all this code
65 * and store in struct dbg_process as early as possible (before process
66 * creation or attachment), the name of the main module
67 * - global:
68 * + define a better way to enable the wine extensions (either DBG SDK function
69 * in dbghelp, or TLS variable, or environment variable or ...)
70 * + audit all files to ensure that we check all potential return values from
71 * every function call to catch the errors
72 * + BTW check also whether the exception mechanism is the best way to return
73 * errors (or find a proper fix for MinGW port)
76 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
78 struct dbg_process* dbg_curr_process = NULL;
79 struct dbg_thread* dbg_curr_thread = NULL;
80 DWORD dbg_curr_tid = 0;
81 DWORD dbg_curr_pid = 0;
82 dbg_ctx_t dbg_context;
83 BOOL dbg_interactiveP = FALSE;
84 HANDLE dbg_houtput = 0;
86 static struct list dbg_process_list = LIST_INIT(dbg_process_list);
88 struct dbg_internal_var dbg_internal_vars[DBG_IV_LAST];
90 static void dbg_outputA(const char* buffer, int len)
92 static char line_buff[4096];
93 static unsigned int line_pos;
95 DWORD w, i;
97 while (len > 0)
99 unsigned int count = min( len, sizeof(line_buff) - line_pos );
100 memcpy( line_buff + line_pos, buffer, count );
101 buffer += count;
102 len -= count;
103 line_pos += count;
104 for (i = line_pos; i > 0; i--) if (line_buff[i-1] == '\n') break;
105 if (!i) /* no newline found */
107 if (len > 0) i = line_pos; /* buffer is full, flush anyway */
108 else break;
110 WriteFile(dbg_houtput, line_buff, i, &w, NULL);
111 memmove( line_buff, line_buff + i, line_pos - i );
112 line_pos -= i;
116 int WINAPIV dbg_printf(const char* format, ...)
118 static char buf[4*1024];
119 va_list valist;
120 int len;
122 va_start(valist, format);
123 len = vsnprintf(buf, sizeof(buf), format, valist);
124 va_end(valist);
126 if (len <= -1 || len >= sizeof(buf))
128 len = sizeof(buf) - 1;
129 buf[len] = 0;
130 buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
132 dbg_outputA(buf, len);
133 return len;
136 static unsigned dbg_load_internal_vars(void)
138 HKEY hkey;
139 DWORD type = REG_DWORD;
140 DWORD val;
141 DWORD count = sizeof(val);
142 int i;
143 struct dbg_internal_var* div = dbg_internal_vars;
145 /* initializes internal vars table */
146 #define INTERNAL_VAR(_var,_val,_ref,_tid) \
147 div->val = _val; div->name = #_var; div->pval = _ref; \
148 div->typeid = _tid; div++;
149 #include "intvar.h"
150 #undef INTERNAL_VAR
152 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
153 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
155 WINE_ERR("Cannot create WineDbg key in registry\n");
156 return FALSE;
159 for (i = 0; i < DBG_IV_LAST; i++)
161 if (!dbg_internal_vars[i].pval)
163 if (!RegQueryValueExA(hkey, dbg_internal_vars[i].name, 0,
164 &type, (LPBYTE)&val, &count))
165 dbg_internal_vars[i].val = val;
166 dbg_internal_vars[i].pval = &dbg_internal_vars[i].val;
169 RegCloseKey(hkey);
171 return TRUE;
174 static unsigned dbg_save_internal_vars(void)
176 HKEY hkey;
177 int i;
179 /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
180 if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey))
182 WINE_ERR("Cannot create WineDbg key in registry\n");
183 return FALSE;
186 for (i = 0; i < DBG_IV_LAST; i++)
188 /* FIXME: type should be inferred from basic type -if any- of intvar */
189 if (dbg_internal_vars[i].pval == &dbg_internal_vars[i].val)
191 DWORD val = dbg_internal_vars[i].val;
192 RegSetValueExA(hkey, dbg_internal_vars[i].name, 0, REG_DWORD, (BYTE *)&val, sizeof(val));
195 RegCloseKey(hkey);
196 return TRUE;
199 const struct dbg_internal_var* dbg_get_internal_var(const char* name)
201 const struct dbg_internal_var* div;
203 for (div = &dbg_internal_vars[DBG_IV_LAST - 1]; div >= dbg_internal_vars; div--)
205 if (!strcmp(div->name, name)) return div;
207 for (div = dbg_curr_process->be_cpu->context_vars; div->name; div++)
209 if (!strcasecmp(div->name, name))
211 struct dbg_internal_var* ret = (void*)lexeme_alloc_size(sizeof(*ret));
212 /* relocate register's field against current context */
213 *ret = *div;
214 ret->pval = (char*)&dbg_context + (DWORD_PTR)div->pval;
215 return ret;
219 return NULL;
222 unsigned dbg_num_processes(void)
224 return list_count(&dbg_process_list);
227 struct dbg_process* dbg_get_process(DWORD pid)
229 struct dbg_process* p;
231 LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
232 if (p->pid == pid) return p;
233 return NULL;
236 struct dbg_process* dbg_get_process_h(HANDLE h)
238 struct dbg_process* p;
240 LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
241 if (p->handle == h) return p;
242 return NULL;
245 #ifdef __i386__
246 extern struct backend_cpu be_i386;
247 #elif defined(__x86_64__)
248 extern struct backend_cpu be_i386;
249 extern struct backend_cpu be_x86_64;
250 #elif defined(__arm__) && !defined(__ARMEB__)
251 extern struct backend_cpu be_arm;
252 #elif defined(__aarch64__) && !defined(__AARCH64EB__)
253 extern struct backend_cpu be_arm64;
254 #else
255 # error CPU unknown
256 #endif
258 struct dbg_process* dbg_add_process(const struct be_process_io* pio, DWORD pid, HANDLE h)
260 struct dbg_process* p;
261 BOOL wow64;
263 if ((p = dbg_get_process(pid)))
264 return p;
266 if (!h)
267 h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
269 if (!(p = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_process)))) return NULL;
270 p->handle = h;
271 p->pid = pid;
272 p->process_io = pio;
273 p->pio_data = NULL;
274 p->imageName = NULL;
275 list_init(&p->threads);
276 p->event_on_first_exception = NULL;
277 p->active_debuggee = FALSE;
278 p->next_bp = 1; /* breakpoint 0 is reserved for step-over */
279 memset(p->bp, 0, sizeof(p->bp));
280 p->delayed_bp = NULL;
281 p->num_delayed_bp = 0;
282 p->source_ofiles = NULL;
283 p->search_path = NULL;
284 p->source_current_file[0] = '\0';
285 p->source_start_line = -1;
286 p->source_end_line = -1;
288 list_add_head(&dbg_process_list, &p->entry);
290 IsWow64Process(h, &wow64);
292 #ifdef __i386__
293 p->be_cpu = &be_i386;
294 #elif defined(__x86_64__)
295 p->be_cpu = wow64 ? &be_i386 : &be_x86_64;
296 #elif defined(__arm__) && !defined(__ARMEB__)
297 p->be_cpu = &be_arm;
298 #elif defined(__aarch64__) && !defined(__AARCH64EB__)
299 p->be_cpu = &be_arm64;
300 #else
301 # error CPU unknown
302 #endif
303 return p;
306 void dbg_set_process_name(struct dbg_process* p, const WCHAR* imageName)
308 assert(p->imageName == NULL);
309 if (imageName)
311 WCHAR* tmp = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(imageName) + 1) * sizeof(WCHAR));
312 if (tmp) p->imageName = lstrcpyW(tmp, imageName);
316 void dbg_del_process(struct dbg_process* p)
318 struct dbg_thread* t;
319 struct dbg_thread* t2;
320 int i;
322 LIST_FOR_EACH_ENTRY_SAFE(t, t2, &p->threads, struct dbg_thread, entry)
323 dbg_del_thread(t);
325 for (i = 0; i < p->num_delayed_bp; i++)
326 if (p->delayed_bp[i].is_symbol)
327 HeapFree(GetProcessHeap(), 0, p->delayed_bp[i].u.symbol.name);
329 HeapFree(GetProcessHeap(), 0, p->delayed_bp);
330 source_nuke_path(p);
331 source_free_files(p);
332 list_remove(&p->entry);
333 if (p == dbg_curr_process) dbg_curr_process = NULL;
334 if (p->event_on_first_exception) CloseHandle(p->event_on_first_exception);
335 HeapFree(GetProcessHeap(), 0, (char*)p->imageName);
336 HeapFree(GetProcessHeap(), 0, p);
339 /******************************************************************
340 * dbg_init
342 * Initializes the dbghelp library, and also sets the application directory
343 * as a place holder for symbol searches.
345 BOOL dbg_init(HANDLE hProc, const WCHAR* in, BOOL invade)
347 BOOL ret;
349 ret = SymInitialize(hProc, NULL, invade);
350 if (ret && in)
352 const WCHAR* last;
354 for (last = in + lstrlenW(in) - 1; last >= in; last--)
356 if (*last == '/' || *last == '\\')
358 WCHAR* tmp;
359 tmp = HeapAlloc(GetProcessHeap(), 0, (1024 + 1 + (last - in) + 1) * sizeof(WCHAR));
360 if (tmp && SymGetSearchPathW(hProc, tmp, 1024))
362 WCHAR* x = tmp + lstrlenW(tmp);
364 *x++ = ';';
365 memcpy(x, in, (last - in) * sizeof(WCHAR));
366 x[last - in] = '\0';
367 ret = SymSetSearchPathW(hProc, tmp);
369 else ret = FALSE;
370 HeapFree(GetProcessHeap(), 0, tmp);
371 break;
375 return ret;
378 BOOL dbg_load_module(HANDLE hProc, HANDLE hFile, const WCHAR* name, DWORD_PTR base, DWORD size)
380 BOOL ret = SymLoadModuleExW(hProc, NULL, name, NULL, base, size, NULL, 0);
381 if (ret)
383 IMAGEHLP_MODULEW64 ihm;
384 ihm.SizeOfStruct = sizeof(ihm);
385 if (SymGetModuleInfoW64(hProc, base, &ihm) && (ihm.PdbUnmatched || ihm.DbgUnmatched))
386 dbg_printf("Loaded unmatched debug information for %s\n", wine_dbgstr_w(name));
388 return ret;
391 struct dbg_thread* dbg_get_thread(struct dbg_process* p, DWORD tid)
393 struct dbg_thread* t;
395 if (!p) return NULL;
396 LIST_FOR_EACH_ENTRY(t, &p->threads, struct dbg_thread, entry)
397 if (t->tid == tid) return t;
398 return NULL;
401 struct dbg_thread* dbg_add_thread(struct dbg_process* p, DWORD tid,
402 HANDLE h, void* teb)
404 struct dbg_thread* t = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_thread));
406 if (!t)
407 return NULL;
409 t->handle = h;
410 t->tid = tid;
411 t->teb = teb;
412 t->process = p;
413 t->exec_mode = dbg_exec_cont;
414 t->exec_count = 0;
415 t->step_over_bp.enabled = FALSE;
416 t->step_over_bp.refcount = 0;
417 t->stopped_xpoint = -1;
418 t->name[0] = '\0';
419 t->in_exception = FALSE;
420 t->frames = NULL;
421 t->num_frames = 0;
422 t->curr_frame = -1;
423 t->addr_mode = AddrModeFlat;
424 t->suspended = FALSE;
426 list_add_head(&p->threads, &t->entry);
428 return t;
431 void dbg_del_thread(struct dbg_thread* t)
433 HeapFree(GetProcessHeap(), 0, t->frames);
434 list_remove(&t->entry);
435 if (t == dbg_curr_thread) dbg_curr_thread = NULL;
436 HeapFree(GetProcessHeap(), 0, t);
439 void dbg_set_option(const char* option, const char* val)
441 if (!strcasecmp(option, "module_load_mismatched"))
443 DWORD opt = SymGetOptions();
444 if (!val)
445 dbg_printf("Option: module_load_mismatched %s\n", opt & SYMOPT_LOAD_ANYTHING ? "true" : "false");
446 else if (!strcasecmp(val, "true")) opt |= SYMOPT_LOAD_ANYTHING;
447 else if (!strcasecmp(val, "false")) opt &= ~SYMOPT_LOAD_ANYTHING;
448 else
450 dbg_printf("Syntax: module_load_mismatched [true|false]\n");
451 return;
453 SymSetOptions(opt);
455 else if (!strcasecmp(option, "symbol_picker"))
457 if (!val)
458 dbg_printf("Option: symbol_picker %s\n",
459 symbol_current_picker == symbol_picker_interactive ? "interactive" : "scoped");
460 else if (!strcasecmp(val, "interactive"))
461 symbol_current_picker = symbol_picker_interactive;
462 else if (!strcasecmp(val, "scoped"))
463 symbol_current_picker = symbol_picker_scoped;
464 else
466 dbg_printf("Syntax: symbol_picker [interactive|scoped]\n");
467 return;
470 else dbg_printf("Unknown option '%s'\n", option);
473 BOOL dbg_interrupt_debuggee(void)
475 struct dbg_process* p;
476 if (list_empty(&dbg_process_list)) return FALSE;
477 /* FIXME: since we likely have a single process, signal the first process
478 * in list
480 p = LIST_ENTRY(list_head(&dbg_process_list), struct dbg_process, entry);
481 if (list_next(&dbg_process_list, &p->entry)) dbg_printf("Ctrl-C: only stopping the first process\n");
482 else dbg_printf("Ctrl-C: stopping debuggee\n");
483 if (p->event_on_first_exception)
485 SetEvent(p->event_on_first_exception);
486 CloseHandle(p->event_on_first_exception);
487 p->event_on_first_exception = NULL;
489 return DebugBreakProcess(p->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 void dbg_init_console(void)
503 /* set the output handle */
504 dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
506 /* set our control-C handler */
507 SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
509 /* set our own title */
510 SetConsoleTitleA("Wine Debugger");
513 static int dbg_winedbg_usage(BOOL advanced)
515 if (advanced)
517 dbg_printf("Usage:\n"
518 " winedbg <cmdline> launch process <cmdline> (as if you were starting\n"
519 " it with wine) and run WineDbg on it\n"
520 " winedbg <num> attach to running process of wpid <num> and run\n"
521 " WineDbg on it\n"
522 " winedbg --gdb <cmdline> launch process <cmdline> (as if you were starting\n"
523 " wine) and run gdb (proxied) on it\n"
524 " winedbg --gdb <num> attach to running process of wpid <num> and run\n"
525 " gdb (proxied) on it\n"
526 " winedbg <file.mdmp> reload the minidump <file.mdmp> into memory and run\n"
527 " WineDbg on it\n"
528 " winedbg --help prints advanced options\n");
530 else
531 dbg_printf("Usage:\n\twinedbg [ [ --gdb ] [ <prog-name> [ <prog-args> ] | <num> | <file.mdmp> | --help ]\n");
532 return 0;
535 void dbg_start_interactive(const char* filename, HANDLE hFile)
537 struct dbg_process* p;
538 struct dbg_process* p2;
540 if (dbg_curr_process)
542 dbg_printf("WineDbg starting on pid %04lx\n", dbg_curr_pid);
543 if (dbg_curr_process->active_debuggee) dbg_active_wait_for_first_exception();
546 dbg_interactiveP = TRUE;
547 parser_handle(filename, hFile);
549 LIST_FOR_EACH_ENTRY_SAFE(p, p2, &dbg_process_list, struct dbg_process, entry)
550 p->process_io->close_process(p, FALSE);
552 dbg_save_internal_vars();
555 static LONG CALLBACK top_filter( EXCEPTION_POINTERS *ptr )
557 dbg_printf( "winedbg: Internal crash at %p\n", ptr->ExceptionRecord->ExceptionAddress );
558 return EXCEPTION_EXECUTE_HANDLER;
561 static void restart_if_wow64(void)
563 BOOL is_wow64;
565 if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
567 STARTUPINFOW si;
568 PROCESS_INFORMATION pi;
569 WCHAR filename[MAX_PATH];
570 void *redir;
571 DWORD exit_code;
573 memset( &si, 0, sizeof(si) );
574 si.cb = sizeof(si);
575 GetSystemDirectoryW( filename, MAX_PATH );
576 lstrcatW( filename, L"\\winedbg.exe" );
578 Wow64DisableWow64FsRedirection( &redir );
579 if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
581 WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
582 SetConsoleCtrlHandler( NULL, TRUE ); /* Ignore ^C */
583 WaitForSingleObject( pi.hProcess, INFINITE );
584 GetExitCodeProcess( pi.hProcess, &exit_code );
585 ExitProcess( exit_code );
587 else WINE_ERR( "failed to restart 64-bit %s, err %ld\n", wine_dbgstr_w(filename), GetLastError() );
588 Wow64RevertWow64FsRedirection( redir );
592 int main(int argc, char** argv)
594 int retv = 0;
595 HANDLE hFile = INVALID_HANDLE_VALUE;
596 enum dbg_start ds;
597 const char* filename = NULL;
599 /* Initialize the output */
600 dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
602 SetUnhandledExceptionFilter( top_filter );
604 /* Initialize internal vars */
605 if (!dbg_load_internal_vars()) return -1;
607 /* as we don't care about exec name */
608 argc--; argv++;
610 if (argc && !strcmp(argv[0], "--help"))
611 return dbg_winedbg_usage(TRUE);
613 if (argc && !strcmp(argv[0], "--gdb"))
615 restart_if_wow64();
616 retv = gdb_main(argc, argv);
617 if (retv == -1) dbg_winedbg_usage(FALSE);
618 return retv;
620 dbg_init_console();
622 SymSetOptions((SymGetOptions() & ~(SYMOPT_UNDNAME)) |
623 SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_AUTO_PUBLICS |
624 SYMOPT_INCLUDE_32BIT_MODULES);
626 if (argc && !strcmp(argv[0], "--auto"))
628 switch (dbg_active_auto(argc, argv))
630 case start_ok: return 0;
631 case start_error_parse: return dbg_winedbg_usage(FALSE);
632 case start_error_init: return -1;
635 if (argc && !strcmp(argv[0], "--minidump"))
637 switch (dbg_active_minidump(argc, argv))
639 case start_ok: return 0;
640 case start_error_parse: return dbg_winedbg_usage(FALSE);
641 case start_error_init: return -1;
644 /* parse options */
645 while (argc > 0 && argv[0][0] == '-')
647 if (!strcmp(argv[0], "--command") && argc > 1)
649 argc--; argv++;
650 hFile = parser_generate_command_file(argv[0], NULL);
651 if (hFile == INVALID_HANDLE_VALUE)
653 dbg_printf("Couldn't open temp file (%lu)\n", GetLastError());
654 return 1;
656 argc--; argv++;
657 continue;
659 if (!strcmp(argv[0], "--file") && argc > 1)
661 argc--; argv++;
662 filename = argv[0];
663 hFile = CreateFileA(argv[0], GENERIC_READ|DELETE, 0,
664 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
665 if (hFile == INVALID_HANDLE_VALUE)
667 dbg_printf("Couldn't open file %s (%lu)\n", argv[0], GetLastError());
668 return 1;
670 argc--; argv++;
671 continue;
673 if (!strcmp(argv[0], "--"))
675 argc--; argv++;
676 break;
678 return dbg_winedbg_usage(FALSE);
680 if (!argc) ds = start_ok;
681 else if ((ds = dbg_active_attach(argc, argv)) == start_error_parse &&
682 (ds = minidump_reload(argc, argv)) == start_error_parse)
683 ds = dbg_active_launch(argc, argv);
684 switch (ds)
686 case start_ok: break;
687 case start_error_parse: return dbg_winedbg_usage(FALSE);
688 case start_error_init: return -1;
691 restart_if_wow64();
693 dbg_start_interactive(filename, hFile);
695 return 0;