winedbg.c 23.5 KB
Newer Older
1 2
/* Wine internal debugger
 * Interface to Windows debugger API
3
 * Copyright 2000-2004 Eric Pouech
4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 19
 */

Alexandre Julliard's avatar
Alexandre Julliard committed
20 21 22
#include "config.h"
#include "wine/port.h"

23 24
#include <stdlib.h>
#include <stdio.h>
25
#include <string.h>
26
#include "debugger.h"
27

28
#include "winternl.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
29
#include "wine/exception.h"
30
#include "wine/library.h"
31

32 33
#include "wine/debug.h"

34 35 36
/* TODO list:
 *
 * - minidump
37
 *      + ensure that all commands work as expected in minidump reload function
38
 *        (and re-enable parser usage)
39
 * - CPU adherence
40
 *      + we always assume the stack grows as on i386 (i.e. downwards)
41
 * - UI
42
 *      + re-enable the limited output (depth of structure printing and number of
43
 *        lines)
44
 *      + make the output as close as possible to what gdb does
45 46
 * - symbol management:
 *      + symbol table loading is broken
47 48 49
 *      + in symbol_get_lvalue, we don't do any scoping (as C does) between local and
 *        global vars (we may need this to force some display for example). A solution
 *        would be always to return arrays with: local vars, global vars, thunks
50 51 52 53 54 55 56 57
 * - type management:
 *      + some bits of internal types are missing (like type casts and the address
 *        operator)
 *      + the type for an enum's value is always inferred as int (winedbg & dbghelp)
 *      + most of the code implies that sizeof(void*) = sizeof(int)
 *      + all computations should be made on long long
 *              o expr computations are in int:s
 *              o bitfield size is on a 4-bytes
58
 * - execution:
59 60 61 62 63 64 65 66
 *      + set a better fix for gdb (proxy mode) than the step-mode hack
 *      + implement function call in debuggee
 *      + trampoline management is broken when getting 16 <=> 32 thunk destination
 *        address
 *      + thunking of delayed imports doesn't work as expected (ie, when stepping,
 *        it currently stops at first insn with line number during the library 
 *        loading). We should identify this (__wine_delay_import) and set a
 *        breakpoint instead of single stepping the library loading.
67 68 69 70
 *      + it's wrong to copy thread->step_over_bp into process->bp[0] (when 
 *        we have a multi-thread debuggee). complete fix must include storing all
 *        thread's step-over bp in process-wide bp array, and not to handle bp
 *        when we have the wrong thread running into that bp
71 72 73 74 75 76 77 78 79 80 81
 *      + code in CREATE_PROCESS debug event doesn't work on Windows, as we cannot
 *        get the name of the main module this way. We should rewrite all this code
 *        and store in struct dbg_process as early as possible (before process
 *        creation or attachment), the name of the main module
 * - global:
 *      + define a better way to enable the wine extensions (either DBG SDK function
 *        in dbghelp, or TLS variable, or environment variable or ...)
 *      + audit all files to ensure that we check all potential return values from
 *        every function call to catch the errors
 *      + BTW check also whether the exception mechanism is the best way to return
 *        errors (or find a proper fix for MinGW port)
82 83
 */

84 85
WINE_DEFAULT_DEBUG_CHANNEL(winedbg);

86 87
struct dbg_process*	dbg_curr_process = NULL;
struct dbg_thread*	dbg_curr_thread = NULL;
88 89
DWORD_PTR	        dbg_curr_tid = 0;
DWORD_PTR	        dbg_curr_pid = 0;
90
dbg_ctx_t               dbg_context;
91
BOOL    	        dbg_interactiveP = FALSE;
92
HANDLE                  dbg_houtput = 0;
93

94
static struct list      dbg_process_list = LIST_INIT(dbg_process_list);
95

96
struct dbg_internal_var         dbg_internal_vars[DBG_IV_LAST];
97

