stack.c 15.5 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 * Debugger stack handling
 *
 * Copyright 1995 Alexandre Julliard
Alexandre Julliard's avatar
Alexandre Julliard committed
5
 * Copyright 1996 Eric Youngdale
6
 * Copyright 1999 Ove Kåven
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
21 22
 */

23
#include "config.h"
24

Alexandre Julliard's avatar
Alexandre Julliard committed
25
#include <stdlib.h>
26
#include <stdio.h>
27

Alexandre Julliard's avatar
Alexandre Julliard committed
28
#include "debugger.h"
29
#include "winbase.h"
30
#include "wine/winbase16.h"
31
#include "tlhelp32.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
32 33

/***********************************************************************
34
 *           stack_info
Alexandre Julliard's avatar
Alexandre Julliard committed
35
 *
36
 * Dump the top of the stack. If len <= 0, a default length is used.
Alexandre Julliard's avatar
Alexandre Julliard committed
37
 */
38
void stack_info(int len)
Alexandre Julliard's avatar
Alexandre Julliard committed
39
{
40 41
    struct dbg_lvalue lvalue;

42 43 44
    if(len <= 0)
        len = 24;

45
    lvalue.cookie = 0;
46
    lvalue.type.id = dbg_itype_segptr;
47
    lvalue.type.module = 0;
48

49
    /* FIXME: we assume stack grows the same way as on i386 */
50 51
    if (!memory_get_current_stack(&lvalue.addr))
        dbg_printf("Bad segment (%d)\n", lvalue.addr.Segment);
Alexandre Julliard's avatar
Alexandre Julliard committed
52

53
    dbg_printf("Stack dump:\n");
54
    switch (lvalue.addr.Mode)
55
    {
56
    case AddrModeFlat: /* 32-bit or 64-bit mode */
57
        memory_examine(&lvalue, len, 'a');
58
        break;
59
    case AddrMode1632: /* 32-bit mode */
60
        memory_examine(&lvalue, len, 'x');
61 62 63
        break;
    case AddrModeReal:  /* 16-bit mode */
    case AddrMode1616:
64
        memory_examine(&lvalue, len, 'w');
65
	break;
Alexandre Julliard's avatar
Alexandre Julliard committed
66 67 68
    }
}

69
static BOOL stack_set_frame_internal(int newframe)
Alexandre Julliard's avatar
Alexandre Julliard committed
70
{
71 72 73 74
    if (newframe >= dbg_curr_thread->num_frames)
        newframe = dbg_curr_thread->num_frames - 1;
    if (newframe < 0)
        newframe = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
75

76 77 78
    if (dbg_curr_thread->curr_frame != newframe)
    {
        IMAGEHLP_STACK_FRAME    ihsf;
79

80 81 82 83 84 85 86
        dbg_curr_thread->curr_frame = newframe;
        stack_get_current_frame(&ihsf);
        SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
    }
    return TRUE;
}

87
static BOOL stack_get_frame(int nf, IMAGEHLP_STACK_FRAME* ihsf)
88
{
89
    memset(ihsf, 0, sizeof(*ihsf));
90
    ihsf->InstructionOffset = dbg_curr_thread->frames[nf].linear_pc;
91 92 93 94 95 96 97 98 99
    /* if we're not the first frame, InstructionOffset is the return address
     * after the call instruction (at least on most processors I know of).
     * However, there are cases where this address is outside of the current function.
     * This happens when the called function is marked <NO RETURN>, in which
     * case the compiler can omit the epilog (gcc 4 does it)
     * Therefore, we decrement InstructionOffset in order to ensure that
     * the considered address is really inside the current function.
     */
    if (nf) ihsf->InstructionOffset--;
100
    ihsf->FrameOffset = dbg_curr_thread->frames[nf].linear_frame;
101
    ihsf->StackOffset = dbg_curr_thread->frames[nf].linear_stack;
102 103 104
    return TRUE;
}

