d3dx10/tests: Fix texture leak in check_resource_data.
[wine.git] / programs / winedbg / tgt_active.c
blob9e11de69bc92de7643598cc0f22405505ff51d13
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 <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdarg.h>
26 #include "debugger.h"
27 #include "psapi.h"
28 #include "resource.h"
29 #include "winternl.h"
30 #include "wine/debug.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
34 static char* dbg_executable;
35 static char* dbg_last_cmd_line;
36 static struct be_process_io be_process_active_io;
38 static void dbg_init_current_process(void)
42 static void dbg_init_current_thread(void* start)
44 if (start)
46 if (list_count(&dbg_curr_process->threads) == 1 /* first thread ? */ &&
47 DBG_IVAR(BreakAllThreadsStartup))
49 ADDRESS64 addr;
51 break_set_xpoints(FALSE);
52 addr.Mode = AddrModeFlat;
53 addr.Offset = (DWORD_PTR)start;
54 break_add_break(&addr, TRUE, TRUE);
55 break_set_xpoints(TRUE);
60 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de);
62 /******************************************************************
63 * dbg_attach_debuggee
65 * Sets the debuggee to <pid>
66 * cofe instructs winedbg what to do when first exception is received
67 * (break=FALSE, continue=TRUE)
68 * wfe is set to TRUE if dbg_attach_debuggee should also proceed with all debug events
69 * until the first exception is received (aka: attach to an already running process)
71 BOOL dbg_attach_debuggee(DWORD pid)
73 if (pid == GetCurrentProcessId())
75 dbg_printf("WineDbg can't debug its own process. Please use another process ID.\n");
76 return FALSE;
78 if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, pid, 0))) return FALSE;
80 if (!DebugActiveProcess(pid))
82 dbg_printf("Can't attach process %04lx: error %lu\n", pid, GetLastError());
83 dbg_del_process(dbg_curr_process);
84 return FALSE;
87 SetEnvironmentVariableA("DBGHELP_NOLIVE", NULL);
89 dbg_curr_process->active_debuggee = TRUE;
90 return TRUE;
93 static unsigned dbg_fetch_context(void)
95 if (!dbg_curr_process->be_cpu->get_context(dbg_curr_thread->handle, &dbg_context))
97 WINE_WARN("Can't get thread's context\n");
98 return FALSE;
100 return TRUE;
103 BOOL dbg_set_curr_thread(DWORD tid)
105 struct dbg_thread* thread;
107 if (!dbg_curr_process)
109 dbg_printf("No process loaded\n");
110 return FALSE;
113 thread = dbg_get_thread(dbg_curr_process, tid);
114 if (thread)
116 dbg_curr_thread = thread;
117 dbg_fetch_context();
118 stack_fetch_frames(&dbg_context);
119 dbg_curr_tid = tid;
120 return TRUE;
122 dbg_printf("No such thread\n");
123 return thread != NULL;
126 /***********************************************************************
127 * dbg_exception_prolog
129 * Examine exception and decide if interactive mode is entered(return TRUE)
130 * or exception is silently continued(return FALSE)
131 * is_debug means the exception is a breakpoint or single step exception
133 static BOOL dbg_exception_prolog(BOOL is_debug, const EXCEPTION_RECORD* rec)
135 ADDRESS64 addr;
136 BOOL is_break;
138 memory_get_current_pc(&addr);
139 break_suspend_execution();
141 /* this will resynchronize builtin dbghelp's internal ELF module list */
142 SymLoadModule(dbg_curr_process->handle, 0, 0, 0, 0, 0);
144 if (is_debug) break_adjust_pc(&addr, rec->ExceptionCode, dbg_curr_thread->first_chance, &is_break);
146 * Do a quiet backtrace so that we have an idea of what the situation
147 * is WRT the source files.
149 stack_fetch_frames(&dbg_context);
151 if (is_debug && !is_break && break_should_continue(&addr, rec->ExceptionCode))
152 return FALSE;
154 if (addr.Mode != dbg_curr_thread->addr_mode)
156 const char* name = NULL;
158 switch (addr.Mode)
160 case AddrMode1616: name = "16 bit"; break;
161 case AddrMode1632: name = "segmented 32 bit"; break;
162 case AddrModeReal: name = "vm86"; break;
163 case AddrModeFlat: name = dbg_curr_process->be_cpu->pointer_size == 4
164 ? "32 bit" : "64 bit"; break;
166 dbg_printf("In %s mode.\n", name);
167 dbg_curr_thread->addr_mode = addr.Mode;
169 display_print();
171 if (!is_debug)
173 /* This is a real crash, dump some info */
174 dbg_curr_process->be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
175 stack_info(-1);
176 dbg_curr_process->be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
177 stack_backtrace(dbg_curr_tid);
179 else
181 static char* last_name;
182 static char* last_file;
184 char buffer[sizeof(SYMBOL_INFO) + 256];
185 SYMBOL_INFO* si = (SYMBOL_INFO*)buffer;
186 void* lin = memory_to_linear_addr(&addr);
187 DWORD64 disp64;
188 IMAGEHLP_LINE64 il;
189 DWORD disp;
191 si->SizeOfStruct = sizeof(*si);
192 si->MaxNameLen = 256;
193 il.SizeOfStruct = sizeof(il);
194 if (SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si) &&
195 SymGetLineFromAddr64(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
197 if ((!last_name || strcmp(last_name, si->Name)) ||
198 (!last_file || strcmp(last_file, il.FileName)))
200 HeapFree(GetProcessHeap(), 0, last_name);
201 HeapFree(GetProcessHeap(), 0, last_file);
202 last_name = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(si->Name) + 1), si->Name);
203 last_file = strcpy(HeapAlloc(GetProcessHeap(), 0, strlen(il.FileName) + 1), il.FileName);
204 dbg_printf("%s () at %s:%lu\n", last_name, last_file, il.LineNumber);
208 if (!is_debug || is_break ||
209 dbg_curr_thread->exec_mode == dbg_exec_step_over_insn ||
210 dbg_curr_thread->exec_mode == dbg_exec_step_into_insn)
212 ADDRESS64 tmp = addr;
213 /* Show where we crashed */
214 memory_disasm_one_insn(&tmp);
216 source_list_from_addr(&addr, 0);
218 return TRUE;
221 static void dbg_exception_epilog(void)
223 break_restart_execution(dbg_curr_thread->exec_count);
225 * This will have gotten absorbed into the breakpoint info
226 * if it was used. Otherwise it would have been ignored.
227 * In any case, we don't mess with it any more.
229 if (dbg_curr_thread->exec_mode == dbg_exec_cont)
230 dbg_curr_thread->exec_count = 0;
231 dbg_curr_thread->in_exception = FALSE;
234 static DWORD dbg_handle_exception(const EXCEPTION_RECORD* rec, BOOL first_chance)
236 BOOL is_debug = FALSE;
237 const THREADNAME_INFO* pThreadName;
238 struct dbg_thread* pThread;
240 assert(dbg_curr_thread);
242 WINE_TRACE("exception=%lx first_chance=%c\n",
243 rec->ExceptionCode, first_chance ? 'Y' : 'N');
245 switch (rec->ExceptionCode)
247 case EXCEPTION_BREAKPOINT:
248 case EXCEPTION_SINGLE_STEP:
249 is_debug = TRUE;
250 break;
251 case EXCEPTION_WINE_NAME_THREAD:
252 pThreadName = (const THREADNAME_INFO*)(rec->ExceptionInformation);
254 if (pThreadName->dwType != 0x1000)
255 return DBG_EXCEPTION_NOT_HANDLED;
256 if (pThreadName->dwThreadID == -1)
257 pThread = dbg_curr_thread;
258 else
259 pThread = dbg_get_thread(dbg_curr_process, pThreadName->dwThreadID);
260 if(!pThread)
262 dbg_printf("Thread ID=%04lx not in our list of threads -> can't rename\n", pThreadName->dwThreadID);
263 return DBG_CONTINUE;
265 if (dbg_read_memory(pThreadName->szName, pThread->name, sizeof(pThread->name)))
267 pThread->name[sizeof(pThread->name) - 1] = '\0';
268 dbg_printf("Thread ID=%04lx renamed using MSVC extension (name==\"%s\")\n",
269 pThread->tid, pThread->name);
271 return DBG_CONTINUE;
272 case EXCEPTION_INVALID_HANDLE:
273 return DBG_CONTINUE;
276 if (first_chance && !is_debug && !DBG_IVAR(BreakOnFirstChance) &&
277 !(rec->ExceptionFlags & EH_STACK_INVALID))
279 /* pass exception to program except for debug exceptions */
280 return DBG_EXCEPTION_NOT_HANDLED;
283 dbg_curr_thread->excpt_record = *rec;
284 dbg_curr_thread->in_exception = TRUE;
285 dbg_curr_thread->first_chance = first_chance;
287 if (!is_debug) info_win32_exception();
289 if (rec->ExceptionCode == STATUS_POSSIBLE_DEADLOCK && !DBG_IVAR(BreakOnCritSectTimeOut))
291 dbg_curr_thread->in_exception = FALSE;
292 return DBG_EXCEPTION_NOT_HANDLED;
295 if (dbg_exception_prolog(is_debug, rec))
297 dbg_interactiveP = TRUE;
298 return 0;
300 dbg_exception_epilog();
302 return DBG_CONTINUE;
305 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill);
307 void fetch_module_name(void* name_addr, void* mod_addr, WCHAR* buffer, size_t bufsz)
309 memory_get_string_indirect(dbg_curr_process, name_addr, TRUE, buffer, bufsz);
310 if (!buffer[0] && !GetModuleFileNameExW(dbg_curr_process->handle, mod_addr, buffer, bufsz))
312 if (GetMappedFileNameW( dbg_curr_process->handle, mod_addr, buffer, bufsz ))
314 /* FIXME: proper NT->Dos conversion */
315 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
317 if (!wcsncmp( buffer, nt_prefixW, 4 ))
318 memmove( buffer, buffer + 4, (lstrlenW(buffer + 4) + 1) * sizeof(WCHAR) );
320 else
321 swprintf(buffer, bufsz, L"DLL_%08lx", (ULONG_PTR)mod_addr);
325 static unsigned dbg_handle_debug_event(DEBUG_EVENT* de)
327 union {
328 char bufferA[256];
329 WCHAR buffer[256];
330 } u;
331 DWORD size, cont = DBG_CONTINUE;
333 dbg_curr_pid = de->dwProcessId;
334 dbg_curr_tid = de->dwThreadId;
336 if ((dbg_curr_process = dbg_get_process(de->dwProcessId)) != NULL)
337 dbg_curr_thread = dbg_get_thread(dbg_curr_process, de->dwThreadId);
338 else
339 dbg_curr_thread = NULL;
341 switch (de->dwDebugEventCode)
343 case EXCEPTION_DEBUG_EVENT:
344 if (!dbg_curr_thread)
346 WINE_ERR("%04lx:%04lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
347 de->dwProcessId, de->dwThreadId);
348 break;
351 WINE_TRACE("%04lx:%04lx: exception code=%08lx\n",
352 de->dwProcessId, de->dwThreadId,
353 de->u.Exception.ExceptionRecord.ExceptionCode);
355 if (dbg_curr_process->event_on_first_exception)
357 SetEvent(dbg_curr_process->event_on_first_exception);
358 CloseHandle(dbg_curr_process->event_on_first_exception);
359 dbg_curr_process->event_on_first_exception = NULL;
360 if (!DBG_IVAR(BreakOnAttach)) break;
362 if (dbg_fetch_context())
364 cont = dbg_handle_exception(&de->u.Exception.ExceptionRecord,
365 de->u.Exception.dwFirstChance);
366 if (cont && dbg_curr_thread)
368 dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
371 break;
373 case CREATE_PROCESS_DEBUG_EVENT:
374 dbg_curr_process = dbg_add_process(&be_process_active_io, de->dwProcessId,
375 de->u.CreateProcessInfo.hProcess);
376 if (dbg_curr_process == NULL)
378 WINE_ERR("Couldn't create process\n");
379 break;
381 size = ARRAY_SIZE(u.buffer);
382 if (!QueryFullProcessImageNameW( dbg_curr_process->handle, 0, u.buffer, &size ))
384 swprintf(u.buffer, ARRAY_SIZE(u.buffer), L"Process_%08x", dbg_curr_pid);
387 WINE_TRACE("%04lx:%04lx: create process '%s'/%p @%p (%lu<%lu>)\n",
388 de->dwProcessId, de->dwThreadId,
389 wine_dbgstr_w(u.buffer),
390 de->u.CreateProcessInfo.lpImageName,
391 de->u.CreateProcessInfo.lpStartAddress,
392 de->u.CreateProcessInfo.dwDebugInfoFileOffset,
393 de->u.CreateProcessInfo.nDebugInfoSize);
394 dbg_set_process_name(dbg_curr_process, u.buffer);
396 if (!dbg_init(dbg_curr_process->handle, u.buffer, FALSE))
397 dbg_printf("Couldn't initiate DbgHelp\n");
398 if (!dbg_load_module(dbg_curr_process->handle, de->u.CreateProcessInfo.hFile, u.buffer,
399 (DWORD_PTR)de->u.CreateProcessInfo.lpBaseOfImage, 0))
400 dbg_printf("couldn't load main module (%lu)\n", GetLastError());
402 WINE_TRACE("%04lx:%04lx: create thread I @%p\n",
403 de->dwProcessId, de->dwThreadId, de->u.CreateProcessInfo.lpStartAddress);
405 dbg_curr_thread = dbg_add_thread(dbg_curr_process,
406 de->dwThreadId,
407 de->u.CreateProcessInfo.hThread,
408 de->u.CreateProcessInfo.lpThreadLocalBase);
409 if (!dbg_curr_thread)
411 WINE_ERR("Couldn't create thread\n");
412 break;
414 dbg_init_current_process();
415 dbg_init_current_thread(de->u.CreateProcessInfo.lpStartAddress);
416 break;
418 case EXIT_PROCESS_DEBUG_EVENT:
419 WINE_TRACE("%04lx:%04lx: exit process (%ld)\n",
420 de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
422 if (dbg_curr_process == NULL)
424 WINE_ERR("Unknown process\n");
425 break;
427 tgt_process_active_close_process(dbg_curr_process, FALSE);
428 dbg_printf("Process of pid=%04lx has terminated\n", de->dwProcessId);
429 break;
431 case CREATE_THREAD_DEBUG_EVENT:
432 WINE_TRACE("%04lx:%04lx: create thread D @%p\n",
433 de->dwProcessId, de->dwThreadId, de->u.CreateThread.lpStartAddress);
435 if (dbg_curr_process == NULL)
437 WINE_ERR("Unknown process\n");
438 break;
440 if (dbg_get_thread(dbg_curr_process, de->dwThreadId) != NULL)
442 WINE_TRACE("Thread already listed, skipping\n");
443 break;
446 dbg_curr_thread = dbg_add_thread(dbg_curr_process,
447 de->dwThreadId,
448 de->u.CreateThread.hThread,
449 de->u.CreateThread.lpThreadLocalBase);
450 if (!dbg_curr_thread)
452 WINE_ERR("Couldn't create thread\n");
453 break;
455 dbg_init_current_thread(de->u.CreateThread.lpStartAddress);
456 break;
458 case EXIT_THREAD_DEBUG_EVENT:
459 WINE_TRACE("%04lx:%04lx: exit thread (%ld)\n",
460 de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
462 if (dbg_curr_thread == NULL)
464 WINE_ERR("Unknown thread\n");
465 break;
467 /* FIXME: remove break point set on thread startup */
468 dbg_del_thread(dbg_curr_thread);
469 break;
471 case LOAD_DLL_DEBUG_EVENT:
472 if (dbg_curr_thread == NULL)
474 WINE_ERR("Unknown thread\n");
475 break;
477 fetch_module_name(de->u.LoadDll.lpImageName, de->u.LoadDll.lpBaseOfDll,
478 u.buffer, ARRAY_SIZE(u.buffer));
480 WINE_TRACE("%04lx:%04lx: loads DLL %s @%p (%lu<%lu>)\n",
481 de->dwProcessId, de->dwThreadId,
482 wine_dbgstr_w(u.buffer), de->u.LoadDll.lpBaseOfDll,
483 de->u.LoadDll.dwDebugInfoFileOffset,
484 de->u.LoadDll.nDebugInfoSize);
485 dbg_load_module(dbg_curr_process->handle, de->u.LoadDll.hFile, u.buffer,
486 (DWORD_PTR)de->u.LoadDll.lpBaseOfDll, 0);
487 break_set_xpoints(FALSE);
488 break_check_delayed_bp();
489 break_set_xpoints(TRUE);
490 if (DBG_IVAR(BreakOnDllLoad))
492 dbg_printf("Stopping on DLL %ls loading at %p\n",
493 u.buffer, de->u.LoadDll.lpBaseOfDll);
494 if (dbg_fetch_context()) cont = 0;
496 break;
498 case UNLOAD_DLL_DEBUG_EVENT:
499 WINE_TRACE("%04lx:%04lx: unload DLL @%p\n",
500 de->dwProcessId, de->dwThreadId,
501 de->u.UnloadDll.lpBaseOfDll);
502 break_delete_xpoints_from_module((DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
503 SymUnloadModule64(dbg_curr_process->handle, (DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
504 break;
506 case OUTPUT_DEBUG_STRING_EVENT:
507 if (dbg_curr_thread == NULL)
509 WINE_ERR("Unknown thread\n");
510 break;
513 memory_get_string(dbg_curr_process,
514 de->u.DebugString.lpDebugStringData, TRUE,
515 de->u.DebugString.fUnicode, u.bufferA, sizeof(u.bufferA));
516 WINE_TRACE("%04lx:%04lx: output debug string (%s)\n",
517 de->dwProcessId, de->dwThreadId, u.bufferA);
518 break;
520 case RIP_EVENT:
521 WINE_TRACE("%04lx:%04lx: rip error=%lu type=%lu\n",
522 de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
523 de->u.RipInfo.dwType);
524 break;
526 default:
527 WINE_TRACE("%04lx:%04lx: unknown event (%lx)\n",
528 de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
530 if (!cont) return TRUE; /* stop execution */
531 ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
532 return FALSE; /* continue execution */
535 static void dbg_resume_debuggee(DWORD cont)
537 if (dbg_curr_thread->in_exception)
539 ADDRESS64 addr;
540 char hexbuf[MAX_OFFSET_TO_STR_LEN];
542 dbg_exception_epilog();
543 memory_get_current_pc(&addr);
544 WINE_TRACE("Exiting debugger PC=%s mode=%d count=%d\n",
545 memory_offset_to_string(hexbuf, addr.Offset, 0),
546 dbg_curr_thread->exec_mode,
547 dbg_curr_thread->exec_count);
548 if (dbg_curr_thread)
550 if (!dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context))
551 dbg_printf("Cannot set ctx on %04lx\n", dbg_curr_tid);
554 dbg_interactiveP = FALSE;
555 if (!ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, cont))
556 dbg_printf("Cannot continue on %04lx (%08lx)\n", dbg_curr_tid, cont);
559 static void wait_exception(void)
561 DEBUG_EVENT de;
563 while (dbg_num_processes() && WaitForDebugEvent(&de, INFINITE))
565 if (dbg_handle_debug_event(&de)) break;
567 dbg_interactiveP = TRUE;
570 void dbg_wait_next_exception(DWORD cont, int count, int mode)
572 ADDRESS64 addr;
573 char hexbuf[MAX_OFFSET_TO_STR_LEN];
575 if (cont == DBG_CONTINUE)
577 dbg_curr_thread->exec_count = count;
578 dbg_curr_thread->exec_mode = mode;
580 dbg_resume_debuggee(cont);
582 wait_exception();
583 if (!dbg_curr_process) return;
585 memory_get_current_pc(&addr);
586 WINE_TRACE("Entering debugger PC=%s mode=%d count=%d\n",
587 memory_offset_to_string(hexbuf, addr.Offset, 0),
588 dbg_curr_thread->exec_mode,
589 dbg_curr_thread->exec_count);
592 void dbg_active_wait_for_first_exception(void)
594 dbg_interactiveP = FALSE;
595 /* wait for first exception */
596 wait_exception();
599 static BOOL dbg_start_debuggee(LPSTR cmdLine)
601 PROCESS_INFORMATION info;
602 STARTUPINFOA startup, current;
603 DWORD flags;
605 GetStartupInfoA(&current);
607 memset(&startup, 0, sizeof(startup));
608 startup.cb = sizeof(startup);
609 startup.dwFlags = STARTF_USESHOWWINDOW;
611 startup.wShowWindow = (current.dwFlags & STARTF_USESHOWWINDOW) ?
612 current.wShowWindow : SW_SHOWNORMAL;
614 /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUIs need it
615 * while GUIs don't
617 flags = DEBUG_PROCESS | CREATE_NEW_CONSOLE;
618 if (!DBG_IVAR(AlsoDebugProcChild)) flags |= DEBUG_ONLY_THIS_PROCESS;
620 if (!CreateProcessA(NULL, cmdLine, NULL, NULL, FALSE, flags,
621 NULL, NULL, &startup, &info))
623 dbg_printf("Couldn't start process '%s'\n", cmdLine);
624 return FALSE;
626 if (!info.dwProcessId)
628 /* this happens when the program being run is not a Wine binary
629 * (for example, a shell wrapper around a WineLib app)
631 /* Current fix: list running processes and let the user attach
632 * to one of them (sic)
633 * FIXME: implement a real fix => grab the process (from the
634 * running processes) from its name
636 dbg_printf("Debuggee has been started (%s)\n"
637 "But WineDbg isn't attached to it. Maybe you're trying to debug a winelib wrapper ??\n"
638 "Try to attach to one of those processes:\n", cmdLine);
639 /* FIXME: (HACK) we need some time before the wrapper executes the winelib app */
640 Sleep(100);
641 info_win32_processes();
642 return TRUE;
644 dbg_curr_pid = info.dwProcessId;
645 if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, dbg_curr_pid, 0))) return FALSE;
646 dbg_curr_process->active_debuggee = TRUE;
647 if (cmdLine != dbg_last_cmd_line)
649 free(dbg_last_cmd_line);
650 dbg_last_cmd_line = cmdLine;
653 return TRUE;
656 /***********************************************************************
657 * dbg_build_command_line
659 * (converted from dlls/ntdll/unix/env.c)
661 * Build the command line of a process from the argv array.
663 * We must quote and escape characters so that the argv array can be rebuilt
664 * from the command line:
665 * - spaces and tabs must be quoted
666 * 'a b' -> '"a b"'
667 * - quotes must be escaped
668 * '"' -> '\"'
669 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
670 * resulting in an odd number of '\' followed by a '"'
671 * '\"' -> '\\\"'
672 * '\\"' -> '\\\\\"'
673 * - '\'s are followed by the closing '"' must be doubled,
674 * resulting in an even number of '\' followed by a '"'
675 * ' \' -> '" \\"'
676 * ' \\' -> '" \\\\"'
677 * - '\'s that are not followed by a '"' can be left as is
678 * 'a\b' == 'a\b'
679 * 'a\\b' == 'a\\b'
681 static char *dbg_build_command_line( char **argv )
683 int len;
684 char **arg, *ret;
685 LPSTR p;
687 len = 1;
688 for (arg = argv; *arg; arg++) len += 3 + 2 * strlen( *arg );
689 if (!(ret = malloc( len ))) return NULL;
691 p = ret;
692 for (arg = argv; *arg; arg++)
694 BOOL has_space, has_quote;
695 int i, bcount;
696 char *a;
698 /* check for quotes and spaces in this argument (first arg is always quoted) */
699 has_space = (arg == argv) || !**arg || strchr( *arg, ' ' ) || strchr( *arg, '\t' );
700 has_quote = strchr( *arg, '"' ) != NULL;
702 /* now transfer it to the command line */
703 if (has_space) *p++ = '"';
704 if (has_quote || has_space)
706 bcount = 0;
707 for (a = *arg; *a; a++)
709 if (*a == '\\') bcount++;
710 else
712 if (*a == '"') /* double all the '\\' preceding this '"', plus one */
713 for (i = 0; i <= bcount; i++) *p++ = '\\';
714 bcount = 0;
716 *p++ = *a;
719 else
721 strcpy( p, *arg );
722 p += strlen( p );
724 if (has_space)
726 /* Double all the '\' preceding the closing quote */
727 for (i = 0; i < bcount; i++) *p++ = '\\';
728 *p++ = '"';
730 *p++ = ' ';
732 if (p > ret) p--; /* remove last space */
733 *p = 0;
734 return ret;
738 void dbg_run_debuggee(struct list_string* ls)
740 if (dbg_curr_process)
742 dbg_printf("Already attached to a process. Use 'detach' or 'kill' before using 'run'\n");
743 return;
745 if (!dbg_executable)
747 dbg_printf("No active target to be restarted\n");
748 return;
750 if (ls)
752 char* cl;
753 char** argv;
754 unsigned argc = 2, i;
755 struct list_string* cls;
757 for (cls = ls; cls; cls = cls->next) argc++;
758 if (!(argv = malloc(argc * sizeof(argv[0])))) return;
759 argv[0] = dbg_executable;
760 for (i = 1, cls = ls; cls; cls = cls->next, i++) argv[i] = cls->string;
761 argv[i] = NULL;
762 cl = dbg_build_command_line(argv);
763 free(argv);
765 if (!cl || !dbg_start_debuggee(cl))
767 free(cl);
768 return;
771 else
773 if (!dbg_last_cmd_line) dbg_last_cmd_line = strdup(dbg_executable);
774 dbg_start_debuggee(dbg_last_cmd_line);
776 dbg_active_wait_for_first_exception();
777 source_list_from_addr(NULL, 0);
780 static BOOL str2int(const char* str, DWORD_PTR* val)
782 char* ptr;
784 *val = strtol(str, &ptr, 0);
785 return str < ptr && !*ptr;
788 static HANDLE create_temp_file(void)
790 WCHAR path[MAX_PATH], name[MAX_PATH];
792 if (!GetTempPathW( MAX_PATH, path ) || !GetTempFileNameW( path, L"wdb", 0, name ))
793 return INVALID_HANDLE_VALUE;
794 return CreateFileW( name, GENERIC_READ|GENERIC_WRITE|DELETE, FILE_SHARE_DELETE,
795 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, 0 );
798 static const struct
800 int type;
801 int platform;
802 int major;
803 int minor;
804 const char *str;
806 version_table[] =
808 { 0, VER_PLATFORM_WIN32s, 2, 0, "2.0" },
809 { 0, VER_PLATFORM_WIN32s, 3, 0, "3.0" },
810 { 0, VER_PLATFORM_WIN32s, 3, 10, "3.1" },
811 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 0, "95" },
812 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 10, "98" },
813 { 0, VER_PLATFORM_WIN32_WINDOWS, 4, 90, "ME" },
814 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 3, 51, "NT 3.51" },
815 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 4, 0, "NT 4.0" },
816 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 0, "2000" },
817 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 1, "XP" },
818 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 5, 2, "XP" },
819 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 5, 2, "Server 2003" },
820 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 0, "Vista" },
821 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 0, "Server 2008" },
822 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 1, "7" },
823 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 1, "Server 2008 R2" },
824 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 2, "8" },
825 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 2, "Server 2012" },
826 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 6, 3, "8.1" },
827 { VER_NT_SERVER, VER_PLATFORM_WIN32_NT, 6, 3, "Server 2012 R2" },
828 { VER_NT_WORKSTATION, VER_PLATFORM_WIN32_NT, 10, 0, "10" },
831 static const char *get_windows_version(void)
833 RTL_OSVERSIONINFOEXW info = { sizeof(RTL_OSVERSIONINFOEXW) };
834 static char str[64];
835 int i;
837 RtlGetVersion( &info );
839 for (i = 0; i < ARRAY_SIZE(version_table); i++)
841 if (version_table[i].type == info.wProductType &&
842 version_table[i].platform == info.dwPlatformId &&
843 version_table[i].major == info.dwMajorVersion &&
844 version_table[i].minor == info.dwMinorVersion)
846 return version_table[i].str;
850 snprintf( str, sizeof(str), "%ld.%ld (%d)", info.dwMajorVersion,
851 info.dwMinorVersion, info.wProductType );
852 return str;
855 static void output_system_info(void)
857 #ifdef __i386__
858 static const char platform[] = "i386";
859 #elif defined(__x86_64__)
860 static const char platform[] = "x86_64";
861 #elif defined(__arm__)
862 static const char platform[] = "arm";
863 #elif defined(__aarch64__)
864 static const char platform[] = "arm64";
865 #else
866 # error CPU unknown
867 #endif
869 const char *(CDECL *wine_get_build_id)(void);
870 void (CDECL *wine_get_host_version)( const char **sysname, const char **release );
871 BOOL is_wow64;
873 wine_get_build_id = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_build_id");
874 wine_get_host_version = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_host_version");
875 if (!IsWow64Process( dbg_curr_process->handle, &is_wow64 )) is_wow64 = FALSE;
877 dbg_printf( "System information:\n" );
878 if (wine_get_build_id) dbg_printf( " Wine build: %s\n", wine_get_build_id() );
879 dbg_printf( " Platform: %s%s\n", platform, is_wow64 ? " (WOW64)" : "" );
880 dbg_printf( " Version: Windows %s\n", get_windows_version() );
881 if (wine_get_host_version)
883 const char *sysname, *release;
884 wine_get_host_version( &sysname, &release );
885 dbg_printf( " Host system: %s\n", sysname );
886 dbg_printf( " Host version: %s\n", release );
890 /******************************************************************
891 * dbg_active_attach
893 * Tries to attach to a running process
894 * Handles the <pid> or <pid> <evt> forms
896 enum dbg_start dbg_active_attach(int argc, char* argv[])
898 DWORD_PTR pid, evt;
900 /* try the form <myself> pid */
901 if (argc == 1 && str2int(argv[0], &pid) && pid != 0)
903 if (!dbg_attach_debuggee(pid))
904 return start_error_init;
906 /* try the form <myself> pid evt (Win32 JIT debugger) */
907 else if (argc == 2 && str2int(argv[0], &pid) && pid != 0 &&
908 str2int(argv[1], &evt) && evt != 0)
910 if (!dbg_attach_debuggee(pid))
912 /* don't care about result */
913 SetEvent((HANDLE)evt);
914 return start_error_init;
916 dbg_curr_process->event_on_first_exception = (HANDLE)evt;
918 else return start_error_parse;
920 dbg_curr_pid = pid;
921 return start_ok;
924 /******************************************************************
925 * dbg_active_launch
927 * Launches a debuggee (with its arguments) from argc/argv
929 enum dbg_start dbg_active_launch(int argc, char* argv[])
931 LPSTR cmd_line;
933 if (argc == 0) return start_error_parse;
935 dbg_executable = strdup(argv[0]);
936 cmd_line = dbg_build_command_line(argv);
938 if (!dbg_start_debuggee(cmd_line))
940 free(cmd_line);
941 return start_error_init;
944 return start_ok;
947 /******************************************************************
948 * dbg_active_auto
950 * Starts (<pid> or <pid> <evt>) in automatic mode
952 enum dbg_start dbg_active_auto(int argc, char* argv[])
954 HANDLE thread = 0, event = 0, input, output = INVALID_HANDLE_VALUE;
955 enum dbg_start ds = start_error_parse;
957 DBG_IVAR(BreakOnDllLoad) = 0;
959 /* auto mode */
960 argc--; argv++;
961 ds = dbg_active_attach(argc, argv);
962 if (ds != start_ok) {
963 msgbox_res_id(NULL, IDS_INVALID_PARAMS, IDS_AUTO_CAPTION, MB_OK);
964 return ds;
967 switch (display_crash_dialog())
969 case ID_DEBUG:
970 AllocConsole();
971 dbg_init_console();
972 dbg_start_interactive(NULL, INVALID_HANDLE_VALUE);
973 return start_ok;
974 case ID_DETAILS:
975 event = CreateEventW( NULL, TRUE, FALSE, NULL );
976 if (event) thread = display_crash_details( event );
977 if (thread) dbg_houtput = output = create_temp_file();
978 break;
981 input = parser_generate_command_file("echo Modules:", "info share",
982 "echo Threads:", "info threads", NULL);
983 if (input == INVALID_HANDLE_VALUE) return start_error_parse;
985 if (dbg_curr_process->active_debuggee)
986 dbg_active_wait_for_first_exception();
988 dbg_interactiveP = TRUE;
989 parser_handle(NULL, input);
990 output_system_info();
992 if (output != INVALID_HANDLE_VALUE)
994 SetEvent( event );
995 WaitForSingleObject( thread, INFINITE );
996 CloseHandle( output );
997 CloseHandle( thread );
998 CloseHandle( event );
1001 CloseHandle( input );
1002 dbg_curr_process->process_io->close_process(dbg_curr_process, TRUE);
1003 return start_ok;
1006 /******************************************************************
1007 * dbg_active_minidump
1009 * Starts (<pid> or <pid> <evt>) in minidump mode
1011 enum dbg_start dbg_active_minidump(int argc, char* argv[])
1013 HANDLE hFile;
1014 enum dbg_start ds = start_error_parse;
1015 const char* file = NULL;
1016 char tmp[8 + 1 + 2 + MAX_PATH]; /* minidump "<file>" */
1018 dbg_houtput = GetStdHandle(STD_ERROR_HANDLE);
1019 DBG_IVAR(BreakOnDllLoad) = 0;
1021 argc--; argv++;
1022 /* hard stuff now ; we can get things like:
1023 * --minidump <pid> 1 arg
1024 * --minidump <pid> <evt> 2 args
1025 * --minidump <file> <pid> 2 args
1026 * --minidump <file> <pid> <evt> 3 args
1028 switch (argc)
1030 case 1:
1031 ds = dbg_active_attach(argc, argv);
1032 break;
1033 case 2:
1034 if ((ds = dbg_active_attach(argc, argv)) != start_ok)
1036 file = argv[0];
1037 ds = dbg_active_attach(argc - 1, argv + 1);
1039 break;
1040 case 3:
1041 file = argv[0];
1042 ds = dbg_active_attach(argc - 1, argv + 1);
1043 break;
1044 default:
1045 return start_error_parse;
1047 if (ds != start_ok) return ds;
1048 memcpy(tmp, "minidump \"", 10);
1049 if (!file)
1051 char path[MAX_PATH];
1053 GetTempPathA(sizeof(path), path);
1054 GetTempFileNameA(path, "WD", 0, tmp + 10);
1056 else strcpy(tmp + 10, file);
1057 strcat(tmp, "\"");
1058 if (!file)
1060 /* FIXME: should generate unix name as well */
1061 dbg_printf("Capturing program state in %s\n", tmp + 9);
1063 hFile = parser_generate_command_file(tmp, "detach", NULL);
1064 if (hFile == INVALID_HANDLE_VALUE) return start_error_parse;
1066 if (dbg_curr_process->active_debuggee)
1067 dbg_active_wait_for_first_exception();
1069 dbg_interactiveP = TRUE;
1070 parser_handle(NULL, hFile);
1072 return start_ok;
1075 static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill)
1077 if (kill)
1079 DWORD exit_code = 0;
1081 if (pcs == dbg_curr_process && dbg_curr_thread->in_exception)
1082 exit_code = dbg_curr_thread->excpt_record.ExceptionCode;
1084 TerminateProcess(pcs->handle, exit_code);
1086 else if (pcs == dbg_curr_process)
1088 /* remove all set breakpoints in debuggee code */
1089 break_set_xpoints(FALSE);
1090 /* needed for single stepping (ugly).
1091 * should this be handled inside the server ???
1093 dbg_curr_process->be_cpu->single_step(&dbg_context, FALSE);
1094 if (dbg_curr_thread->in_exception)
1096 dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
1097 ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, DBG_CONTINUE);
1101 if (!kill)
1103 if (!DebugActiveProcessStop(pcs->pid)) return FALSE;
1105 SymCleanup(pcs->handle);
1106 dbg_del_process(pcs);
1108 return TRUE;
1111 static BOOL tgt_process_active_read(HANDLE hProcess, const void* addr,
1112 void* buffer, SIZE_T len, SIZE_T* rlen)
1114 return ReadProcessMemory( hProcess, addr, buffer, len, rlen );
1117 static BOOL tgt_process_active_write(HANDLE hProcess, void* addr,
1118 const void* buffer, SIZE_T len, SIZE_T* wlen)
1120 return WriteProcessMemory( hProcess, addr, buffer, len, wlen );
1123 static BOOL tgt_process_active_get_selector(HANDLE hThread, DWORD sel, LDT_ENTRY* le)
1125 return GetThreadSelectorEntry( hThread, sel, le );
1128 static struct be_process_io be_process_active_io =
1130 tgt_process_active_close_process,
1131 tgt_process_active_read,
1132 tgt_process_active_write,
1133 tgt_process_active_get_selector