tgt_active.c 33.7 KB
Newer Older
1 2 3
/*
 * Wine debugger - back-end for an active target
 *
Eric Pouech's avatar
Eric Pouech committed
4
 * Copyright 2000-2006 Eric Pouech
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
19 20 21 22 23 24 25 26
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#include "debugger.h"
27
#include "psapi.h"
28
#include "resource.h"
29 30 31 32 33
#include "winternl.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(winedbg);

34
static char*            dbg_executable;
35
static char*            dbg_last_cmd_line;
Eric Pouech's avatar
Eric Pouech committed
36
static struct be_process_io be_process_active_io;
Eric Pouech's avatar
Eric Pouech committed
37 38 39 40 41 42 43 44 45

static void dbg_init_current_process(void)
{
}

static void dbg_init_current_thread(void* start)
{
    if (start)
    {
46
	if (list_count(&dbg_curr_process->threads) == 1 /* first thread ? */ &&
47
	    DBG_IVAR(BreakAllThreadsStartup))
Eric Pouech's avatar
Eric Pouech committed
48
        {
49
	    ADDRESS64   addr;
Eric Pouech's avatar
Eric Pouech committed
50 51 52

            break_set_xpoints(FALSE);
	    addr.Mode   = AddrModeFlat;
53
	    addr.Offset = (DWORD_PTR)start;
Eric Pouech's avatar
Eric Pouech committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	    break_add_break(&addr, TRUE, TRUE);
	    break_set_xpoints(TRUE);
	}
    } 
}

static unsigned dbg_handle_debug_event(DEBUG_EVENT* de);

/******************************************************************
 *		dbg_attach_debuggee
 *
 * Sets the debuggee to <pid>
 * cofe instructs winedbg what to do when first exception is received 
 * (break=FALSE, continue=TRUE)
 * wfe is set to TRUE if dbg_attach_debuggee should also proceed with all debug events
 * until the first exception is received (aka: attach to an already running process)
 */
71
BOOL dbg_attach_debuggee(DWORD pid)
Eric Pouech's avatar
Eric Pouech committed
72
{
73 74 75 76 77
    if (pid == GetCurrentProcessId())
    {
        dbg_printf("WineDbg can't debug its own process. Please use another process ID.\n");
        return FALSE;
    }
Eric Pouech's avatar
Eric Pouech committed
78
    if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, pid, 0))) return FALSE;
Eric Pouech's avatar
Eric Pouech committed
79

80
    if (!DebugActiveProcess(pid))
Eric Pouech's avatar
Eric Pouech committed
81
    {
82
        dbg_printf("Can't attach process %04lx: error %lu\n", pid, GetLastError());
Eric Pouech's avatar
Eric Pouech committed
83 84 85 86
        dbg_del_process(dbg_curr_process);
	return FALSE;
    }

87 88
    SetEnvironmentVariableA("DBGHELP_NOLIVE", NULL);

89
    dbg_curr_process->active_debuggee = TRUE;
Eric Pouech's avatar
Eric Pouech committed
90 91 92 93 94
    return TRUE;
}

static unsigned dbg_fetch_context(void)
{
95
    if (!dbg_curr_process->be_cpu->get_context(dbg_curr_thread->handle, &dbg_context))
Eric Pouech's avatar
Eric Pouech committed
96 97 98 99 100 101 102
    {
        WINE_WARN("Can't get thread's context\n");
        return FALSE;
    }
    return TRUE;
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
BOOL dbg_set_curr_thread(DWORD tid)
{
    struct dbg_thread* thread;

    if (!dbg_curr_process)
    {
        dbg_printf("No process loaded\n");
        return FALSE;
    }

    thread = dbg_get_thread(dbg_curr_process, tid);
    if (thread)
    {
        dbg_curr_thread = thread;
        dbg_fetch_context();
        stack_fetch_frames(&dbg_context);
        dbg_curr_tid = tid;
        return TRUE;
    }
    dbg_printf("No such thread\n");
    return thread != NULL;
}

126 127 128 129 130 131 132
/***********************************************************************
 *              dbg_exception_prolog
 *
 * Examine exception and decide if interactive mode is entered(return TRUE)
 * or exception is silently continued(return FALSE)
 * 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)
Eric Pouech's avatar
Eric Pouech committed
134
{
135
    ADDRESS64   addr;
Eric Pouech's avatar
Eric Pouech committed
136 137 138 139 140 141 142 143
    BOOL        is_break;

    memory_get_current_pc(&addr);
    break_suspend_execution();

    /* this will resynchronize builtin dbghelp's internal ELF module list */
    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);
Eric Pouech's avatar
Eric Pouech committed
145 146 147 148
    /*
     * Do a quiet backtrace so that we have an idea of what the situation
     * is WRT the source files.
     */
149
    stack_fetch_frames(&dbg_context);
150 151

    if (is_debug && !is_break && break_should_continue(&addr, rec->ExceptionCode))