105 106 107 108 109 110
BOOL stack_get_current_frame(IMAGEHLP_STACK_FRAME* ihsf)
{
    /*
     * If we don't have a valid backtrace, then just return.
     */
    if (dbg_curr_thread->frames == NULL) return FALSE;
111
    return stack_get_frame(dbg_curr_thread->curr_frame, ihsf);
112 113
}

114 115 116 117 118 119 120 121 122 123
BOOL stack_get_register_frame(const struct dbg_internal_var* div, DWORD_PTR** pval)
{
    if (dbg_curr_thread->frames == NULL) return FALSE;
    if (dbg_curr_thread->frames[dbg_curr_thread->curr_frame].is_ctx_valid)
        *pval = (DWORD_PTR*)((char*)&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].context +
                             (DWORD_PTR)div->pval);
    else
    {
        enum be_cpu_addr        kind;

124
        if (!dbg_curr_process->be_cpu->get_register_info(div->val, &kind)) return FALSE;
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

        /* reuse some known registers directly out of stackwalk details */
        switch (kind)
        {
        case be_cpu_addr_pc:
            *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_pc;
            break;
        case be_cpu_addr_stack:
            *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_stack;
            break;
        case be_cpu_addr_frame:
            *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_frame;
            break;
        }
    }
    return TRUE;
}

143 144
BOOL stack_set_frame(int newframe)
{
145
    ADDRESS64   addr;
146
    if (!stack_set_frame_internal(newframe)) return FALSE;
147
    addr.Mode = AddrModeFlat;
148
    addr.Offset = (DWORD_PTR)memory_to_linear_addr(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_pc);
149
    source_list_from_addr(&addr, 0);
150
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
151
}
Alexandre Julliard's avatar
Alexandre Julliard committed
152

153 154 155 156 157 158
/******************************************************************
 *		stack_get_current_symbol
 *
 * Retrieves the symbol information for the current frame element
 */
BOOL stack_get_current_symbol(SYMBOL_INFO* symbol)
Alexandre Julliard's avatar
Alexandre Julliard committed
159
{
160 161
    IMAGEHLP_STACK_FRAME        ihsf;
    DWORD64                     disp;
162

163 164 165
    if (!stack_get_current_frame(&ihsf)) return FALSE;
    return SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset,
                       &disp, symbol);
166
}
167

168
static BOOL CALLBACK stack_read_mem(HANDLE hProc, DWORD64 addr, 
169 170
                                    PVOID buffer, DWORD size, PDWORD written)
{
171 172 173
    SIZE_T sz;
    BOOL ret;

174 175
    struct dbg_process* pcs = dbg_get_process_h(hProc);
    if (!pcs) return FALSE;
176 177
    ret = pcs->process_io->read(hProc, (const void*)(DWORD_PTR)addr, buffer,
                                size, &sz);
178 179
    if (written != NULL) *written = sz;
    return ret;
180 181
}

182
/******************************************************************
183
 *		stack_fetch_frames
184
 *
185
 * Do a backtrace on the current thread
186
 */