98
static void dbg_outputA(const char* buffer, int len)
99
{
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    static char line_buff[4096];
    static unsigned int line_pos;

    DWORD w, i;

    while (len > 0)
    {
        unsigned int count = min( len, sizeof(line_buff) - line_pos );
        memcpy( line_buff + line_pos, buffer, count );
        buffer += count;
        len -= count;
        line_pos += count;
        for (i = line_pos; i > 0; i--) if (line_buff[i-1] == '\n') break;
        if (!i)  /* no newline found */
        {
            if (len > 0) i = line_pos;  /* buffer is full, flush anyway */
            else break;
        }
        WriteFile(dbg_houtput, line_buff, i, &w, NULL);
        memmove( line_buff, line_buff + i, line_pos - i );
        line_pos -= i;
    }
122
}
123

124
const char* dbg_W2A(const WCHAR* buffer, unsigned len)
125
{
126 127 128 129
    static unsigned ansilen;
    static char* ansi;
    unsigned newlen;

130
    newlen = WideCharToMultiByte(CP_ACP, 0, buffer, len, NULL, 0, NULL, NULL);
131
    if (newlen > ansilen)
132
    {
133 134 135 136 137 138 139 140
        static char* newansi;
        if (ansi)
            newansi = HeapReAlloc(GetProcessHeap(), 0, ansi, newlen);
        else
            newansi = HeapAlloc(GetProcessHeap(), 0, newlen);
        if (!newansi) return NULL;
        ansilen = newlen;
        ansi = newansi;
141
    }
142 143 144 145 146 147 148 149 150
    WideCharToMultiByte(CP_ACP, 0, buffer, len, ansi, newlen, NULL, NULL);
    return ansi;
}

void	dbg_outputW(const WCHAR* buffer, int len)
{
    const char* ansi = dbg_W2A(buffer, len);
    if (ansi) dbg_outputA(ansi, strlen(ansi));
    /* FIXME: should CP_ACP be GetConsoleCP()? */
151 152
}

153
int	dbg_printf(const char* format, ...)
154
{
155
    static    char	buf[4*1024];
156
    va_list 	valist;
157
    int		len;
158 159

    va_start(valist, format);
160
    len = vsnprintf(buf, sizeof(buf), format, valist);
161
    va_end(valist);
162

163 164
    if (len <= -1 || len >= sizeof(buf)) 
    {
165 166 167 168
	len = sizeof(buf) - 1;
	buf[len] = 0;
	buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
    }
169
    dbg_outputA(buf, len);
170
    return len;
171
}
172

173
static	unsigned dbg_load_internal_vars(void)
174
{
175 176 177 178 179 180 181
    HKEY	                hkey;
    DWORD 	                type = REG_DWORD;
    DWORD	                val;
    DWORD 	                count = sizeof(val);
    int		                i;
    struct dbg_internal_var*    div = dbg_internal_vars;

182
/* initializes internal vars table */
183
#define  INTERNAL_VAR(_var,_val,_ref,_tid) 			\
184
        div->val = _val; div->name = #_var; div->pval = _ref;	\
185
        div->typeid = _tid; div++;
186 187
#include "intvar.h"
#undef   INTERNAL_VAR
188

189
    /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
190 191 192 193
    if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) 
    {
	WINE_ERR("Cannot create WineDbg key in registry\n");
	return FALSE;
194 195
    }

196 197 198 199
    for (i = 0; i < DBG_IV_LAST; i++) 
    {
        if (!dbg_internal_vars[i].pval) 
        {
200 201
            if (!RegQueryValueExA(hkey, dbg_internal_vars[i].name, 0,
                                  &type, (LPBYTE)&val, &count))
202 203 204 205 206
                dbg_internal_vars[i].val = val;
            dbg_internal_vars[i].pval = &dbg_internal_vars[i].val;
        }
    }
    RegCloseKey(hkey);
207

208 209 210 211 212 213 214 215
    return TRUE;
}