Eric Pouech's avatar
Eric Pouech committed
152 153 154 155
	return FALSE;

    if (addr.Mode != dbg_curr_thread->addr_mode)
    {
156
        const char* name;
157

Eric Pouech's avatar
Eric Pouech committed
158 159 160
        switch (addr.Mode)
        {
        case AddrMode1616: name = "16 bit";     break;
161
        case AddrMode1632: name = "segmented 32 bit"; break;
Eric Pouech's avatar
Eric Pouech committed
162
        case AddrModeReal: name = "vm86";       break;
163 164
        case AddrModeFlat: name = dbg_curr_process->be_cpu->pointer_size == 4
                                  ? "32 bit" : "64 bit"; break;
165
        default: return FALSE;
Eric Pouech's avatar
Eric Pouech committed
166 167 168 169 170 171 172 173 174
        }
        dbg_printf("In %s mode.\n", name);
        dbg_curr_thread->addr_mode = addr.Mode;
    }
    display_print();

    if (!is_debug)
    {
	/* This is a real crash, dump some info */
175
        dbg_curr_process->be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
176
	stack_info(-1);
177
        dbg_curr_process->be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
Eric Pouech's avatar
Eric Pouech committed
178 179 180 181 182 183 184 185 186 187 188
	stack_backtrace(dbg_curr_tid);
    }
    else
    {
        static char*        last_name;
        static char*        last_file;

        char                buffer[sizeof(SYMBOL_INFO) + 256];
        SYMBOL_INFO*        si = (SYMBOL_INFO*)buffer;
        void*               lin = memory_to_linear_addr(&addr);
        DWORD64             disp64;
189
        IMAGEHLP_LINE64     il;
Eric Pouech's avatar
Eric Pouech committed
190 191 192 193 194 195
        DWORD               disp;

        si->SizeOfStruct = sizeof(*si);
        si->MaxNameLen   = 256;
        il.SizeOfStruct = sizeof(il);
        if (SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si) &&
196
            SymGetLineFromAddr64(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
Eric Pouech's avatar
Eric Pouech committed
197 198 199 200
        {
            if ((!last_name || strcmp(last_name, si->Name)) ||
                (!last_file || strcmp(last_file, il.FileName)))
            {
201 202 203 204
                free(last_name);
                free(last_file);
                last_name = strdup(si->Name);
                last_file = strdup(il.FileName);
205
                dbg_printf("%s () at %s:%lu\n", last_name, last_file, il.LineNumber);
Eric Pouech's avatar
Eric Pouech committed
206 207 208 209 210 211 212
            }
        }
    }
    if (!is_debug || is_break ||
        dbg_curr_thread->exec_mode == dbg_exec_step_over_insn ||
        dbg_curr_thread->exec_mode == dbg_exec_step_into_insn)
    {
213
        ADDRESS64 tmp = addr;
Eric Pouech's avatar
Eric Pouech committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        /* Show where we crashed */
        memory_disasm_one_insn(&tmp);
    }
    source_list_from_addr(&addr, 0);

    return TRUE;
}

static void dbg_exception_epilog(void)
{
    break_restart_execution(dbg_curr_thread->exec_count);
    /*
     * This will have gotten absorbed into the breakpoint info
     * if it was used.  Otherwise it would have been ignored.
     * In any case, we don't mess with it any more.
     */
    if (dbg_curr_thread->exec_mode == dbg_exec_cont)
	dbg_curr_thread->exec_count = 0;
    dbg_curr_thread->in_exception = FALSE;
}

static DWORD dbg_handle_exception(const EXCEPTION_RECORD* rec, BOOL first_chance)
{
    BOOL                is_debug = FALSE;
238
    const THREADNAME_INFO*    pThreadName;
Eric Pouech's avatar
Eric Pouech committed
239 240 241 242
    struct dbg_thread*  pThread;

    assert(dbg_curr_thread);

243
    WINE_TRACE("exception=%lx first_chance=%c\n",
Eric Pouech's avatar
Eric Pouech committed
244 245 246 247 248 249 250 251
               rec->ExceptionCode, first_chance ? 'Y' : 'N');

    switch (rec->ExceptionCode)
    {
    case EXCEPTION_BREAKPOINT:
    case EXCEPTION_SINGLE_STEP:
        is_debug = TRUE;
        break;
252
    case EXCEPTION_WINE_NAME_THREAD:
253
        pThreadName = (const THREADNAME_INFO*)(rec->ExceptionInformation);
254 255 256

        if (pThreadName->dwType != 0x1000)
            return DBG_EXCEPTION_NOT_HANDLED;
Eric Pouech's avatar
Eric Pouech committed
257 258 259 260
        if (pThreadName->dwThreadID == -1)
            pThread = dbg_curr_thread;
        else
            pThread = dbg_get_thread(dbg_curr_process, pThreadName->dwThreadID);
261 262
        if(!pThread)
        {
263
            dbg_printf("Thread ID=%04lx not in our list of threads -> can't rename\n", pThreadName->dwThreadID);
264 265
            return DBG_CONTINUE;
        }
266 267 268 269
        if (dbg_read_memory(pThreadName->szName, pThread->name, sizeof(pThread->name)))
        {
            pThread->name[sizeof(pThread->name) - 1] = '\0';
            dbg_printf("Thread ID=%04lx renamed using MSVC extension (name==\"%s\")\n",
Eric Pouech's avatar
Eric Pouech committed
270
                       pThread->tid, pThread->name);
271
        }
Eric Pouech's avatar
Eric Pouech committed
272
        return DBG_CONTINUE;
273 274
    case EXCEPTION_INVALID_HANDLE:
        return DBG_CONTINUE;
Eric Pouech's avatar
Eric Pouech committed
275 276 277 278 279 280 281 282 283
    }

    if (first_chance && !is_debug && !DBG_IVAR(BreakOnFirstChance) &&
	!(rec->ExceptionFlags & EH_STACK_INVALID))
    {
        /* pass exception to program except for debug exceptions */
        return DBG_EXCEPTION_NOT_HANDLED;
    }

284 285 286
    dbg_curr_thread->excpt_record = *rec;
    dbg_curr_thread->in_exception = TRUE;
    dbg_curr_thread->first_chance = first_chance;
Eric Pouech's avatar
Eric Pouech committed
287

288
    if (!is_debug) info_win32_exception();
Eric Pouech's avatar
Eric Pouech committed
289

290 291 292 293
    if (rec->ExceptionCode == STATUS_POSSIBLE_DEADLOCK && !DBG_IVAR(BreakOnCritSectTimeOut))
    {
        dbg_curr_thread->in_exception = FALSE;
        return DBG_EXCEPTION_NOT_HANDLED;
Eric Pouech's avatar
Eric Pouech committed
294 295
    }

296
    if (dbg_exception_prolog(is_debug, rec))
Eric Pouech's avatar
Eric Pouech committed
297 298 299 300 301 302 303 304 305
    {
	dbg_interactiveP = TRUE;
        return 0;
    }
    dbg_exception_epilog();

    return DBG_CONTINUE;
}