187
unsigned stack_fetch_frames(const dbg_ctx_t* _ctx)
188
{
189 190
    STACKFRAME64 sf;
    unsigned     nf = 0;
191 192 193
    /* as native stackwalk can modify the context passed to it, simply copy
     * it to avoid any damage
     */
194
    dbg_ctx_t ctx = *_ctx;
195
    BOOL         ret;
196

197 198 199
    HeapFree(GetProcessHeap(), 0, dbg_curr_thread->frames);
    dbg_curr_thread->frames = NULL;

200
    memset(&sf, 0, sizeof(sf));
201 202 203
    dbg_curr_process->be_cpu->get_addr(dbg_curr_thread->handle, &ctx, be_cpu_addr_frame, &sf.AddrFrame);
    dbg_curr_process->be_cpu->get_addr(dbg_curr_thread->handle, &ctx, be_cpu_addr_pc, &sf.AddrPC);
    dbg_curr_process->be_cpu->get_addr(dbg_curr_thread->handle, &ctx, be_cpu_addr_stack, &sf.AddrStack);
204

205 206 207
    /* don't confuse StackWalk by passing in inconsistent addresses */
    if ((sf.AddrPC.Mode == AddrModeFlat) && (sf.AddrFrame.Mode != AddrModeFlat))
    {
208
        sf.AddrFrame.Offset = (ULONG_PTR)memory_to_linear_addr(&sf.AddrFrame);
209 210 211
        sf.AddrFrame.Mode = AddrModeFlat;
    }

212
    while ((ret = StackWalk64(dbg_curr_process->be_cpu->machine, dbg_curr_process->handle,
213 214 215
                              dbg_curr_thread->handle, &sf, &ctx, stack_read_mem,
                              SymFunctionTableAccess64, SymGetModuleBase64, NULL)) ||
           nf == 0) /* we always register first frame information */
Alexandre Julliard's avatar
Alexandre Julliard committed
216
    {
217
        dbg_curr_thread->frames = dbg_heap_realloc(dbg_curr_thread->frames,
218
                                                   (nf + 1) * sizeof(dbg_curr_thread->frames[0]));
Alexandre Julliard's avatar
Alexandre Julliard committed
219

220
        dbg_curr_thread->frames[nf].addr_pc      = sf.AddrPC;
221
        dbg_curr_thread->frames[nf].linear_pc    = (DWORD_PTR)memory_to_linear_addr(&sf.AddrPC);
222
        dbg_curr_thread->frames[nf].addr_frame   = sf.AddrFrame;
223
        dbg_curr_thread->frames[nf].linear_frame = (DWORD_PTR)memory_to_linear_addr(&sf.AddrFrame);
224
        dbg_curr_thread->frames[nf].addr_stack   = sf.AddrStack;
225
        dbg_curr_thread->frames[nf].linear_stack = (DWORD_PTR)memory_to_linear_addr(&sf.AddrStack);
226
        dbg_curr_thread->frames[nf].context      = ctx;
227 228 229 230 231 232 233
        /* FIXME: can this heuristic be improved: we declare first context always valid, and next ones
         * if it has been modified by the call to StackWalk...
         */
        dbg_curr_thread->frames[nf].is_ctx_valid =
            (nf == 0 ||
             (dbg_curr_thread->frames[nf - 1].is_ctx_valid &&
              memcmp(&dbg_curr_thread->frames[nf - 1].context, &ctx, sizeof(ctx))));
234
        nf++;
235 236 237 238 239
        /* bail if:
         * - we've (probably) gotten ourselves into an infinite loop,
         * - or StackWalk failed on first frame
         */
        if (nf > 200 || !ret) break;
240
    }
241 242 243 244
    dbg_curr_thread->curr_frame = -1;
    dbg_curr_thread->num_frames = nf;
    stack_set_frame_internal(0);
    return nf;
245 246
}

247 248
struct sym_enum
{
249
    DWORD_PTR   frame;
250
    BOOL        first;
251 252
};

253
static BOOL WINAPI sym_enum_cb(PSYMBOL_INFO sym_info, ULONG size, PVOID user)
254
{
255
    struct sym_enum*    se = user;
256

257
    if (sym_info->Flags & SYMFLAG_PARAMETER)
258
    {
259 260
        if (!se->first) dbg_printf(", "); else se->first = FALSE;
        symbol_print_local(sym_info, se->frame, FALSE);
261 262 263 264 265 266 267 268 269
    }
    return TRUE;
}