static	unsigned dbg_save_internal_vars(void)
{
    HKEY	                hkey;
    int		                i;

216
    /* @@ Wine registry key: HKCU\Software\Wine\WineDbg */
217 218
    if (RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Wine\\WineDbg", &hkey)) 
    {
219
	WINE_ERR("Cannot create WineDbg key in registry\n");
220 221 222
	return FALSE;
    }

223 224
    for (i = 0; i < DBG_IV_LAST; i++) 
    {
225
        /* FIXME: type should be inferred from basic type -if any- of intvar */
226
        if (dbg_internal_vars[i].pval == &dbg_internal_vars[i].val)
227 228 229 230
        {
            DWORD val = dbg_internal_vars[i].val;
            RegSetValueExA(hkey, dbg_internal_vars[i].name, 0, REG_DWORD, (BYTE *)&val, sizeof(val));
        }
231
    }
232
    RegCloseKey(hkey);
233 234
    return TRUE;
}
235

236
const struct dbg_internal_var* dbg_get_internal_var(const char* name)
237
{
238
    const struct dbg_internal_var*      div;
239

240 241 242
    for (div = &dbg_internal_vars[DBG_IV_LAST - 1]; div >= dbg_internal_vars; div--)
    {
	if (!strcmp(div->name, name)) return div;
243
    }
244
    for (div = dbg_curr_process->be_cpu->context_vars; div->name; div++)
245
    {
246 247 248 249 250 251 252 253
	if (!strcasecmp(div->name, name))
        {
            struct dbg_internal_var*    ret = (void*)lexeme_alloc_size(sizeof(*ret));
            /* relocate register's field against current context */
            *ret = *div;
            ret->pval = (DWORD_PTR*)((char*)&dbg_context + (DWORD_PTR)div->pval);
            return ret;
        }
254 255
    }

256 257
    return NULL;
}
258

259 260
unsigned         dbg_num_processes(void)
{
261
    return list_count(&dbg_process_list);
262 263
}

264
struct dbg_process*     dbg_get_process(DWORD pid)
265
{
266
    struct dbg_process*	p;
267

268 269 270
    LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
	if (p->pid == pid) return p;
    return NULL;
271 272
}

273 274 275 276
struct dbg_process*     dbg_get_process_h(HANDLE h)
{
    struct dbg_process*	p;

277 278 279
    LIST_FOR_EACH_ENTRY(p, &dbg_process_list, struct dbg_process, entry)
	if (p->handle == h) return p;
    return NULL;
280 281
}

282 283 284 285 286
#ifdef __i386__
extern struct backend_cpu be_i386;
#elif defined(__powerpc__)
extern struct backend_cpu be_ppc;
#elif defined(__x86_64__)
287
extern struct backend_cpu be_i386;
288 289 290 291 292 293 294 295 296
extern struct backend_cpu be_x86_64;
#elif defined(__arm__) && !defined(__ARMEB__)
extern struct backend_cpu be_arm;
#elif defined(__aarch64__) && !defined(__AARCH64EB__)
extern struct backend_cpu be_arm64;
#else
# error CPU unknown
#endif

Eric Pouech's avatar
Eric Pouech committed
297
struct dbg_process*	dbg_add_process(const struct be_process_io* pio, DWORD pid, HANDLE h)
298
{
299
    struct dbg_process*	p;
300
    BOOL wow64;
301

302
    if ((p = dbg_get_process(pid)))
303
        return p;
304 305 306

    if (!h)
        h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
307

308
    if (!(p = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_process)))) return NULL;
309 310
    p->handle = h;
    p->pid = pid;
Eric Pouech's avatar
Eric Pouech committed
311
    p->process_io = pio;
312
    p->pio_data = NULL;
313
    p->imageName = NULL;
314
    list_init(&p->threads);
315
    p->continue_on_first_exception = FALSE;
316
    p->active_debuggee = FALSE;
317 318
    p->next_bp = 1;  /* breakpoint 0 is reserved for step-over */
    memset(p->bp, 0, sizeof(p->bp));
319 320
    p->delayed_bp = NULL;
    p->num_delayed_bp = 0;
321 322 323 324 325
    p->source_ofiles = NULL;
    p->search_path = NULL;
    p->source_current_file[0] = '\0';
    p->source_start_line = -1;
    p->source_end_line = -1;
326

327
    list_add_head(&dbg_process_list, &p->entry);
328

329 330
    IsWow64Process(h, &wow64);

331 332 333 334 335
#ifdef __i386__
    p->be_cpu = &be_i386;
#elif defined(__powerpc__)
    p->be_cpu = &be_ppc;
#elif defined(__x86_64__)
336
    p->be_cpu = wow64 ? &be_i386 : &be_x86_64;
337 338 339 340 341 342 343
#elif defined(__arm__) && !defined(__ARMEB__)
    p->be_cpu = &be_arm;
#elif defined(__aarch64__) && !defined(__AARCH64EB__)
    p->be_cpu = &be_arm64;