306 307
static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill);

308
void fetch_module_name(void* name_addr, void* mod_addr, WCHAR* buffer, size_t bufsz)
309
{
310 311
    memory_get_string_indirect(dbg_curr_process, name_addr, TRUE, buffer, bufsz);
    if (!buffer[0] && !GetModuleFileNameExW(dbg_curr_process->handle, mod_addr, buffer, bufsz))
312
    {
313 314 315 316 317
        if (GetMappedFileNameW( dbg_curr_process->handle, mod_addr, buffer, bufsz ))
        {
            /* FIXME: proper NT->Dos conversion */
            static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};

318
            if (!wcsncmp( buffer, nt_prefixW, 4 ))
319 320 321
                memmove( buffer, buffer + 4, (lstrlenW(buffer + 4) + 1) * sizeof(WCHAR) );
        }
        else
322
            swprintf(buffer, bufsz, L"DLL_%08lx", (ULONG_PTR)mod_addr);
323 324 325
    }
}

Eric Pouech's avatar
Eric Pouech committed
326 327
static unsigned dbg_handle_debug_event(DEBUG_EVENT* de)
{
328 329 330 331
    union {
        char	bufferA[256];
        WCHAR	buffer[256];
    } u;
332
    DWORD size, cont = DBG_CONTINUE;
Eric Pouech's avatar
Eric Pouech committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346

    dbg_curr_pid = de->dwProcessId;
    dbg_curr_tid = de->dwThreadId;

    if ((dbg_curr_process = dbg_get_process(de->dwProcessId)) != NULL)
        dbg_curr_thread = dbg_get_thread(dbg_curr_process, de->dwThreadId);
    else
        dbg_curr_thread = NULL;

    switch (de->dwDebugEventCode)
    {
    case EXCEPTION_DEBUG_EVENT:
        if (!dbg_curr_thread)
        {
347
            WINE_ERR("%04lx:%04lx: not a registered process or thread (perhaps a 16 bit one ?)\n",
Eric Pouech's avatar
Eric Pouech committed
348 349 350 351
                     de->dwProcessId, de->dwThreadId);
            break;
        }

352
        WINE_TRACE("%04lx:%04lx: exception code=%08lx\n",
Eric Pouech's avatar
Eric Pouech committed
353 354 355
                   de->dwProcessId, de->dwThreadId,
                   de->u.Exception.ExceptionRecord.ExceptionCode);

356
        if (dbg_curr_process->event_on_first_exception)
Eric Pouech's avatar
Eric Pouech committed
357
        {
358 359 360
            SetEvent(dbg_curr_process->event_on_first_exception);
            CloseHandle(dbg_curr_process->event_on_first_exception);
            dbg_curr_process->event_on_first_exception = NULL;
Eric Pouech's avatar
Eric Pouech committed
361 362 363 364 365 366 367 368
            if (!DBG_IVAR(BreakOnAttach)) break;
        }
        if (dbg_fetch_context())
        {
            cont = dbg_handle_exception(&de->u.Exception.ExceptionRecord,
                                        de->u.Exception.dwFirstChance);
            if (cont && dbg_curr_thread)
            {
369
                dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
Eric Pouech's avatar
Eric Pouech committed
370 371 372 373 374
            }
        }
        break;

    case CREATE_PROCESS_DEBUG_EVENT:
Eric Pouech's avatar
Eric Pouech committed
375
        dbg_curr_process = dbg_add_process(&be_process_active_io, de->dwProcessId,
Eric Pouech's avatar
Eric Pouech committed
376 377 378 379 380 381
                                           de->u.CreateProcessInfo.hProcess);
        if (dbg_curr_process == NULL)
        {
            WINE_ERR("Couldn't create process\n");
            break;
        }
382 383 384
        size = ARRAY_SIZE(u.buffer);
        if (!QueryFullProcessImageNameW( dbg_curr_process->handle, 0, u.buffer, &size ))
        {
385
            swprintf(u.buffer, ARRAY_SIZE(u.buffer), L"Process_%08x", dbg_curr_pid);
386
        }
Eric Pouech's avatar
Eric Pouech committed
387

388
        WINE_TRACE("%04lx:%04lx: create process '%s'/%p @%p (%lu<%lu>)\n",
Eric Pouech's avatar
Eric Pouech committed
389
                   de->dwProcessId, de->dwThreadId,
390 391
                   wine_dbgstr_w(u.buffer),
                   de->u.CreateProcessInfo.lpImageName,
392
                   de->u.CreateProcessInfo.lpStartAddress,
Eric Pouech's avatar
Eric Pouech committed
393 394
                   de->u.CreateProcessInfo.dwDebugInfoFileOffset,
                   de->u.CreateProcessInfo.nDebugInfoSize);
395
        dbg_set_process_name(dbg_curr_process, u.buffer);
Eric Pouech's avatar
Eric Pouech committed
396

397
        if (!dbg_init(dbg_curr_process->handle, u.buffer, FALSE))
Eric Pouech's avatar
Eric Pouech committed
398
            dbg_printf("Couldn't initiate DbgHelp\n");
399 400
        if (!dbg_load_module(dbg_curr_process->handle, de->u.CreateProcessInfo.hFile, u.buffer,
                             (DWORD_PTR)de->u.CreateProcessInfo.lpBaseOfImage, 0))
401
            dbg_printf("couldn't load main module (%lu)\n", GetLastError());
Eric Pouech's avatar
Eric Pouech committed
402

403
        WINE_TRACE("%04lx:%04lx: create thread I @%p\n",
404
                   de->dwProcessId, de->dwThreadId, de->u.CreateProcessInfo.lpStartAddress);
Eric Pouech's avatar
Eric Pouech committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

        dbg_curr_thread = dbg_add_thread(dbg_curr_process,
                                         de->dwThreadId,
                                         de->u.CreateProcessInfo.hThread,
                                         de->u.CreateProcessInfo.lpThreadLocalBase);
        if (!dbg_curr_thread)
        {
            WINE_ERR("Couldn't create thread\n");
            break;
        }
        dbg_init_current_process();
        dbg_init_current_thread(de->u.CreateProcessInfo.lpStartAddress);
        break;

    case EXIT_PROCESS_DEBUG_EVENT:
420
        WINE_TRACE("%04lx:%04lx: exit process (%ld)\n",
Eric Pouech's avatar
Eric Pouech committed
421 422 423 424 425 426 427
                   de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);

        if (dbg_curr_process == NULL)
        {
            WINE_ERR("Unknown process\n");
            break;
        }
428
        tgt_process_active_close_process(dbg_curr_process, FALSE);
429
        dbg_printf("Process of pid=%04lx has terminated\n", de->dwProcessId);
Eric Pouech's avatar
Eric Pouech committed
430 431 432
        break;

    case CREATE_THREAD_DEBUG_EVENT:
433
        WINE_TRACE("%04lx:%04lx: create thread D @%p\n",
434
                   de->dwProcessId, de->dwThreadId, de->u.CreateThread.lpStartAddress);
Eric Pouech's avatar
Eric Pouech committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

        if (dbg_curr_process == NULL)
        {
            WINE_ERR("Unknown process\n");
            break;
        }
        if (dbg_get_thread(dbg_curr_process, de->dwThreadId) != NULL)
        {
            WINE_TRACE("Thread already listed, skipping\n");
            break;
        }

        dbg_curr_thread = dbg_add_thread(dbg_curr_process,
                                         de->dwThreadId,
                                         de->u.CreateThread.hThread,
                                         de->u.CreateThread.lpThreadLocalBase);
        if (!dbg_curr_thread)
        {
            WINE_ERR("Couldn't create thread\n");
            break;
        }
        dbg_init_current_thread(de->u.CreateThread.lpStartAddress);
        break;

    case EXIT_THREAD_DEBUG_EVENT:
460
        WINE_TRACE("%04lx:%04lx: exit thread (%ld)\n",
Eric Pouech's avatar
Eric Pouech committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
                   de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);

        if (dbg_curr_thread == NULL)
        {
            WINE_ERR("Unknown thread\n");
            break;
        }
        /* FIXME: remove break point set on thread startup */
        dbg_del_thread(dbg_curr_thread);
        break;

    case LOAD_DLL_DEBUG_EVENT:
        if (dbg_curr_thread == NULL)
        {
            WINE_ERR("Unknown thread\n");
            break;
        }
478
        fetch_module_name(de->u.LoadDll.lpImageName, de->u.LoadDll.lpBaseOfDll,
479
                          u.buffer, ARRAY_SIZE(u.buffer));
Eric Pouech's avatar
Eric Pouech committed
480

481
        WINE_TRACE("%04lx:%04lx: loads DLL %s @%p (%lu<%lu>)\n",
Eric Pouech's avatar
Eric Pouech committed
482
                   de->dwProcessId, de->dwThreadId,
483
                   wine_dbgstr_w(u.buffer), de->u.LoadDll.lpBaseOfDll,
Eric Pouech's avatar
Eric Pouech committed
484 485
                   de->u.LoadDll.dwDebugInfoFileOffset,
                   de->u.LoadDll.nDebugInfoSize);
486 487
        dbg_load_module(dbg_curr_process->handle, de->u.LoadDll.hFile, u.buffer,
                        (DWORD_PTR)de->u.LoadDll.lpBaseOfDll, 0);
Eric Pouech's avatar
Eric Pouech committed
488 489 490 491 492
        break_set_xpoints(FALSE);
        break_check_delayed_bp();
        break_set_xpoints(TRUE);
        if (DBG_IVAR(BreakOnDllLoad))
        {
493 494
            dbg_printf("Stopping on DLL %ls loading at %p\n",
                       u.buffer, de->u.LoadDll.lpBaseOfDll);
Eric Pouech's avatar
Eric Pouech committed
495 496 497 498 499
            if (dbg_fetch_context()) cont = 0;
        }
        break;

    case UNLOAD_DLL_DEBUG_EVENT:
500
        WINE_TRACE("%04lx:%04lx: unload DLL @%p\n",
Eric Pouech's avatar
Eric Pouech committed
501
                   de->dwProcessId, de->dwThreadId,
502
                   de->u.UnloadDll.lpBaseOfDll);
503
        break_delete_xpoints_from_module((DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
504
        dbg_unload_module(dbg_curr_process, (DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
Eric Pouech's avatar
Eric Pouech committed
505 506 507 508 509 510 511 512 513 514 515
        break;

    case OUTPUT_DEBUG_STRING_EVENT:
        if (dbg_curr_thread == NULL)
        {
            WINE_ERR("Unknown thread\n");
            break;
        }

        memory_get_string(dbg_curr_process,
                          de->u.DebugString.lpDebugStringData, TRUE,
516
                          de->u.DebugString.fUnicode, u.bufferA, sizeof(u.bufferA));
517
        WINE_TRACE("%04lx:%04lx: output debug string (%s)\n",
518
                   de->dwProcessId, de->dwThreadId, u.bufferA);
Eric Pouech's avatar
Eric Pouech committed
519 520 521
        break;

    case RIP_EVENT:
522
        WINE_TRACE("%04lx:%04lx: rip error=%lu type=%lu\n",
Eric Pouech's avatar
Eric Pouech committed
523 524 525 526 527
                   de->dwProcessId, de->dwThreadId, de->u.RipInfo.dwError,
                   de->u.RipInfo.dwType);
        break;

    default:
528
        WINE_TRACE("%04lx:%04lx: unknown event (%lx)\n",
Eric Pouech's avatar
Eric Pouech committed
529 530 531 532 533 534 535 536 537 538 539
                   de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
    }
    if (!cont) return TRUE;  /* stop execution */
    ContinueDebugEvent(de->dwProcessId, de->dwThreadId, cont);
    return FALSE;  /* continue execution */
}

static void dbg_resume_debuggee(DWORD cont)
{
    if (dbg_curr_thread->in_exception)
    {
540 541
        ADDRESS64       addr;
        char            hexbuf[MAX_OFFSET_TO_STR_LEN];
Eric Pouech's avatar
Eric Pouech committed
542 543 544

        dbg_exception_epilog();
        memory_get_current_pc(&addr);
545 546 547
        WINE_TRACE("Exiting debugger      PC=%s mode=%d count=%d\n",
                   memory_offset_to_string(hexbuf, addr.Offset, 0),
                   dbg_curr_thread->exec_mode,
Eric Pouech's avatar
Eric Pouech committed
548 549 550
                   dbg_curr_thread->exec_count);
        if (dbg_curr_thread)
        {
551
            if (!dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context))
552
                dbg_printf("Cannot set ctx on %04lx\n", dbg_curr_tid);
Eric Pouech's avatar
Eric Pouech committed
553 554 555 556
        }
    }
    dbg_interactiveP = FALSE;
    if (!ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, cont))
557
        dbg_printf("Cannot continue on %04lx (%08lx)\n", dbg_curr_tid, cont);
Eric Pouech's avatar
Eric Pouech committed
558 559
}

560 561 562 563
static void wait_exception(void)
{
    DEBUG_EVENT		de;

564
    while (dbg_num_processes() && WaitForDebugEvent(&de, INFINITE))
565 566 567 568 569 570
    {
        if (dbg_handle_debug_event(&de)) break;
    }
    dbg_interactiveP = TRUE;
}

Eric Pouech's avatar
Eric Pouech committed
571 572
void dbg_wait_next_exception(DWORD cont, int count, int mode)
{
573 574
    ADDRESS64           addr;
    char                hexbuf[MAX_OFFSET_TO_STR_LEN];
Eric Pouech's avatar
Eric Pouech committed
575 576 577 578 579 580 581 582

    if (cont == DBG_CONTINUE)
    {
        dbg_curr_thread->exec_count = count;
        dbg_curr_thread->exec_mode = mode;
    }
    dbg_resume_debuggee(cont);

583
    wait_exception();
Eric Pouech's avatar
Eric Pouech committed
584 585 586
    if (!dbg_curr_process) return;

    memory_get_current_pc(&addr);
587 588 589
    WINE_TRACE("Entering debugger     PC=%s mode=%d count=%d\n",
               memory_offset_to_string(hexbuf, addr.Offset, 0),
               dbg_curr_thread->exec_mode,
Eric Pouech's avatar
Eric Pouech committed
590 591 592
               dbg_curr_thread->exec_count);
}

593
void     dbg_active_wait_for_first_exception(void)
Eric Pouech's avatar
Eric Pouech committed
594
{
595
    dbg_interactiveP = FALSE;
Eric Pouech's avatar
Eric Pouech committed
596
    /* wait for first exception */
597
    wait_exception();
Eric Pouech's avatar
Eric Pouech committed
598 599
}

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
static BOOL dbg_active_wait_for_startup(DEBUG_EVENT* de)
{
    dbg_interactiveP = FALSE;
    while (dbg_num_processes() && WaitForDebugEvent(de, INFINITE))
    {
        switch (de->dwDebugEventCode)
        {
        case CREATE_PROCESS_DEBUG_EVENT:
        case CREATE_THREAD_DEBUG_EVENT:
        case LOAD_DLL_DEBUG_EVENT:
        case EXCEPTION_DEBUG_EVENT:
            if (dbg_handle_debug_event(de)) return TRUE;
            break;
        default:
            return FALSE;
        }
    }
    return FALSE;
}

620
static BOOL dbg_start_debuggee(LPSTR cmdLine)
Eric Pouech's avatar
Eric Pouech committed
621 622
{
    PROCESS_INFORMATION	info;
623
    STARTUPINFOA	startup, current;
624
    DWORD               flags;
Eric Pouech's avatar
Eric Pouech committed
625

626 627
    GetStartupInfoA(&current);

Eric Pouech's avatar
Eric Pouech committed
628 629 630
    memset(&startup, 0, sizeof(startup));
    startup.cb = sizeof(startup);
    startup.dwFlags = STARTF_USESHOWWINDOW;
631 632 633

    startup.wShowWindow = (current.dwFlags & STARTF_USESHOWWINDOW) ?
        current.wShowWindow : SW_SHOWNORMAL;
Eric Pouech's avatar
Eric Pouech committed
634

635 636
    /* FIXME: shouldn't need the CREATE_NEW_CONSOLE, but as usual CUIs need it
     * while GUIs don't
Eric Pouech's avatar
Eric Pouech committed
637
     */
638 639 640
    flags = DEBUG_PROCESS | CREATE_NEW_CONSOLE;
    if (!DBG_IVAR(AlsoDebugProcChild)) flags |= DEBUG_ONLY_THIS_PROCESS;

641 642
    if (!CreateProcessA(NULL, cmdLine, NULL, NULL, FALSE, flags,
                        NULL, NULL, &startup, &info))
Eric Pouech's avatar
Eric Pouech committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    {
	dbg_printf("Couldn't start process '%s'\n", cmdLine);
	return FALSE;
    }
    if (!info.dwProcessId)
    {
        /* this happens when the program being run is not a Wine binary
         * (for example, a shell wrapper around a WineLib app)
         */
        /* Current fix: list running processes and let the user attach
         * to one of them (sic)
         * FIXME: implement a real fix => grab the process (from the
         * running processes) from its name
         */
        dbg_printf("Debuggee has been started (%s)\n"
                   "But WineDbg isn't attached to it. Maybe you're trying to debug a winelib wrapper ??\n"
                   "Try to attach to one of those processes:\n", cmdLine);
        /* FIXME: (HACK) we need some time before the wrapper executes the winelib app */
        Sleep(100);
        info_win32_processes();
        return TRUE;
    }
    dbg_curr_pid = info.dwProcessId;
Eric Pouech's avatar
Eric Pouech committed
666
    if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, dbg_curr_pid, 0))) return FALSE;
667
    dbg_curr_process->active_debuggee = TRUE;
668 669 670 671 672
    if (cmdLine != dbg_last_cmd_line)
    {
        free(dbg_last_cmd_line);
        dbg_last_cmd_line = cmdLine;
    }
Eric Pouech's avatar
Eric Pouech committed
673 674 675 676

    return TRUE;
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
/***********************************************************************
 *           dbg_build_command_line
 *
 * (converted from dlls/ntdll/unix/env.c)
 *
 * Build the command line of a process from the argv array.
 *
 * We must quote and escape characters so that the argv array can be rebuilt
 * from the command line:
 * - spaces and tabs must be quoted
 *   'a b'   -> '"a b"'
 * - quotes must be escaped
 *   '"'     -> '\"'
 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
 *   resulting in an odd number of '\' followed by a '"'
 *   '\"'    -> '\\\"'
 *   '\\"'   -> '\\\\\"'
 * - '\'s are followed by the closing '"' must be doubled,
 *   resulting in an even number of '\' followed by a '"'
 *   ' \'    -> '" \\"'
 *   ' \\'    -> '" \\\\"'
 * - '\'s that are not followed by a '"' can be left as is
 *   'a\b'   == 'a\b'
 *   'a\\b'  == 'a\\b'
 */
static char *dbg_build_command_line( char **argv )
{
    int len;
    char **arg, *ret;
    LPSTR p;

    len = 1;
    for (arg = argv; *arg; arg++) len += 3 + 2 * strlen( *arg );
    if (!(ret = malloc( len ))) return NULL;

    p = ret;
    for (arg = argv; *arg; arg++)
    {
        BOOL has_space, has_quote;
        int i, bcount;
        char *a;

        /* check for quotes and spaces in this argument (first arg is always quoted) */
        has_space = (arg == argv) || !**arg || strchr( *arg, ' ' ) || strchr( *arg, '\t' );
        has_quote = strchr( *arg, '"' ) != NULL;

        /* now transfer it to the command line */
        if (has_space) *p++ = '"';
        if (has_quote || has_space)
        {
            bcount = 0;
            for (a = *arg; *a; a++)
            {
                if (*a == '\\') bcount++;
                else
                {
                    if (*a == '"') /* double all the '\\' preceding this '"', plus one */
                        for (i = 0; i <= bcount; i++) *p++ = '\\';
                    bcount = 0;
                }
                *p++ = *a;
            }
        }
        else
        {
            strcpy( p, *arg );
            p += strlen( p );
        }
        if (has_space)
        {
            /* Double all the '\' preceding the closing quote */
            for (i = 0; i < bcount; i++) *p++ = '\\';
            *p++ = '"';
        }
        *p++ = ' ';
    }
    if (p > ret) p--;  /* remove last space */
    *p = 0;
    return ret;
}


759
void	dbg_run_debuggee(struct list_string* ls)
Eric Pouech's avatar
Eric Pouech committed
760
{
761 762 763 764 765 766
    if (dbg_curr_process)
    {
        dbg_printf("Already attached to a process. Use 'detach' or 'kill' before using 'run'\n");
        return;
    }
    if (!dbg_executable)
Eric Pouech's avatar
Eric Pouech committed
767
    {
768
        dbg_printf("No active target to be restarted\n");
Eric Pouech's avatar
Eric Pouech committed
769 770
        return;
    }
771
    if (ls)
Eric Pouech's avatar
Eric Pouech committed
772
    {
773 774 775 776 777 778 779 780 781 782 783 784 785 786
        char* cl;
        char** argv;
        unsigned argc = 2, i;
        struct list_string* cls;

        for (cls = ls; cls; cls = cls->next) argc++;
        if (!(argv = malloc(argc * sizeof(argv[0])))) return;
        argv[0] = dbg_executable;
        for (i = 1, cls = ls; cls; cls = cls->next, i++) argv[i] = cls->string;
        argv[i] = NULL;
        cl = dbg_build_command_line(argv);
        free(argv);

        if (!cl || !dbg_start_debuggee(cl))
Eric Pouech's avatar
Eric Pouech committed
787
        {
788 789 790 791 792 793 794 795
            free(cl);
            return;
        }
    }
    else
    {
        if (!dbg_last_cmd_line) dbg_last_cmd_line = strdup(dbg_executable);
        dbg_start_debuggee(dbg_last_cmd_line);
Eric Pouech's avatar
Eric Pouech committed
796
    }
797 798
    dbg_active_wait_for_first_exception();
    source_list_from_addr(NULL, 0);
Eric Pouech's avatar
Eric Pouech committed
799 800
}

801
static BOOL str2int(const char* str, DWORD_PTR* val)
802 803 804
{
    char*   ptr;

805
    *val = strtol(str, &ptr, 0);
806 807 808
    return str < ptr && !*ptr;
}

809 810 811 812
static HANDLE create_temp_file(void)
{
    WCHAR path[MAX_PATH], name[MAX_PATH];

813
    if (!GetTempPathW( MAX_PATH, path ) || !GetTempFileNameW( path, L"wdb", 0, name ))
814 815 816 817
        return INVALID_HANDLE_VALUE;
    return CreateFileW( name, GENERIC_READ|GENERIC_WRITE|DELETE, FILE_SHARE_DELETE,
                        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, 0 );
}
818 819 820 821 822 823 824 825 826

/******************************************************************
 *		dbg_active_attach
 *
 * Tries to attach to a running process
 * Handles the <pid> or <pid> <evt> forms
 */
enum dbg_start  dbg_active_attach(int argc, char* argv[])
{
827
    DWORD_PTR pid, evt;
828 829 830 831

    /* try the form <myself> pid */
    if (argc == 1 && str2int(argv[0], &pid) && pid != 0)
    {
832
        if (!dbg_attach_debuggee(pid))
Eric Pouech's avatar
Eric Pouech committed
833
            return start_error_init;
834 835
    }
    /* try the form <myself> pid evt (Win32 JIT debugger) */
Eric Pouech's avatar
Eric Pouech committed
836 837
    else if (argc == 2 && str2int(argv[0], &pid) && pid != 0 &&
             str2int(argv[1], &evt) && evt != 0)
838
    {
839
        if (!dbg_attach_debuggee(pid))
840 841 842 843 844
        {
            /* don't care about result */
            SetEvent((HANDLE)evt);
            return start_error_init;
        }
845
        dbg_curr_process->event_on_first_exception = (HANDLE)evt;
846
    }
Eric Pouech's avatar
Eric Pouech committed
847 848 849 850
    else return start_error_parse;

    dbg_curr_pid = pid;
    return start_ok;
851 852 853 854 855 856 857 858 859 860 861 862 863
}

/******************************************************************
 *		dbg_active_launch
 *
 * Launches a debuggee (with its arguments) from argc/argv
 */
enum dbg_start    dbg_active_launch(int argc, char* argv[])
{
    LPSTR	cmd_line;

    if (argc == 0) return start_error_parse;

864
    dbg_executable = strdup(argv[0]);
865
    cmd_line = dbg_build_command_line(argv);
866

867 868
    if (!dbg_start_debuggee(cmd_line))
    {
869
        free(cmd_line);
870 871
        return start_error_init;
    }
872

873 874
    return start_ok;
}
Eric Pouech's avatar
Eric Pouech committed
875 876 877 878 879 880 881 882

/******************************************************************
 *		dbg_active_auto
 *
 * Starts (<pid> or <pid> <evt>) in automatic mode
 */
enum dbg_start dbg_active_auto(int argc, char* argv[])
{
883
    HANDLE thread = 0, event = 0, input, output = INVALID_HANDLE_VALUE;
884
    enum dbg_start      ds = start_error_parse;
885 886
    BOOL first_exception = TRUE;
    DEBUG_EVENT de;
887

888 889 890 891 892 893 894 895 896
    DBG_IVAR(BreakOnDllLoad) = 0;

    /* auto mode */
    argc--; argv++;
    ds = dbg_active_attach(argc, argv);
    if (ds != start_ok) {
        msgbox_res_id(NULL, IDS_INVALID_PARAMS, IDS_AUTO_CAPTION, MB_OK);
        return ds;
    }
897 898 899 900 901

    switch (display_crash_dialog())
    {
    case ID_DEBUG:
        AllocConsole();
902
        dbg_init_console();
903
        dbg_start_interactive(NULL, INVALID_HANDLE_VALUE);
904
        return start_ok;
905
    case ID_DETAILS:
906 907 908
        event = CreateEventW( NULL, TRUE, FALSE, NULL );
        if (event) thread = display_crash_details( event );
        if (thread) dbg_houtput = output = create_temp_file();
909
        break;
910
    }
911

912
    input = parser_generate_command_file("echo Modules:", "info share",
913 914 915 916
                                         "echo Threads:", "info threads",
                                         "info system",
                                         "detach",
                                         NULL);
917
    if (input == INVALID_HANDLE_VALUE) return start_error_parse;
918

919 920 921 922 923 924 925 926 927
    /* debuggee can terminate before we get the first exception.
     * so detect end of attach load sequence, and then print information.
     */
    if (dbg_curr_process->active_debuggee && !(first_exception = dbg_active_wait_for_startup(&de)))
    {
        dbg_printf("Couldn't get first exception for process %04lx %ls%s.\n"
                   "No backtrace available\n",
                   dbg_curr_pid, dbg_curr_process->imageName, dbg_curr_process->is_wow64 ? " (WOW64)" : "");
    }
928 929

    dbg_interactiveP = TRUE;
930
    parser_handle(NULL, input);
931

932 933 934 935 936 937
    if (!first_exception)
    {
        /* continue managing debug events, in case the exception event comes after current debug event */
        ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
        dbg_active_wait_for_first_exception();
    }
938 939
    if (output != INVALID_HANDLE_VALUE)
    {
940 941
        SetEvent( event );
        WaitForSingleObject( thread, INFINITE );
942
        CloseHandle( output );
943 944
        CloseHandle( thread );
        CloseHandle( event );
945
    }
946

947
    CloseHandle( input );
948 949 950 951 952 953 954 955 956 957 958 959 960
    return start_ok;
}

/******************************************************************
 *		dbg_active_minidump
 *
 * Starts (<pid> or <pid> <evt>) in minidump mode
 */
enum dbg_start dbg_active_minidump(int argc, char* argv[])
{
    HANDLE              hFile;
    enum dbg_start      ds = start_error_parse;
    const char*     file = NULL;
961
    char            tmp[8 + 1 + 2 + MAX_PATH]; /* minidump "<file>" */
962 963 964 965 966 967 968 969 970 971 972 973

    dbg_houtput = GetStdHandle(STD_ERROR_HANDLE);
    DBG_IVAR(BreakOnDllLoad) = 0;

    argc--; argv++;
    /* hard stuff now ; we can get things like:
     * --minidump <pid>                     1 arg
     * --minidump <pid> <evt>               2 args
     * --minidump <file> <pid>              2 args
     * --minidump <file> <pid> <evt>        3 args
     */
    switch (argc)
974
    {
975 976 977 978 979
    case 1:
        ds = dbg_active_attach(argc, argv);
        break;
    case 2:
        if ((ds = dbg_active_attach(argc, argv)) != start_ok)
980 981 982 983
        {
            file = argv[0];
            ds = dbg_active_attach(argc - 1, argv + 1);
        }
984 985 986 987 988 989 990 991 992 993 994 995 996
        break;
    case 3:
        file = argv[0];
        ds = dbg_active_attach(argc - 1, argv + 1);
        break;
    default:
        return start_error_parse;
    }
    if (ds != start_ok) return ds;
    memcpy(tmp, "minidump \"", 10);
    if (!file)
    {
        char        path[MAX_PATH];
997

998 999
        GetTempPathA(sizeof(path), path);
        GetTempFileNameA(path, "WD", 0, tmp + 10);
1000
    }
1001 1002 1003 1004 1005 1006 1007 1008
    else strcpy(tmp + 10, file);
    strcat(tmp, "\"");
    if (!file)
    {
        /* FIXME: should generate unix name as well */
        dbg_printf("Capturing program state in %s\n", tmp + 9);
    }
    hFile = parser_generate_command_file(tmp, "detach", NULL);
1009
    if (hFile == INVALID_HANDLE_VALUE) return start_error_parse;
Eric Pouech's avatar
Eric Pouech committed
1010

1011 1012 1013
    if (dbg_curr_process->active_debuggee)
        dbg_active_wait_for_first_exception();

Eric Pouech's avatar
Eric Pouech committed
1014
    dbg_interactiveP = TRUE;
1015
    parser_handle(NULL, hFile);
Eric Pouech's avatar
Eric Pouech committed
1016

1017
    return start_ok;
Eric Pouech's avatar
Eric Pouech committed
1018
}
1019 1020 1021

static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill)
{
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    if (kill)
    {
        DWORD exit_code = 0;

        if (pcs == dbg_curr_process && dbg_curr_thread->in_exception)
            exit_code = dbg_curr_thread->excpt_record.ExceptionCode;

        TerminateProcess(pcs->handle, exit_code);
    }
    else if (pcs == dbg_curr_process)
1032 1033 1034 1035 1036 1037
    {
        /* remove all set breakpoints in debuggee code */
        break_set_xpoints(FALSE);
        /* needed for single stepping (ugly).
         * should this be handled inside the server ??? 
         */
1038
        dbg_curr_process->be_cpu->single_step(&dbg_context, FALSE);
1039 1040
        if (dbg_curr_thread->in_exception)
        {
1041
            dbg_curr_process->be_cpu->set_context(dbg_curr_thread->handle, &dbg_context);
1042 1043
            ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, DBG_CONTINUE);
        }
1044
    }