static void stack_print_addr_and_args(int nf)
{
    char                        buffer[sizeof(SYMBOL_INFO) + 256];
    SYMBOL_INFO*                si = (SYMBOL_INFO*)buffer;
    IMAGEHLP_STACK_FRAME        ihsf;
270
    IMAGEHLP_LINE64             il;
271 272 273 274 275
    IMAGEHLP_MODULE             im;
    DWORD64                     disp64;

    print_bare_address(&dbg_curr_thread->frames[nf].addr_pc);

276
    stack_get_frame(nf, &ihsf);
277 278 279 280 281 282 283 284 285 286 287 288 289 290

    /* grab module where symbol is. If we don't have a module, we cannot print more */
    im.SizeOfStruct = sizeof(im);
    if (!SymGetModuleInfo(dbg_curr_process->handle, ihsf.InstructionOffset, &im))
        return;

    si->SizeOfStruct = sizeof(*si);
    si->MaxNameLen   = 256;
    if (SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset, &disp64, si))
    {
        struct sym_enum se;
        DWORD           disp;

        dbg_printf(" %s", si->Name);
291
        if (disp64) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
292 293

        SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
294
        se.first = TRUE;
295
        se.frame = ihsf.FrameOffset;
296
        dbg_printf("(");
297
        SymEnumSymbols(dbg_curr_process->handle, 0, NULL, sym_enum_cb, &se);
298
        dbg_printf(")");
299 300

        il.SizeOfStruct = sizeof(il);
301 302
        if (SymGetLineFromAddr64(dbg_curr_process->handle,
				 ihsf.InstructionOffset, &disp, &il))
303
            dbg_printf(" [%s:%u]", il.FileName, il.LineNumber);
304 305 306 307 308 309
        dbg_printf(" in %s", im.ModuleName);
    }
    else dbg_printf(" in %s (+0x%lx)", 
                    im.ModuleName, (DWORD_PTR)(ihsf.InstructionOffset - im.BaseOfImage));
}

310 311 312
/******************************************************************
 *		backtrace
 *
313
 * Do a backtrace on the current thread
314
 */
