winedbg: When filling an imagehlp frame information, also do the stack field, it...
[wine] / programs / winedbg / stack.c
1 /*
2  * Debugger stack handling
3  *
4  * Copyright 1995 Alexandre Julliard
5  * Copyright 1996 Eric Youngdale
6  * Copyright 1999 Ove Kåven
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * 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
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <stdio.h>
27
28 #include "debugger.h"
29 #include "winbase.h"
30 #include "wine/winbase16.h"
31 #include "tlhelp32.h"
32
33 /***********************************************************************
34  *           stack_info
35  *
36  * Dump the top of the stack
37  */
38 void stack_info(void)
39 {
40     struct dbg_lvalue lvalue;
41
42     lvalue.cookie = 0;
43     lvalue.type.id = dbg_itype_segptr;
44     lvalue.type.module = 0;
45
46     /* FIXME: we assume stack grows the same way as on i386 */
47     if (!memory_get_current_stack(&lvalue.addr))
48         dbg_printf("Bad segment (%d)\n", lvalue.addr.Segment);
49
50     dbg_printf("Stack dump:\n");
51     switch (lvalue.addr.Mode)
52     {
53     case AddrModeFlat: /* 32-bit mode */
54     case AddrMode1632: /* 32-bit mode */
55         memory_examine(&lvalue, 24, 'x');
56         break;
57     case AddrModeReal:  /* 16-bit mode */
58     case AddrMode1616:
59         memory_examine(&lvalue, 24, 'w');
60         break;
61     }
62 }
63
64 static BOOL stack_set_frame_internal(int newframe)
65 {
66     if (newframe >= dbg_curr_thread->num_frames)
67         newframe = dbg_curr_thread->num_frames - 1;
68     if (newframe < 0)
69         newframe = 0;
70
71     if (dbg_curr_thread->curr_frame != newframe)
72     {
73         IMAGEHLP_STACK_FRAME    ihsf;
74
75         dbg_curr_thread->curr_frame = newframe;
76         stack_get_current_frame(&ihsf);
77         SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
78     }
79     return TRUE;
80 }
81
82 static BOOL stack_get_frame(int nf, IMAGEHLP_STACK_FRAME* ihsf)
83 {
84     memset(ihsf, 0, sizeof(*ihsf));
85     ihsf->InstructionOffset = dbg_curr_thread->frames[nf].linear_pc;
86     ihsf->FrameOffset = dbg_curr_thread->frames[nf].linear_frame;
87     ihsf->StackOffset = dbg_curr_thread->frames[nf].linear_stack;
88     return TRUE;
89 }
90
91 BOOL stack_get_current_frame(IMAGEHLP_STACK_FRAME* ihsf)
92 {
93     /*
94      * If we don't have a valid backtrace, then just return.
95      */
96     if (dbg_curr_thread->frames == NULL) return FALSE;
97     return stack_get_frame(dbg_curr_thread->curr_frame, ihsf);
98 }
99
100 BOOL stack_get_register_current_frame(unsigned regno, DWORD_PTR** pval)
101 {
102     enum be_cpu_addr            kind;
103
104     if (dbg_curr_thread->frames == NULL) return FALSE;
105
106     if (!be_cpu->get_register_info(regno, &kind)) return FALSE;
107
108     switch (kind)
109     {
110     case be_cpu_addr_pc:
111         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_pc;
112         break;
113     case be_cpu_addr_stack:
114         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_stack;
115         break;
116     case be_cpu_addr_frame:
117         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_frame;
118         break;
119     }
120     return TRUE;
121 }
122
123 BOOL stack_get_register_frame(const struct dbg_internal_var* div, DWORD_PTR** pval)
124 {
125     if (dbg_curr_thread->frames == NULL) return FALSE;
126     if (dbg_curr_thread->frames[dbg_curr_thread->curr_frame].is_ctx_valid)
127         *pval = (DWORD_PTR*)((char*)&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].context +
128                              (DWORD_PTR)div->pval);
129     else
130     {
131         enum be_cpu_addr        kind;
132
133         if (!be_cpu->get_register_info(div->val, &kind)) return FALSE;
134
135         /* reuse some known registers directly out of stackwalk details */
136         switch (kind)
137         {
138         case be_cpu_addr_pc:
139             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_pc;
140             break;
141         case be_cpu_addr_stack:
142             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_stack;
143             break;
144         case be_cpu_addr_frame:
145             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_frame;
146             break;
147         }
148     }
149     return TRUE;
150 }
151
152 BOOL stack_set_frame(int newframe)
153 {
154     ADDRESS64   addr;
155     if (!stack_set_frame_internal(newframe)) return FALSE;
156     addr.Mode = AddrModeFlat;
157     addr.Offset = (DWORD_PTR)memory_to_linear_addr(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_pc);
158     source_list_from_addr(&addr, 0);
159     return TRUE;
160 }
161
162 /******************************************************************
163  *              stack_get_current_symbol
164  *
165  * Retrieves the symbol information for the current frame element
166  */
167 BOOL stack_get_current_symbol(SYMBOL_INFO* symbol)
168 {
169     IMAGEHLP_STACK_FRAME        ihsf;
170     DWORD64                     disp;
171
172     if (!stack_get_current_frame(&ihsf)) return FALSE;
173     return SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset,
174                        &disp, symbol);
175 }
176
177 static BOOL CALLBACK stack_read_mem(HANDLE hProc, DWORD64 addr, 
178                                     PVOID buffer, DWORD size, PDWORD written)
179 {
180     SIZE_T sz;
181     BOOL ret;
182
183     struct dbg_process* pcs = dbg_get_process_h(hProc);
184     if (!pcs) return FALSE;
185     ret = pcs->process_io->read(hProc, (const void*)(DWORD_PTR)addr, buffer,
186                                 size, &sz);
187     if (written != NULL) *written = sz;
188     return ret;
189 }
190
191 /******************************************************************
192  *              stack_fetch_frames
193  *
194  * Do a backtrace on the current thread
195  */
196 unsigned stack_fetch_frames(const CONTEXT* _ctx)
197 {
198     STACKFRAME64 sf;
199     unsigned     nf = 0;
200     /* as native stackwalk can modify the context passed to it, simply copy
201      * it to avoid any damage
202      */
203     CONTEXT      ctx = *_ctx, prevctx = ctx;
204
205     HeapFree(GetProcessHeap(), 0, dbg_curr_thread->frames);
206     dbg_curr_thread->frames = NULL;
207
208     memset(&sf, 0, sizeof(sf));
209     memory_get_current_frame(&sf.AddrFrame);
210     memory_get_current_pc(&sf.AddrPC);
211     memory_get_current_stack(&sf.AddrStack);
212
213     /* don't confuse StackWalk by passing in inconsistent addresses */
214     if ((sf.AddrPC.Mode == AddrModeFlat) && (sf.AddrFrame.Mode != AddrModeFlat))
215     {
216         sf.AddrFrame.Offset = (ULONG_PTR)memory_to_linear_addr(&sf.AddrFrame);
217         sf.AddrFrame.Mode = AddrModeFlat;
218     }
219
220     while (StackWalk64(be_cpu->machine, dbg_curr_process->handle,
221                        dbg_curr_thread->handle, &sf, &ctx, stack_read_mem,
222                        SymFunctionTableAccess64, SymGetModuleBase64, NULL))
223     {
224         dbg_curr_thread->frames = dbg_heap_realloc(dbg_curr_thread->frames, 
225                                                    (nf + 1) * sizeof(dbg_curr_thread->frames[0]));
226
227         dbg_curr_thread->frames[nf].addr_pc      = sf.AddrPC;
228         dbg_curr_thread->frames[nf].linear_pc    = (DWORD_PTR)memory_to_linear_addr(&sf.AddrPC);
229         dbg_curr_thread->frames[nf].addr_frame   = sf.AddrFrame;
230         dbg_curr_thread->frames[nf].linear_frame = (DWORD_PTR)memory_to_linear_addr(&sf.AddrFrame);
231         dbg_curr_thread->frames[nf].addr_stack   = sf.AddrStack;
232         dbg_curr_thread->frames[nf].linear_stack = (DWORD_PTR)memory_to_linear_addr(&sf.AddrStack);
233         dbg_curr_thread->frames[nf].context      = prevctx;
234         /* FIXME: can this heuristic be improved: we declare first context always valid, and next ones
235          * if it has been modified by the call to StackWalk...
236          */
237         dbg_curr_thread->frames[nf].is_ctx_valid =
238             (nf == 0 ||
239              (dbg_curr_thread->frames[nf - 1].is_ctx_valid &&
240               memcmp(&dbg_curr_thread->frames[nf - 1].context, &ctx, sizeof(ctx))));
241         prevctx = ctx;
242         nf++;
243         /* we've probably gotten ourselves into an infinite loop so bail */
244         if (nf > 200) break;
245     }
246     dbg_curr_thread->curr_frame = -1;
247     dbg_curr_thread->num_frames = nf;
248     stack_set_frame_internal(0);
249     return nf;
250 }
251
252 struct sym_enum
253 {
254     DWORD_PTR   frame;
255     BOOL        first;
256 };
257
258 static BOOL WINAPI sym_enum_cb(PSYMBOL_INFO sym_info, ULONG size, PVOID user)
259 {
260     struct sym_enum*    se = user;
261
262     if (sym_info->Flags & SYMFLAG_PARAMETER)
263     {
264         if (!se->first) dbg_printf(", "); else se->first = FALSE;
265         symbol_print_local(sym_info, se->frame, FALSE);
266     }
267     return TRUE;
268 }
269
270 static void stack_print_addr_and_args(int nf)
271 {
272     char                        buffer[sizeof(SYMBOL_INFO) + 256];
273     SYMBOL_INFO*                si = (SYMBOL_INFO*)buffer;
274     IMAGEHLP_STACK_FRAME        ihsf;
275     IMAGEHLP_LINE64             il;
276     IMAGEHLP_MODULE             im;
277     DWORD64                     disp64;
278
279     print_bare_address(&dbg_curr_thread->frames[nf].addr_pc);
280
281     stack_get_frame(nf, &ihsf);
282
283     /* grab module where symbol is. If we don't have a module, we cannot print more */
284     im.SizeOfStruct = sizeof(im);
285     if (!SymGetModuleInfo(dbg_curr_process->handle, ihsf.InstructionOffset, &im))
286         return;
287
288     si->SizeOfStruct = sizeof(*si);
289     si->MaxNameLen   = 256;
290     if (SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset, &disp64, si))
291     {
292         struct sym_enum se;
293         DWORD           disp;
294
295         dbg_printf(" %s", si->Name);
296         if (disp64) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
297
298         SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
299         se.first = TRUE;
300         se.frame = ihsf.FrameOffset;
301         dbg_printf("(");
302         SymEnumSymbols(dbg_curr_process->handle, 0, NULL, sym_enum_cb, &se);
303         dbg_printf(")");
304
305         il.SizeOfStruct = sizeof(il);
306         if (SymGetLineFromAddr64(dbg_curr_process->handle,
307                                  ihsf.InstructionOffset, &disp, &il))
308             dbg_printf(" [%s:%u]", il.FileName, il.LineNumber);
309         dbg_printf(" in %s", im.ModuleName);
310     }
311     else dbg_printf(" in %s (+0x%lx)", 
312                     im.ModuleName, (DWORD_PTR)(ihsf.InstructionOffset - im.BaseOfImage));
313 }
314
315 /******************************************************************
316  *              backtrace
317  *
318  * Do a backtrace on the current thread
319  */
320 static void backtrace(void)
321 {
322     unsigned                    cf = dbg_curr_thread->curr_frame;
323     IMAGEHLP_STACK_FRAME        ihsf;
324
325     dbg_printf("Backtrace:\n");
326     for (dbg_curr_thread->curr_frame = 0;
327          dbg_curr_thread->curr_frame < dbg_curr_thread->num_frames;
328          dbg_curr_thread->curr_frame++)
329     {
330         dbg_printf("%s%d ", 
331                    (cf == dbg_curr_thread->curr_frame ? "=>" : "  "),
332                    dbg_curr_thread->curr_frame);
333         stack_print_addr_and_args(dbg_curr_thread->curr_frame);
334         dbg_printf(" (");
335         print_bare_address(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_frame);
336         dbg_printf(")\n");
337     }
338     /* reset context to current stack frame */
339     dbg_curr_thread->curr_frame = cf;
340     if (!dbg_curr_thread->frames) return;
341     stack_get_frame(dbg_curr_thread->curr_frame, &ihsf);
342     SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
343 }
344
345 /******************************************************************
346  *              backtrace_tid
347  *
348  * Do a backtrace on a thread from its process and its identifier
349  * (preserves current thread and context information)
350  */
351 static void backtrace_tid(struct dbg_process* pcs, DWORD tid)
352 {
353     struct dbg_thread*  thread = dbg_curr_thread;
354
355     if (!(dbg_curr_thread = dbg_get_thread(pcs, tid)))
356         dbg_printf("Unknown thread id (%04x) in process (%04x)\n", tid, pcs->pid);
357     else
358     {
359         CONTEXT context;
360
361         dbg_curr_tid = dbg_curr_thread->tid;
362         memset(&context, 0, sizeof(context));
363         context.ContextFlags = CONTEXT_FULL;
364         if (SuspendThread(dbg_curr_thread->handle) != -1)
365         {
366             if (!GetThreadContext(dbg_curr_thread->handle, &context))
367             {
368                 dbg_printf("Can't get context for thread %04x in current process\n",
369                            tid);
370             }
371             else
372             {
373                 stack_fetch_frames(&context);
374                 backtrace();
375             }
376             ResumeThread(dbg_curr_thread->handle);
377         }
378         else dbg_printf("Can't suspend thread %04x in current process\n", tid);
379     }
380     dbg_curr_thread = thread;
381     dbg_curr_tid = thread ? thread->tid : 0;
382 }
383
384 /******************************************************************
385  *              backtrace_all
386  *
387  * Do a backtrace on every running thread in the system (except the debugger)
388  * (preserves current process information)
389  */
390 static void backtrace_all(void)
391 {
392     struct dbg_process* process = dbg_curr_process;
393     struct dbg_thread*  thread = dbg_curr_thread;
394     CONTEXT             ctx = dbg_context;
395     DWORD               cpid = dbg_curr_pid;
396     THREADENTRY32       entry;
397     HANDLE              snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
398
399     if (snapshot == INVALID_HANDLE_VALUE)
400     {
401         dbg_printf("Unable to create toolhelp snapshot\n");
402         return;
403     }
404
405     entry.dwSize = sizeof(entry);
406     if (Thread32First(snapshot, &entry))
407     {
408         do
409         {
410             if (entry.th32OwnerProcessID == GetCurrentProcessId()) continue;
411             if (dbg_curr_process && dbg_curr_pid != entry.th32OwnerProcessID &&
412                 cpid != dbg_curr_pid)
413                 dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
414
415             if (entry.th32OwnerProcessID == cpid)
416             {
417                 dbg_curr_process = process;
418                 dbg_curr_pid = cpid;
419             }
420             else if (entry.th32OwnerProcessID != dbg_curr_pid)
421             {
422                 if (!dbg_attach_debuggee(entry.th32OwnerProcessID, FALSE))
423                 {
424                     dbg_printf("\nwarning: could not attach to %04x\n",
425                                entry.th32OwnerProcessID);
426                     continue;
427                 }
428                 dbg_curr_pid = dbg_curr_process->pid;
429                 dbg_active_wait_for_first_exception();
430             }
431
432             dbg_printf("\nBacktracing for thread %04x in process %04lx (%s):\n",
433                        entry.th32ThreadID, dbg_curr_pid,
434                        dbg_W2A(dbg_curr_process->imageName, -1));
435             backtrace_tid(dbg_curr_process, entry.th32ThreadID);
436         }
437         while (Thread32Next(snapshot, &entry));
438
439         if (dbg_curr_process && cpid != dbg_curr_pid)
440             dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
441     }
442     CloseHandle(snapshot);
443     dbg_curr_process = process;
444     dbg_curr_pid = cpid;
445     dbg_curr_thread = thread;
446     dbg_curr_tid = thread ? thread->tid : 0;
447     dbg_context = ctx;
448 }
449
450 void stack_backtrace(DWORD tid)
451 {
452     /* backtrace every thread in every process except the debugger itself,
453      * invoking via "bt all"
454      */
455     if (tid == -1) return backtrace_all();
456
457     if (!dbg_curr_process) 
458     {
459         dbg_printf("You must be attached to a process to run this command.\n");
460         return;
461     }
462     
463     if (tid == dbg_curr_tid)
464     {
465         backtrace();
466     }
467     else
468     {
469         backtrace_tid(dbg_curr_process, tid);
470     }
471 }