#else
# error CPU unknown
#endif
344 345 346
    return p;
}

347
void dbg_set_process_name(struct dbg_process* p, const WCHAR* imageName)
348 349 350 351
{
    assert(p->imageName == NULL);
    if (imageName)
    {
352 353
        WCHAR* tmp = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(imageName) + 1) * sizeof(WCHAR));
        if (tmp) p->imageName = lstrcpyW(tmp, imageName);
354 355 356
    }
}

357
void dbg_del_process(struct dbg_process* p)
358
{
359 360
    struct dbg_thread*  t;
    struct dbg_thread*  t2;
361 362
    int	i;

363 364
    LIST_FOR_EACH_ENTRY_SAFE(t, t2, &p->threads, struct dbg_thread, entry)
        dbg_del_thread(t);
365

366 367
    for (i = 0; i < p->num_delayed_bp; i++)
        if (p->delayed_bp[i].is_symbol)
368
            HeapFree(GetProcessHeap(), 0, p->delayed_bp[i].u.symbol.name);
369

370
    HeapFree(GetProcessHeap(), 0, p->delayed_bp);
371 372
    source_nuke_path(p);
    source_free_files(p);
373
    list_remove(&p->entry);
374 375 376
    if (p == dbg_curr_process) dbg_curr_process = NULL;
    HeapFree(GetProcessHeap(), 0, (char*)p->imageName);
    HeapFree(GetProcessHeap(), 0, p);
377 378
}

379 380 381 382 383 384
/******************************************************************
 *		dbg_init
 *
 * Initializes the dbghelp library, and also sets the application directory
 * as a place holder for symbol searches.
 */
385
BOOL dbg_init(HANDLE hProc, const WCHAR* in, BOOL invade)
386 387 388 389 390 391
{
    BOOL        ret;

    ret = SymInitialize(hProc, NULL, invade);
    if (ret && in)
    {
392
        const WCHAR*    last;
393

394
        for (last = in + lstrlenW(in) - 1; last >= in; last--)
395 396 397
        {
            if (*last == '/' || *last == '\\')
            {
398 399 400
                WCHAR*  tmp;
                tmp = HeapAlloc(GetProcessHeap(), 0, (1024 + 1 + (last - in) + 1) * sizeof(WCHAR));
                if (tmp && SymGetSearchPathW(hProc, tmp, 1024))
401
                {
402
                    WCHAR*      x = tmp + lstrlenW(tmp);
403 404

                    *x++ = ';';
405
                    memcpy(x, in, (last - in) * sizeof(WCHAR));
406
                    x[last - in] = '\0';
407
                    ret = SymSetSearchPathW(hProc, tmp);
408 409 410 411 412 413 414 415 416 417
                }
                else ret = FALSE;
                HeapFree(GetProcessHeap(), 0, tmp);
                break;
            }
        }
    }
    return ret;
}

418
struct mod_loader_info
419
{
420
    HANDLE              handle;
421
    IMAGEHLP_MODULE64*  imh_mod;
422
};
423

424
static BOOL CALLBACK mod_loader_cb(PCSTR mod_name, DWORD64 base, PVOID ctx)
425
{
426
    struct mod_loader_info*     mli = ctx;
427

428
    if (!strcmp(mod_name, "<wine-loader>"))
429
    {
430
        if (SymGetModuleInfo64(mli->handle, base, mli->imh_mod))
431
            return FALSE; /* stop enum */
432
    }
433
    return TRUE;
434 435
}

436
BOOL dbg_get_debuggee_info(HANDLE hProcess, IMAGEHLP_MODULE64* imh_mod)
437
{
438
    struct mod_loader_info  mli;
439
    BOOL                    opt;
440 441 442 443 444 445 446 447 448 449

    /* this will resynchronize builtin dbghelp's internal ELF module list */
    SymLoadModule(hProcess, 0, 0, 0, 0, 0);
    mli.handle  = hProcess;
    mli.imh_mod = imh_mod;
    imh_mod->SizeOfStruct = sizeof(*imh_mod);
    imh_mod->BaseOfImage = 0;
    /* this is a wine specific options to return also ELF modules in the
     * enumeration
     */
450
    opt = SymSetExtendedOption(SYMOPT_EX_WINE_NATIVE_MODULES, TRUE);
451
    SymEnumerateModules64(hProcess, mod_loader_cb, &mli);
452
    SymSetExtendedOption(SYMOPT_EX_WINE_NATIVE_MODULES, opt);
453 454 455 456

    return imh_mod->BaseOfImage != 0;
}