315
static void backtrace(void)
316
{
317
    unsigned                    cf = dbg_curr_thread->curr_frame;
318
    IMAGEHLP_STACK_FRAME        ihsf;
319 320

    dbg_printf("Backtrace:\n");
321 322 323
    for (dbg_curr_thread->curr_frame = 0;
         dbg_curr_thread->curr_frame < dbg_curr_thread->num_frames;
         dbg_curr_thread->curr_frame++)
324 325
    {
        dbg_printf("%s%d ", 
326
                   (cf == dbg_curr_thread->curr_frame ? "=>" : "  "),
327
                   dbg_curr_thread->curr_frame);
328
        stack_print_addr_and_args(dbg_curr_thread->curr_frame);
329
        dbg_printf(" (");
330
        print_bare_address(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_frame);
331
        dbg_printf(")\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
332
    }
333
    /* reset context to current stack frame */
334
    dbg_curr_thread->curr_frame = cf;
335
    if (!dbg_curr_thread->frames) return;
336
    stack_get_frame(dbg_curr_thread->curr_frame, &ihsf);
337
    SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
338 339 340 341 342 343 344 345
}

/******************************************************************
 *		backtrace_tid
 *
 * Do a backtrace on a thread from its process and its identifier
 * (preserves current thread and context information)
 */
346
static void backtrace_tid(struct dbg_process* pcs, DWORD tid)
347 348
{
    struct dbg_thread*  thread = dbg_curr_thread;
Alexandre Julliard's avatar
Alexandre Julliard committed
349

350
    if (!(dbg_curr_thread = dbg_get_thread(pcs, tid)))
351
        dbg_printf("Unknown thread id (%04x) in process (%04x)\n", tid, pcs->pid);
352 353
    else
    {
354
        dbg_ctx_t ctx = {{0}};
355 356 357 358

        dbg_curr_tid = dbg_curr_thread->tid;
        if (SuspendThread(dbg_curr_thread->handle) != -1)
        {
359
            if (!pcs->be_cpu->get_context(dbg_curr_thread->handle, &ctx))
360
            {
361
                dbg_printf("Can't get context for thread %04x in current process\n",
362 363
                           tid);
            }
364 365
            else
            {
366
                stack_fetch_frames(&ctx);
367 368
                backtrace();
            }
369 370
            ResumeThread(dbg_curr_thread->handle);
        }
371
        else dbg_printf("Can't suspend thread %04x in current process\n", tid);
372 373 374 375 376 377 378 379 380 381 382 383 384
    }
    dbg_curr_thread = thread;
    dbg_curr_tid = thread ? thread->tid : 0;
}

/******************************************************************
 *		backtrace_all
 *
 * Do a backtrace on every running thread in the system (except the debugger)
 * (preserves current process information)
 */
static void backtrace_all(void)
{
385
    struct dbg_process* process = dbg_curr_process;
386
    struct dbg_thread*  thread = dbg_curr_thread;
387
    dbg_ctx_t ctx = dbg_context;
388
    DWORD               cpid = dbg_curr_pid;
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    THREADENTRY32       entry;
    HANDLE              snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    if (snapshot == INVALID_HANDLE_VALUE)
    {
        dbg_printf("Unable to create toolhelp snapshot\n");
        return;
    }

    entry.dwSize = sizeof(entry);
    if (Thread32First(snapshot, &entry))
    {
        do
        {
            if (entry.th32OwnerProcessID == GetCurrentProcessId()) continue;
404 405
            if (dbg_curr_process && dbg_curr_pid != entry.th32OwnerProcessID &&
                cpid != dbg_curr_pid)
406
                dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
407

408 409 410 411 412 413
            if (entry.th32OwnerProcessID == cpid)
            {
                dbg_curr_process = process;
                dbg_curr_pid = cpid;
            }
            else if (entry.th32OwnerProcessID != dbg_curr_pid)
414
            {
415
                if (!dbg_attach_debuggee(entry.th32OwnerProcessID))
416
                {
417
                    dbg_printf("\nwarning: could not attach to %04x\n",
418 419 420 421
                               entry.th32OwnerProcessID);
                    continue;
                }
                dbg_curr_pid = dbg_curr_process->pid;
422
                dbg_active_wait_for_first_exception();
423 424
            }

425
            dbg_printf("\nBacktracing for thread %04x in process %04lx (%s):\n",
426 427
                       entry.th32ThreadID, dbg_curr_pid,
                       dbg_W2A(dbg_curr_process->imageName, -1));
428
            backtrace_tid(dbg_curr_process, entry.th32ThreadID);
429 430 431
        }
        while (Thread32Next(snapshot, &entry));

432
        if (dbg_curr_process && cpid != dbg_curr_pid)
433
            dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
434 435
    }
    CloseHandle(snapshot);
436
    dbg_curr_process = process;
437 438 439 440
    dbg_curr_pid = cpid;
    dbg_curr_thread = thread;
    dbg_curr_tid = thread ? thread->tid : 0;
    dbg_context = ctx;
441 442
}

443
void stack_backtrace(DWORD tid)
444 445 446 447
{
    /* backtrace every thread in every process except the debugger itself,
     * invoking via "bt all"
     */
448 449 450 451 452
    if (tid == -1)
    {
        backtrace_all();
        return;
    }
453 454 455 456 457 458 459

    if (!dbg_curr_process) 
    {
        dbg_printf("You must be attached to a process to run this command.\n");
        return;
    }
    
460
    if (tid == dbg_curr_tid)
Alexandre Julliard's avatar
Alexandre Julliard committed
461
    {
462
        backtrace();
Alexandre Julliard's avatar
Alexandre Julliard committed
463
    }
464
    else
Alexandre Julliard's avatar
Alexandre Julliard committed
465
    {
466
        backtrace_tid(dbg_curr_process, tid);
Alexandre Julliard's avatar
Alexandre Julliard committed
467 468
    }
}