Release 4.20.
[wine.git] / programs / winedbg / tgt_active.c
blob71e0bc1944da2a0532a4fa485130d3885e79efb7
1 /*
2 * Wine debugger - back-end for an active target
4 * Copyright 2000-2006 Eric Pouech
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdarg.h>
28 #include "debugger.h"
29 #include "psapi.h"
30 #include "resource.h"
31 #include "winternl.h"
32 #include "wine/debug.h"
33 #include "wine/exception.h"
34 #include "wine/unicode.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
38 static char* dbg_last_cmd_line;
39 static struct be_process_io be_process_active_io;
41 static void dbg_init_current_process(void)
45 static void dbg_init_current_thread(void* start)
47 if (start)
49 if (list_count(&dbg_curr_process->threads) == 1 /* first thread ? */ &&
50 DBG_IVAR(BreakAllThreadsStartup))
52 ADDRESS64 addr;
54 break_set_xpoints(FALSE);
55 addr.Mode = AddrModeFlat;
56 addr.Offset = (DWORD_PTR)start;
57 break_add_break(&addr, TRUE, TRUE);
58 break_set_xpoints(TRUE);
63 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de);
65 /******************************************************************
66 * dbg_attach_debuggee
68 * Sets the debuggee to <pid>
69 * cofe instructs winedbg what to do when first exception is received
70 * (break=FALSE, continue=TRUE)
71 * wfe is set to TRUE if dbg_attach_debuggee should also proceed with all debug events
72 * until the first exception is received (aka: attach to an already running process)
74 BOOL dbg_attach_debuggee(DWORD pid)
76 if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, pid, 0))) return FALSE;
78 if (!DebugActiveProcess(pid))
80 dbg_printf("Can't attach process %04x: error %u\n", pid, GetLastError());
81 dbg_del_process(dbg_curr_process);
82 return FALSE;
85 SetEnvironmentVariableA("DBGHELP_NOLIVE", NULL);
87 dbg_curr_process->active_debuggee = TRUE;
88 return TRUE;
91 static unsigned dbg_fetch_context(void)
93 if (!dbg_curr_process->be_cpu->get_context(dbg_curr_thread->handle, &dbg_context))
95 WINE_WARN("Can't get thread's context\n");
96 return FALSE;
98 return TRUE;
101 /***********************************************************************
102 * dbg_exception_prolog
104 * Examine exception and decide if interactive mode is entered(return TRUE)
105 * or exception is silently continued(return FALSE)
106 * is_debug means the exception is a breakpoint or single step exception
108 static BOOL dbg_exception_prolog(BOOL is_debug, const EXCEPTION_RECORD* rec)
110 ADDRESS64 addr;
111 BOOL is_break;
113 memory_get_current_pc(&addr);
114 break_suspend_execution();
116 /* this will resynchronize builtin dbghelp's internal ELF module list */
117 SymLoadModule(dbg_curr_process->handle, 0, 0, 0, 0, 0);
119 if (is_debug) break_adjust_pc(&addr, rec->ExceptionCode, dbg_curr_thread->first_chance, &is_break);
121 * Do a quiet backtrace so that we have an idea of what the situation
122 * is WRT the source files.
124 stack_fetch_frames(&dbg_context);
126 if (is_debug && !is_break && break_should_continue(&addr, rec->ExceptionCode))
127 return FALSE;
129 if (addr.Mode != dbg_curr_thread->addr_mode)
131 const char* name = NULL;
133 switch (addr.Mode)
135 case AddrMode1616: name = "16 bit"; break;
136 case AddrMode1632: name = "segmented 32 bit"; break;
137 case AddrModeReal: name = "vm86"; break;
138 case AddrModeFlat: name = dbg_curr_process->be_cpu->pointer_size == 4
139 ? "32 bit" : "64 bit"; break;
141 dbg_printf("In %s mode.\n", name);
142 dbg_curr_thread->addr_mode = addr.Mode;
144 display_print();
146 if (!is_debug)
148 /* This is a real crash, dump some info */
149 dbg_curr_process->be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
150 stack_info(-1);
151 dbg_curr_process->be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
152 stack_backtrace(dbg_curr_tid);
154 else
156 static char* last_name;
157 static char* last_file;
159 char buffer[sizeof(SYMBOL_INFO) + 256];
160 SYMBOL_INFO* si = (SYMBOL_INFO*)buffer;
161 void* lin = memory_to_linear_addr(&addr);
162 DWORD64 disp64;
163 IMAGEHLP_LINE64 il;
164 DWORD disp;
166 si->SizeOfStruct = sizeof(*si);
167 si->MaxNameLen = 256;
168 il.SizeOfStruct = sizeof(il);
169 if (SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si) &&
170 SymGetLineFromAddr64(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
172 if ((!last_name || strcmp(last_name, si->Name)) ||
173 (!last_file || strcmp(last_file, il.FileName)))
175 HeapFree(GetProcessHeap(), 0, last_name);
176 HeapFree(GetProcessHeap(), 0, last_file);
177 last_name = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(si->Name) + 1), si->Name);
178 last_file = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(il.FileName) + 1), il.FileName);
179 dbg_printf("%s () at %s:%u\n", last_name, last_file, il.LineNumber);
183 if (!is_debug || is_break ||
184 dbg_curr_thread->exec_mode == dbg_exec_step_over_insn ||
185 dbg_curr_thread->exec_mode == dbg_exec_step_into_insn)
187 ADDRESS64 tmp = addr;
188 /* Show where we crashed */
189 memory_disasm_one_insn(&tmp);
191 source_list_from_addr(&addr, 0);
193 return TRUE;
196 static void dbg_exception_epilog(void)
198 break_restart_execution(dbg_curr_thread->exec_count);
200 * This will have gotten absorbed into the breakpoint info
201 * if it was used. Otherwise it would have been ignored.
202 * In any case, we don't mess with it any more.
204 if (dbg_curr_thread->exec_mode == dbg_exec_cont)
205 dbg_curr_thread->exec_count = 0;
206 dbg_curr_thread->in_exception = FALSE;
209 static DWORD dbg_handle_exception(const EXCEPTION_RECORD* rec, BOOL first_chance)
211 BOOL is_debug = FALSE;
212 const THREADNAME_INFO* pThreadName;
213 struct dbg_thread* pThread;
215 assert(dbg_curr_thread);
217 WINE_TRACE("exception=%x first_chance=%c\n",
218 rec->ExceptionCode, first_chance ? 'Y' : 'N');
220 switch (rec->ExceptionCode)
222 case EXCEPTION_BREAKPOINT:
223 case EXCEPTION_SINGLE_STEP:
224 is_debug = TRUE;
225 break;
226 case EXCEPTION_NAME_THREAD:
227 pThreadName = (const THREADNAME_INFO*)(rec->ExceptionInformation);
228 if (pThreadName->dwThreadID == -1)
229 pThread = dbg_curr_thread;
230 else
231 pThread = dbg_get_thread(dbg_curr_process, pThreadName->dwThreadID);
232 if(!pThread)
234 dbg_printf("Thread ID=%04x not in our list of threads -> can't rename\n", pThreadName->dwThreadID);
235 return DBG_CONTINUE;
237 if (dbg_read_memory(pThreadName->szName, pThread->name, 9))
238 dbg_printf("Thread ID=%04x renamed using MS VC6 extension (name==\"%.9s\")\n",
239 pThread->tid, pThread->name);
240 return DBG_CONTINUE;
241 case EXCEPTION_INVALID_HANDLE:
242 return DBG_CONTINUE;
245 if (first_chance && !is_debug && !DBG_IVAR(BreakOnFirstChance) &&
246 !(rec->ExceptionFlags & EH_STACK_INVALID))
248 /* pass exception to program except for debug exceptions */
249 return DBG_EXCEPTION_NOT_HANDLED;
252 dbg_curr_thread->excpt_record = *rec;
253 dbg_curr_thread->in_exception = TRUE;
254 dbg_curr_thread->first_chance = first_chance;
256 if (!is_debug) info_win32_exception();
258 if (rec->ExceptionCode == STATUS_POSSIBLE_DEADLOCK && !DBG_IVAR(BreakOnCritSectTimeOut))
260 dbg_curr_thread->in_exception = FALSE;
261 return DBG_EXCEPTION_NOT_HANDLED;
264 if (dbg_exception_prolog(is_debug, rec))
266 dbg_interactiveP = TRUE;
267 return 0;
269 dbg_exception_epilog();
271 return DBG_CONTINUE;
274 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill);
276 static void fetch_module_name(void* name_addr, BOOL unicode, void* mod_addr,
277 WCHAR* buffer, size_t bufsz, BOOL is_pcs)
279 static const WCHAR pcspid[] = {'P','r','o','c','e','s','s','_','%','0','8','x',0};
280 static const WCHAR dlladdr[] = {'D','L','L','_','%','0','8','l','x',0};
282 memory_get_string_indirect(dbg_curr_process, name_addr, unicode, buffer, bufsz);
283 if (!buffer[0] &&
284 !GetModuleFileNameExW(dbg_curr_process->handle, mod_addr, buffer, bufsz))
286 if (is_pcs)
288 HMODULE h;
289 WORD (WINAPI *gpif)(HANDLE, LPWSTR, DWORD);
291 /* On Windows, when we get the process creation debug event for a process
292 * created by winedbg, the modules' list is not initialized yet. Hence,
293 * GetModuleFileNameExA (on the main module) will generate an error.
294 * Psapi (starting on XP) provides GetProcessImageFileName() which should
295 * give us the expected result
297 if (!(h = GetModuleHandleA("psapi")) ||
298 !(gpif = (void*)GetProcAddress(h, "GetProcessImageFileNameW")) ||
299 !(gpif)(dbg_curr_process->handle, buffer, bufsz))
300 snprintfW(buffer, bufsz, pcspid, dbg_curr_pid);
302 else
303 snprintfW(buffer, bufsz, dlladdr, (ULONG_PTR)mod_addr);
307 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de)
309 union {
310 char bufferA[256];
311 WCHAR buffer[256];
312 } u;
313 DWORD cont = DBG_CONTINUE;
315 dbg_curr_pid = de->dwProcessId;
316 dbg_curr_tid = de->dwThreadId;
318 if ((dbg_curr_process = dbg_get_process(de->dwProcessId)) != NULL)
319 dbg_curr_thread = dbg_get_thread(dbg_curr_process, de->dwThreadId);
320 else
321 dbg_curr_thread = NULL;
323 switch (de->dwDebugEventCode)
325 case EXCEPTION_DEBUG_EVENT:
326 if (!dbg_curr_thread)
328 WINE_ERR("%04x:%04x: not a registered process or thread (perhaps a 16 bit one ?)\n",
329 de->dwProcessId, de->dwThreadId);
330 break;
333 WINE_TRACE("%04x:%04x: exception code=%08x\n",
334 de->dwProcessId, de->dwThreadId,
335 de->u.Exception.ExceptionRecord.ExceptionCode);
337 if (dbg_curr_process->event_on_first_exception)
339 SetEvent(dbg_curr_process->event_on_first_exception);
340 CloseHandle(dbg_curr_process->event_on_first_exception);
341 dbg_curr_process->event_on_first_exception = NULL;
342 if (!DBG_IVAR(BreakOnAttach)) break;
344 if (dbg_fetch_context())
346 cont = dbg_handle_exception(&de->u.Exception.ExceptionRecord,
347 de->u.Exception.dwFirstChance);
348 if (cont && dbg_curr_thread)
350 dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
353 break;
355 case CREATE_PROCESS_DEBUG_EVENT:
356 dbg_curr_process = dbg_add_process(&be_process_active_io, de->dwProcessId,
357 de->u.CreateProcessInfo.hProcess);
358 if (dbg_curr_process == NULL)
360 WINE_ERR("Couldn't create process\n");
361 break;
363 fetch_module_name(de->u.CreateProcessInfo.lpImageName,
364 de->u.CreateProcessInfo.fUnicode,
365 de->u.CreateProcessInfo.lpBaseOfImage,
366 u.buffer, ARRAY_SIZE(u.buffer), TRUE);
368 WINE_TRACE("%04x:%04x: create process '%s'/%p @%p (%u<%u>)\n",
369 de->dwProcessId, de->dwThreadId,
370 wine_dbgstr_w(u.buffer),
371 de->u.CreateProcessInfo.lpImageName,
372 de->u.CreateProcessInfo.lpStartAddress,
373 de->u.CreateProcessInfo.dwDebugInfoFileOffset,
374 de->u.CreateProcessInfo.nDebugInfoSize);
375 dbg_set_process_name(dbg_curr_process, u.buffer);
377 if (!dbg_init(dbg_curr_process->handle, u.buffer, FALSE))
378 dbg_printf("Couldn't initiate DbgHelp\n");
379 if (!dbg_load_module(dbg_curr_process->handle, de->u.CreateProcessInfo.hFile, u.buffer,
380 (DWORD_PTR)de->u.CreateProcessInfo.lpBaseOfImage, 0))
381 dbg_printf("couldn't load main module (%u)\n", GetLastError());
383 WINE_TRACE("%04x:%04x: create thread I @%p\n",
384 de->dwProcessId, de->dwThreadId, de->u.CreateProcessInfo.lpStartAddress);
386 dbg_curr_thread = dbg_add_thread(dbg_curr_process,
387 de->dwThreadId,
388 de->u.CreateProcessInfo.hThread,
389 de->u.CreateProcessInfo.lpThreadLocalBase);
390 if (!dbg_curr_thread)
392 WINE_ERR("Couldn't create thread\n");
393 break;
395 dbg_init_current_process();
396 dbg_init_current_thread(de->u.CreateProcessInfo.lpStartAddress);
397 break;
399 case EXIT_PROCESS_DEBUG_EVENT:
400 WINE_TRACE("%04x:%04x: exit process (%d)\n",
401 de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
403 if (dbg_curr_process == NULL)
405 WINE_ERR("Unknown process\n");
406 break;
408 tgt_process_active_close_process(dbg_curr_process, FALSE);
409 dbg_printf("Process of pid=%04x has terminated\n", de->dwProcessId);
410 break;
412 case CREATE_THREAD_DEBUG_EVENT:
413 WINE_TRACE("%04x:%04x: create thread D @%p\n",
414 de->dwProcessId, de->dwThreadId, de->u.CreateThread.lpStartAddress);
416 if (dbg_curr_process == NULL)
418 WINE_ERR("Unknown process\n");
419 break;
421 if (dbg_get_thread(dbg_curr_process, de->dwThreadId) != NULL)
423 WINE_TRACE("Thread already listed, skipping\n");
424 break;
427 dbg_curr_thread = dbg_add_thread(dbg_curr_process,
428 de->dwThreadId,
429 de->u.CreateThread.hThread,
430 de->u.CreateThread.lpThreadLocalBase);
431 if (!dbg_curr_thread)
433 WINE_ERR("Couldn't create thread\n");
434 break;
436 dbg_init_current_thread(de->u.CreateThread.lpStartAddress);
437 break;
439 case EXIT_THREAD_DEBUG_EVENT:
440 WINE_TRACE("%04x:%04x: exit thread (%d)\n",
441 de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
443 if (dbg_curr_thread == NULL)
445 WINE_ERR("Unknown thread\n");
446 break;
448 /* FIXME: remove break point set on thread startup */
449 dbg_del_thread(dbg_curr_thread);
450 break;
452 case LOAD_DLL_DEBUG_EVENT:
453 if (dbg_curr_thread == NULL)
455 WINE_ERR("Unknown thread\n");
456 break;
458 fetch_module_name(de->u.LoadDll.lpImageName,
459 de->u.LoadDll.fUnicode,
460 de->u.LoadDll.lpBaseOfDll,
461 u.buffer, ARRAY_SIZE(u.buffer), FALSE);
463 WINE_TRACE("%04x:%04x: loads DLL %s @%p (%u<%u>)\n",
464 de->dwProcessId, de->dwThreadId,
465 wine_dbgstr_w(u.buffer), de->u.LoadDll.lpBaseOfDll,
466 de->u.LoadDll.dwDebugInfoFileOffset,
467 de->u.LoadDll.nDebugInfoSize);
468 dbg_load_module(dbg_curr_process->handle, de->u.LoadDll.hFile, u.buffer,
469 (DWORD_PTR)de->u.LoadDll.lpBaseOfDll, 0);
470 break_set_xpoints(FALSE);
471 break_check_delayed_bp();
472 break_set_xpoints(TRUE);
473 if (DBG_IVAR(BreakOnDllLoad))
475 dbg_printf("Stopping on DLL %s loading at %p\n",
476 dbg_W2A(u.buffer, -1), de->u.LoadDll.lpBaseOfDll);
477 if (dbg_fetch_context()) cont = 0;
479 break;
481 case UNLOAD_DLL_DEBUG_EVENT:
482 WINE_TRACE("%04x:%04x: unload DLL @%p\n",
483 de->dwProcessId, de->dwThreadId,
484 de->u.UnloadDll.lpBaseOfDll);
485 break_delete_xpoints_from_module((DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
486 SymUnloadModule64(dbg_curr_process->handle, (DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
487 break;
489 case OUTPUT_DEBUG_STRING_EVENT:
490 if (dbg_curr_thread == NULL)
492 WINE_ERR("Unknown thread\n");
493 break;
496 memory_get_string(dbg_curr_process,
497 de->u.DebugString.lpDebugStringData, TRUE,
498 de->u.DebugString.fUnicode, u.bufferA, sizeof(u.bufferA));
499 WINE_TRACE("%04x:%04x: output debug string (%s)\n",
500 de->dwProcessId, de->dwThreadId, u.bufferA);
501 break;
503 case RIP_EVENT:
504 WINE_TRACE("%04x:%04x: rip error=%u type=%u\n",
505 de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
506 de->u.RipInfo.dwType);
507 break;
509 default:
510 WINE_TRACE("%04x:%04x: unknown event (%x)\n",
511 de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
513 if (!cont) return TRUE; /* stop execution */
514 ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
515 return FALSE; /* continue execution */
518 static void dbg_resume_debuggee(DWORD cont)
520 if (dbg_curr_thread->in_exception)
522 ADDRESS64 addr;
523 char hexbuf[MAX_OFFSET_TO_STR_LEN];
525 dbg_exception_epilog();
526 memory_get_current_pc(&addr);
527 WINE_TRACE("Exiting debugger PC=%s mode=%d count=%d\n",
528 memory_offset_to_string(hexbuf, addr.Offset, 0),
529 dbg_curr_thread->exec_mode,
530 dbg_curr_thread->exec_count);
531 if (dbg_curr_thread)
533 if (!dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context))
534 dbg_printf("Cannot set ctx on %04lx\n", dbg_curr_tid);
537 dbg_interactiveP = FALSE;
538 if (!ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, cont))
539 dbg_printf("Cannot continue on %04lx (%08x)\n", dbg_curr_tid, cont);
542 static void wait_exception(void)
544 DEBUG_EVENT de;
546 while (dbg_num_processes() && WaitForDebugEvent(&de, INFINITE))
548 if (dbg_handle_debug_event(&de)) break;
550 dbg_interactiveP = TRUE;
553 void dbg_wait_next_exception(DWORD cont, int count, int mode)
555 ADDRESS64 addr;
556 char hexbuf[MAX_OFFSET_TO_STR_LEN];
558 if (cont == DBG_CONTINUE)
560 dbg_curr_thread->exec_count = count;
561 dbg_curr_thread->exec_mode = mode;
563 dbg_resume_debuggee(cont);
565 wait_exception();
566 if (!dbg_curr_process) return;
568 memory_get_current_pc(&addr);
569 WINE_TRACE("Entering debugger PC=%s mode=%d count=%d\n",
570 memory_offset_to_string(hexbuf, addr.Offset, 0),
571 dbg_curr_thread->exec_mode,
572 dbg_curr_thread->exec_count);
575 void dbg_active_wait_for_first_exception(void)
577 dbg_interactiveP = FALSE;
578 /* wait for first exception */
579 wait_exception();
582 static BOOL dbg_start_debuggee(LPSTR cmdLine)
584 PROCESS_INFORMATION info;
585 STARTUPINFOA startup, current;
586 DWORD flags;
588 GetStartupInfoA(&current);
590 memset(&startup, 0, sizeof(startup));
591 startup.cb = sizeof(startup);
592 startup.dwFlags = STARTF_USESHOWWINDOW;
594 startup.wShowWindow = (current.dwFlags & STARTF_USESHOWWINDOW) ?
595 current.wShowWindow : SW_SHOWNORMAL;
597 /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUIs need it
598 * while GUIs don't
600 flags = DEBUG_PROCESS | CREATE_NEW_CONSOLE;
601 if (!DBG_IVAR(AlsoDebugProcChild)) flags |= DEBUG_ONLY_THIS_PROCESS;
603 if (!CreateProcessA(NULL, cmdLine, NULL, NULL, FALSE, flags,
604 NULL, NULL, &startup, &info))
606 dbg_printf("Couldn't start process '%s'\n", cmdLine);
607 return FALSE;
609 if (!info.dwProcessId)
611 /* this happens when the program being run is not a Wine binary
612 * (for example, a shell wrapper around a WineLib app)
614 /* Current fix: list running processes and let the user attach
615 * to one of them (sic)
616 * FIXME: implement a real fix => grab the process (from the
617 * running processes) from its name
619 dbg_printf("Debuggee has been started (%s)\n"
620 "But WineDbg isn't attached to it. Maybe you're trying to debug a winelib wrapper ??\n"
621 "Try to attach to one of those processes:\n", cmdLine);
622 /* FIXME: (HACK) we need some time before the wrapper executes the winelib app */
623 Sleep(100);
624 info_win32_processes();
625 return TRUE;
627 dbg_curr_pid = info.dwProcessId;
628 if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, dbg_curr_pid, 0))) return FALSE;
629 dbg_curr_process->active_debuggee = TRUE;
631 return TRUE;
634 void dbg_run_debuggee(const char* args)
636 if (args)
638 WINE_FIXME("Re-running current program with %s as args is broken\n", wine_dbgstr_a(args));
639 return;
641 else
643 if (!dbg_last_cmd_line)
645 dbg_printf("Cannot find previously used command line.\n");
646 return;
648 dbg_start_debuggee(dbg_last_cmd_line);
649 dbg_active_wait_for_first_exception();
650 source_list_from_addr(NULL, 0);
654 static BOOL str2int(const char* str, DWORD_PTR* val)
656 char* ptr;
658 *val = strtol(str, &ptr, 10);
659 return str < ptr && !*ptr;
662 static HANDLE create_temp_file(void)
664 static const WCHAR prefixW[] = {'w','d','b',0};
665 WCHAR path[MAX_PATH], name[MAX_PATH];
667 if (!GetTempPathW( MAX_PATH, path ) || !GetTempFileNameW( path, prefixW, 0, name ))
668 return INVALID_HANDLE_VALUE;
669 return CreateFileW( name, GENERIC_READ|GENERIC_WRITE|DELETE, FILE_SHARE_DELETE,
670 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, 0 );
673 static const struct
675 int type;
676 int platform;
677 int major;
678 int minor;
679 const char *str;
681 version_table[] =
683 { 0, VER_PLATFORM_WIN32s, 2, 0, "2.0" },
684 { 0, VER_PLATFORM_WIN32s, 3, 0, "3.0" },
685 { 0, VER_PLATFORM_WIN32s, 3, 10, "3.1" },
686 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 0, "95" },
687 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 10, "98" },
688 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 90, "ME" },
689 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 3, 51, "NT 3.51" },
690 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 4, 0, "NT 4.0" },
691 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 0, "2000" },
692 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 1, "XP" },
693 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 2, "XP" },
694 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 5, 2, "Server 2003" },
695 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 0, "Vista" },
696 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 0, "Server 2008" },
697 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 1, "7" },
698 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 1, "Server 2008 R2" },
699 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 2, "8" },
700 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 2, "Server 2012" },
701 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 3, "8.1" },
702 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 3, "Server 2012 R2" },
703 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 10, 0, "10" },
706 static const char *get_windows_version(void)
708 OSVERSIONINFOEXW info = { sizeof(OSVERSIONINFOEXW) };
709 static char str[64];
710 int i;
712 GetVersionExW( (OSVERSIONINFOW *)&info );
714 for (i = 0; i < ARRAY_SIZE(version_table); i++)
716 if (version_table[i].type == info.wProductType &&
717 version_table[i].platform == info.dwPlatformId &&
718 version_table[i].major == info.dwMajorVersion &&
719 version_table[i].minor == info.dwMinorVersion)
721 return version_table[i].str;
725 snprintf( str, sizeof(str), "%d.%d (%d)", info.dwMajorVersion,
726 info.dwMinorVersion, info.wProductType );
727 return str;
730 static void output_system_info(void)
732 #ifdef __i386__
733 static const char platform[] = "i386";
734 #elif defined(__x86_64__)
735 static const char platform[] = "x86_64";
736 #elif defined(__powerpc__)
737 static const char platform[] = "powerpc";
738 #elif defined(__arm__)
739 static const char platform[] = "arm";
740 #elif defined(__aarch64__)
741 static const char platform[] = "arm64";
742 #else
743 # error CPU unknown
744 #endif
746 const char *(CDECL *wine_get_build_id)(void);
747 void (CDECL *wine_get_host_version)( const char **sysname, const char **release );
748 BOOL is_wow64;
750 wine_get_build_id = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_build_id");
751 wine_get_host_version = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_host_version");
752 if (!IsWow64Process( dbg_curr_process->handle, &is_wow64 )) is_wow64 = FALSE;
754 dbg_printf( "System information:\n" );
755 if (wine_get_build_id) dbg_printf( " Wine build: %s\n", wine_get_build_id() );
756 dbg_printf( " Platform: %s%s\n", platform, is_wow64 ? " (WOW64)" : "" );
757 dbg_printf( " Version: Windows %s\n", get_windows_version() );
758 if (wine_get_host_version)
760 const char *sysname, *release;
761 wine_get_host_version( &sysname, &release );
762 dbg_printf( " Host system: %s\n", sysname );
763 dbg_printf( " Host version: %s\n", release );
767 /******************************************************************
768 * dbg_active_attach
770 * Tries to attach to a running process
771 * Handles the <pid> or <pid> <evt> forms
773 enum dbg_start dbg_active_attach(int argc, char* argv[])
775 DWORD_PTR pid, evt;
777 /* try the form <myself> pid */
778 if (argc == 1 && str2int(argv[0], &pid) && pid != 0)
780 if (!dbg_attach_debuggee(pid))
781 return start_error_init;
783 /* try the form <myself> pid evt (Win32 JIT debugger) */
784 else if (argc == 2 && str2int(argv[0], &pid) && pid != 0 &&
785 str2int(argv[1], &evt) && evt != 0)
787 if (!dbg_attach_debuggee(pid))
789 /* don't care about result */
790 SetEvent((HANDLE)evt);
791 return start_error_init;
793 dbg_curr_process->event_on_first_exception = (HANDLE)evt;
795 else return start_error_parse;
797 dbg_curr_pid = pid;
798 return start_ok;
801 /******************************************************************
802 * dbg_active_launch
804 * Launches a debuggee (with its arguments) from argc/argv
806 enum dbg_start dbg_active_launch(int argc, char* argv[])
808 int i, len;
809 LPSTR cmd_line;
811 if (argc == 0) return start_error_parse;
813 if (!(cmd_line = HeapAlloc(GetProcessHeap(), 0, len = 1)))
815 oom_leave:
816 dbg_printf("Out of memory\n");
817 return start_error_init;
819 cmd_line[0] = '\0';
821 for (i = 0; i < argc; i++)
823 len += strlen(argv[i]) + 1;
824 if (!(cmd_line = HeapReAlloc(GetProcessHeap(), 0, cmd_line, len)))
825 goto oom_leave;
826 strcat(cmd_line, argv[i]);
827 cmd_line[len - 2] = ' ';
828 cmd_line[len - 1] = '\0';
831 if (!dbg_start_debuggee(cmd_line))
833 HeapFree(GetProcessHeap(), 0, cmd_line);
834 return start_error_init;
836 HeapFree(GetProcessHeap(), 0, dbg_last_cmd_line);
837 dbg_last_cmd_line = cmd_line;
838 return start_ok;
841 /******************************************************************
842 * dbg_active_auto
844 * Starts (<pid> or <pid> <evt>) in automatic mode
846 enum dbg_start dbg_active_auto(int argc, char* argv[])
848 HANDLE thread = 0, event = 0, input, output = INVALID_HANDLE_VALUE;
849 enum dbg_start ds = start_error_parse;
851 DBG_IVAR(BreakOnDllLoad) = 0;
853 /* auto mode */
854 argc--; argv++;
855 ds = dbg_active_attach(argc, argv);
856 if (ds != start_ok) {
857 msgbox_res_id(NULL, IDS_INVALID_PARAMS, IDS_AUTO_CAPTION, MB_OK);
858 return ds;
861 switch (display_crash_dialog())
863 case ID_DEBUG:
864 AllocConsole();
865 dbg_init_console();
866 dbg_start_interactive(INVALID_HANDLE_VALUE);
867 return start_ok;
868 case ID_DETAILS:
869 event = CreateEventW( NULL, TRUE, FALSE, NULL );
870 if (event) thread = display_crash_details( event );
871 if (thread) dbg_houtput = output = create_temp_file();
872 break;
875 input = parser_generate_command_file("echo Modules:", "info share",
876 "echo Threads:", "info threads", NULL);
877 if (input == INVALID_HANDLE_VALUE) return start_error_parse;
879 if (dbg_curr_process->active_debuggee)
880 dbg_active_wait_for_first_exception();
882 dbg_interactiveP = TRUE;
883 parser_handle(input);
884 output_system_info();
886 if (output != INVALID_HANDLE_VALUE)
888 SetEvent( event );
889 WaitForSingleObject( thread, INFINITE );
890 CloseHandle( output );
891 CloseHandle( thread );
892 CloseHandle( event );
895 CloseHandle( input );
896 dbg_curr_process->process_io->close_process(dbg_curr_process, TRUE);
897 return start_ok;
900 /******************************************************************
901 * dbg_active_minidump
903 * Starts (<pid> or <pid> <evt>) in minidump mode
905 enum dbg_start dbg_active_minidump(int argc, char* argv[])
907 HANDLE hFile;
908 enum dbg_start ds = start_error_parse;
909 const char* file = NULL;
910 char tmp[8 + 1 + 2 + MAX_PATH]; /* minidump "<file>" */
912 dbg_houtput = GetStdHandle(STD_ERROR_HANDLE);
913 DBG_IVAR(BreakOnDllLoad) = 0;
915 argc--; argv++;
916 /* hard stuff now ; we can get things like:
917 * --minidump <pid> 1 arg
918 * --minidump <pid> <evt> 2 args
919 * --minidump <file> <pid> 2 args
920 * --minidump <file> <pid> <evt> 3 args
922 switch (argc)
924 case 1:
925 ds = dbg_active_attach(argc, argv);
926 break;
927 case 2:
928 if ((ds = dbg_active_attach(argc, argv)) != start_ok)
930 file = argv[0];
931 ds = dbg_active_attach(argc - 1, argv + 1);
933 break;
934 case 3:
935 file = argv[0];
936 ds = dbg_active_attach(argc - 1, argv + 1);
937 break;
938 default:
939 return start_error_parse;
941 if (ds != start_ok) return ds;
942 memcpy(tmp, "minidump \"", 10);
943 if (!file)
945 char path[MAX_PATH];
947 GetTempPathA(sizeof(path), path);
948 GetTempFileNameA(path, "WD", 0, tmp + 10);
950 else strcpy(tmp + 10, file);
951 strcat(tmp, "\"");
952 if (!file)
954 /* FIXME: should generate unix name as well */
955 dbg_printf("Capturing program state in %s\n", tmp + 9);
957 hFile = parser_generate_command_file(tmp, "detach", NULL);
958 if (hFile == INVALID_HANDLE_VALUE) return start_error_parse;
960 if (dbg_curr_process->active_debuggee)
961 dbg_active_wait_for_first_exception();
963 dbg_interactiveP = TRUE;
964 parser_handle(hFile);
966 return start_ok;
969 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill)
971 if (kill)
973 DWORD exit_code = 0;
975 if (pcs == dbg_curr_process && dbg_curr_thread->in_exception)
976 exit_code = dbg_curr_thread->excpt_record.ExceptionCode;
978 TerminateProcess(pcs->handle, exit_code);
980 else if (pcs == dbg_curr_process)
982 /* remove all set breakpoints in debuggee code */
983 break_set_xpoints(FALSE);
984 /* needed for single stepping (ugly).
985 * should this be handled inside the server ???
987 dbg_curr_process->be_cpu->single_step(&dbg_context, FALSE);
988 if (dbg_curr_thread->in_exception)
990 dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
991 ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, DBG_CONTINUE);
995 if (!kill)
997 if (!DebugActiveProcessStop(pcs->pid)) return FALSE;
999 SymCleanup(pcs->handle);
1000 dbg_del_process(pcs);
1002 return TRUE;
1005 static BOOL tgt_process_active_read(HANDLE hProcess, const void* addr,
1006 void* buffer, SIZE_T len, SIZE_T* rlen)
1008 return ReadProcessMemory( hProcess, addr, buffer, len, rlen );
1011 static BOOL tgt_process_active_write(HANDLE hProcess, void* addr,
1012 const void* buffer, SIZE_T len, SIZE_T* wlen)
1014 return WriteProcessMemory( hProcess, addr, buffer, len, wlen );
1017 static BOOL tgt_process_active_get_selector(HANDLE hThread, DWORD sel, LDT_ENTRY* le)
1019 return GetThreadSelectorEntry( hThread, sel, le );
1022 static struct be_process_io be_process_active_io =
1024 tgt_process_active_close_process,
1025 tgt_process_active_read,
1026 tgt_process_active_write,
1027 tgt_process_active_get_selector