457
BOOL dbg_load_module(HANDLE hProc, HANDLE hFile, const WCHAR* name, DWORD_PTR base, DWORD size)
458 459 460 461 462 463 464 465 466 467 468 469
{
    BOOL ret = SymLoadModuleExW(hProc, NULL, name, NULL, base, size, NULL, 0);
    if (ret)
    {
        IMAGEHLP_MODULEW64      ihm;
        ihm.SizeOfStruct = sizeof(ihm);
        if (SymGetModuleInfoW64(hProc, base, &ihm) && (ihm.PdbUnmatched || ihm.DbgUnmatched))
            dbg_printf("Loaded unmatched debug information for %s\n", wine_dbgstr_w(name));
    }
    return ret;
}

470 471 472
struct dbg_thread* dbg_get_thread(struct dbg_process* p, DWORD tid)
{
    struct dbg_thread*	t;
473

474
    if (!p) return NULL;
475 476 477
    LIST_FOR_EACH_ENTRY(t, &p->threads, struct dbg_thread, entry)
	if (t->tid == tid) return t;
    return NULL;
478 479
}

480
struct dbg_thread* dbg_add_thread(struct dbg_process* p, DWORD tid,
481
                                  HANDLE h, void* teb)
482
{
483 484
    struct dbg_thread*	t = HeapAlloc(GetProcessHeap(), 0, sizeof(struct dbg_thread));

485 486
    if (!t)
	return NULL;
487

488 489 490 491
    t->handle = h;
    t->tid = tid;
    t->teb = teb;
    t->process = p;
492
    t->exec_mode = dbg_exec_cont;
493
    t->exec_count = 0;
494 495
    t->step_over_bp.enabled = FALSE;
    t->step_over_bp.refcount = 0;
496
    t->stopped_xpoint = -1;
497
    t->in_exception = FALSE;
498 499 500
    t->frames = NULL;
    t->num_frames = 0;
    t->curr_frame = -1;
501
    t->addr_mode = AddrModeFlat;
502

503
    snprintf(t->name, sizeof(t->name), "%04x", tid);
504

505
    list_add_head(&p->threads, &t->entry);
506 507 508 509

    return t;
}

510
void dbg_del_thread(struct dbg_thread* t)
511
{
512
    HeapFree(GetProcessHeap(), 0, t->frames);
513
    list_remove(&t->entry);
514 515
    if (t == dbg_curr_thread) dbg_curr_thread = NULL;
    HeapFree(GetProcessHeap(), 0, t);
516 517
}

518
void dbg_set_option(const char* option, const char* val)
519
{
520
    if (!strcasecmp(option, "module_load_mismatched"))
521 522
    {
        DWORD   opt = SymGetOptions();
523 524 525 526 527 528 529 530 531
        if (!val)
            dbg_printf("Option: module_load_mismatched %s\n", opt & SYMOPT_LOAD_ANYTHING ? "true" : "false");
        else if (!strcasecmp(val, "true"))      opt |= SYMOPT_LOAD_ANYTHING;
        else if (!strcasecmp(val, "false"))     opt &= ~SYMOPT_LOAD_ANYTHING;
        else
        {
            dbg_printf("Syntax: module_load_mismatched [true|false]\n");
            return;
        }
532 533
        SymSetOptions(opt);
    }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    else if (!strcasecmp(option, "symbol_picker"))
    {
        if (!val)
            dbg_printf("Option: symbol_picker %s\n",
                       symbol_current_picker == symbol_picker_interactive ? "interactive" : "scoped");
        else if (!strcasecmp(val, "interactive"))
            symbol_current_picker = symbol_picker_interactive;
        else if (!strcasecmp(val, "scoped"))
            symbol_current_picker = symbol_picker_scoped;
        else
        {
            dbg_printf("Syntax: symbol_picker [interactive|scoped]\n");
            return;
        }
    }
549 550 551
    else dbg_printf("Unknown option '%s'\n", option);
}