1045 1046

    if (!kill)
1047 1048
    {
        if (!DebugActiveProcessStop(pcs->pid)) return FALSE;
1049 1050 1051 1052 1053 1054 1055
    }
    SymCleanup(pcs->handle);
    dbg_del_process(pcs);

    return TRUE;
}

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
static BOOL tgt_process_active_read(HANDLE hProcess, const void* addr,
                                    void* buffer, SIZE_T len, SIZE_T* rlen)
{
    return ReadProcessMemory( hProcess, addr, buffer, len, rlen );
}

static BOOL tgt_process_active_write(HANDLE hProcess, void* addr,
                                     const void* buffer, SIZE_T len, SIZE_T* wlen)
{
    return WriteProcessMemory( hProcess, addr, buffer, len, wlen );
}

static BOOL tgt_process_active_get_selector(HANDLE hThread, DWORD sel, LDT_ENTRY* le)
{
1070 1071 1072 1073 1074 1075 1076 1077 1078
#ifdef _WIN64
    THREAD_DESCRIPTOR_INFORMATION desc = { .Selector = sel };
    ULONG retlen;

    if (RtlWow64GetThreadSelectorEntry( hThread, &desc, sizeof(desc), &retlen ))
        return FALSE;
    *le = desc.Entry;
    return TRUE;
#else
1079
    return GetThreadSelectorEntry( hThread, sel, le );
1080
#endif
1081 1082
}

Eric Pouech's avatar
Eric Pouech committed
1083
static struct be_process_io be_process_active_io =
1084 1085
{
    tgt_process_active_close_process,
1086 1087 1088
    tgt_process_active_read,
    tgt_process_active_write,
    tgt_process_active_get_selector
1089
};