552
BOOL dbg_interrupt_debuggee(void)
553
{
554 555
    struct dbg_process* p;
    if (list_empty(&dbg_process_list)) return FALSE;
556 557 558
    /* FIXME: since we likely have a single process, signal the first process
     * in list
     */
559 560
    p = LIST_ENTRY(list_head(&dbg_process_list), struct dbg_process, entry);
    if (list_next(&dbg_process_list, &p->entry)) dbg_printf("Ctrl-C: only stopping the first process\n");
561
    else dbg_printf("Ctrl-C: stopping debuggee\n");
562 563
    p->continue_on_first_exception = FALSE;
    return DebugBreakProcess(p->handle);
564 565
}

566
static BOOL WINAPI ctrl_c_handler(DWORD dwCtrlType)
Eric Pouech's avatar
Eric Pouech committed
567 568 569
{
    if (dwCtrlType == CTRL_C_EVENT)
    {
570
        return dbg_interrupt_debuggee();
Eric Pouech's avatar
Eric Pouech committed
571 572 573 574
    }
    return FALSE;
}

575
void dbg_init_console(void)
576
{
577 578 579
    /* set the output handle */
    dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);

Eric Pouech's avatar
Eric Pouech committed
580
    /* set our control-C handler */
581
    SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
582 583

    /* set our own title */
584
    SetConsoleTitleA("Wine Debugger");
585 586
}

587
static int dbg_winedbg_usage(BOOL advanced)
588
{
589 590 591
    if (advanced)
    {
    dbg_printf("Usage:\n"
592
               "   winedbg <cmdline>       launch process <cmdline> (as if you were starting\n"
593
               "                           it with wine) and run WineDbg on it\n"
594
               "   winedbg <num>           attach to running process of wpid <num> and run\n"
595
               "                           WineDbg on it\n"
596
               "   winedbg --gdb <cmdline> launch process <cmdline> (as if you were starting\n"
597
               "                           wine) and run gdb (proxied) on it\n"
598
               "   winedbg --gdb <num>     attach to running process of wpid <num> and run\n"
599
               "                           gdb (proxied) on it\n"
600
               "   winedbg <file.mdmp>     reload the minidump <file.mdmp> into memory and run\n"
601 602 603 604
               "                           WineDbg on it\n"
               "   winedbg --help          prints advanced options\n");
    }
    else
605
        dbg_printf("Usage:\n\twinedbg [ [ --gdb ] [ <prog-name> [ <prog-args> ] | <num> | <file.mdmp> | --help ]\n");
606
    return 0;
607 608
}

609 610
void dbg_start_interactive(HANDLE hFile)
{
611 612 613
    struct dbg_process* p;
    struct dbg_process* p2;

614 615
    if (dbg_curr_process)
    {
616
        dbg_printf("WineDbg starting on pid %04lx\n", dbg_curr_pid);
617 618 619 620 621 622
        if (dbg_curr_process->active_debuggee) dbg_active_wait_for_first_exception();
    }

    dbg_interactiveP = TRUE;
    parser_handle(hFile);

623 624
    LIST_FOR_EACH_ENTRY_SAFE(p, p2, &dbg_process_list, struct dbg_process, entry)
        p->process_io->close_process(p, FALSE);
625 626 627 628

    dbg_save_internal_vars();
}

629 630 631 632 633 634
static LONG CALLBACK top_filter( EXCEPTION_POINTERS *ptr )
{
    dbg_printf( "winedbg: Internal crash at %p\n", ptr->ExceptionRecord->ExceptionAddress );
    return EXCEPTION_EXECUTE_HANDLER;
}

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
static void restart_if_wow64(void)
{
    BOOL is_wow64;

    if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
    {
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
        WCHAR filename[MAX_PATH];
        void *redir;
        DWORD exit_code;

        memset( &si, 0, sizeof(si) );
        si.cb = sizeof(si);
        GetModuleFileNameW( 0, filename, MAX_PATH );

        Wow64DisableWow64FsRedirection( &redir );
        if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
        {
            WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
655
            SetConsoleCtrlHandler( NULL, TRUE ); /* Ignore ^C */
656 657 658 659 660 661 662 663 664
            WaitForSingleObject( pi.hProcess, INFINITE );
            GetExitCodeProcess( pi.hProcess, &exit_code );
            ExitProcess( exit_code );
        }
        else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
        Wow64RevertWow64FsRedirection( redir );
    }
}

665
int __cdecl main(int argc, char** argv)
666
{
Eric Pouech's avatar
Eric Pouech committed
667 668 669
    int 	        retv = 0;
    HANDLE              hFile = INVALID_HANDLE_VALUE;
    enum dbg_start      ds;
670

671
    /* Initialize the output */
672
    dbg_houtput = GetStdHandle(STD_OUTPUT_HANDLE);
673

674 675
    SetUnhandledExceptionFilter( top_filter );

676 677
    /* Initialize internal vars */
    if (!dbg_load_internal_vars()) return -1;
678

679 680 681
    /* as we don't care about exec name */
    argc--; argv++;

682 683 684
    if (argc && !strcmp(argv[0], "--help"))
        return dbg_winedbg_usage(TRUE);

685 686
    if (argc && !strcmp(argv[0], "--gdb"))
    {
687
        restart_if_wow64();
688
        retv = gdb_main(argc, argv);
689
        if (retv == -1) dbg_winedbg_usage(FALSE);
690 691
        return retv;
    }
Eric Pouech's avatar
Eric Pouech committed
692
    dbg_init_console();
693

Eric Pouech's avatar
Eric Pouech committed
694 695 696
    SymSetOptions((SymGetOptions() & ~(SYMOPT_UNDNAME)) |
                  SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_AUTO_PUBLICS);

697
    if (argc && !strcmp(argv[0], "--auto"))
Eric Pouech's avatar
Eric Pouech committed
698
    {
699 700 701
        switch (dbg_active_auto(argc, argv))
        {
        case start_ok:          return 0;
702
        case start_error_parse: return dbg_winedbg_usage(FALSE);
703 704
        case start_error_init:  return -1;
        }
Eric Pouech's avatar
Eric Pouech committed
705
    }
706 707 708 709 710 711 712 713 714
    if (argc && !strcmp(argv[0], "--minidump"))
    {
        switch (dbg_active_minidump(argc, argv))
        {
        case start_ok:          return 0;
        case start_error_parse: return dbg_winedbg_usage(FALSE);
        case start_error_init:  return -1;
        }
    }
715 716
    /* parse options */
    while (argc > 0 && argv[0][0] == '-')
717
    {
718
        if (!strcmp(argv[0], "--command"))
719
        {
720 721 722
            argc--; argv++;
            hFile = parser_generate_command_file(argv[0], NULL);
            if (hFile == INVALID_HANDLE_VALUE)
723
            {
724
                dbg_printf("Couldn't open temp file (%u)\n", GetLastError());
725
                return 1;
726
            }
727 728 729 730 731 732 733 734 735
            argc--; argv++;
            continue;
        }
        if (!strcmp(argv[0], "--file"))
        {
            argc--; argv++;
            hFile = CreateFileA(argv[0], GENERIC_READ|DELETE, 0, 
                                NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
            if (hFile == INVALID_HANDLE_VALUE)
736
            {
737
                dbg_printf("Couldn't open file %s (%u)\n", argv[0], GetLastError());
738
                return 1;
739
            }
740 741
            argc--; argv++;
            continue;
742
        }
743 744 745 746 747
        if (!strcmp(argv[0], "--"))
        {
            argc--; argv++;
            break;
        }
748
        return dbg_winedbg_usage(FALSE);
749
    }
750
    if (!argc) ds = start_ok;
751 752
    else if ((ds = dbg_active_attach(argc, argv)) == start_error_parse &&
             (ds = minidump_reload(argc, argv)) == start_error_parse)
753
        ds = dbg_active_launch(argc, argv);
Eric Pouech's avatar
Eric Pouech committed
754
    switch (ds)
755
    {
Eric Pouech's avatar
Eric Pouech committed
756
    case start_ok:              break;
757
    case start_error_parse:     return dbg_winedbg_usage(FALSE);
Eric Pouech's avatar
Eric Pouech committed
758
    case start_error_init:      return -1;
759
    }
760

761 762
    restart_if_wow64();

763
    dbg_start_interactive(hFile);
764

Eric Pouech's avatar
Eric Pouech committed
765
    return 0;
766
}