winedbg: Store the CONTEXT in each stack frame to enable register access in the non...
[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     return TRUE;
88 }
89
90 BOOL stack_get_current_frame(IMAGEHLP_STACK_FRAME* ihsf)
91 {
92     /*
93      * If we don't have a valid backtrace, then just return.
94      */
95     if (dbg_curr_thread->frames == NULL) return FALSE;
96     return stack_get_frame(dbg_curr_thread->curr_frame, ihsf);
97 }
98
99 BOOL stack_get_register_current_frame(unsigned regno, DWORD_PTR** pval)
100 {
101     enum be_cpu_addr            kind;
102
103     if (dbg_curr_thread->frames == NULL) return FALSE;
104
105     if (!be_cpu->get_register_info(regno, &kind)) return FALSE;
106
107     switch (kind)
108     {
109     case be_cpu_addr_pc:
110         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_pc;
111         break;
112     case be_cpu_addr_stack:
113         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_stack;
114         break;
115     case be_cpu_addr_frame:
116         *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_frame;
117         break;
118     }
119     return TRUE;
120 }
121
122 BOOL stack_get_register_frame(const struct dbg_internal_var* div, DWORD_PTR** pval)
123 {
124     if (dbg_curr_thread->frames == NULL) return FALSE;
125     if (dbg_curr_thread->frames[dbg_curr_thread->curr_frame].is_ctx_valid)
126         *pval = (DWORD_PTR*)((char*)&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].context +
127                              (DWORD_PTR)div->pval);
128     else
129     {
130         enum be_cpu_addr        kind;
131
132         if (!be_cpu->get_register_info(div->val, &kind)) return FALSE;
133
134         /* reuse some known registers directly out of stackwalk details */
135         switch (kind)
136         {
137         case be_cpu_addr_pc:
138             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_pc;
139             break;
140         case be_cpu_addr_stack:
141             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_stack;
142             break;
143         case be_cpu_addr_frame:
144             *pval = &dbg_curr_thread->frames[dbg_curr_thread->curr_frame].linear_frame;
145             break;
146         }
147     }
148     return TRUE;
149 }
150
151 BOOL stack_set_frame(int newframe)
152 {
153     ADDRESS64   addr;
154     if (!stack_set_frame_internal(newframe)) return FALSE;
155     addr.Mode = AddrModeFlat;
156     addr.Offset = (DWORD_PTR)memory_to_linear_addr(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_pc);
157     source_list_from_addr(&addr, 0);
158     return TRUE;
159 }
160
161 /******************************************************************
162  *              stack_get_current_symbol
163  *
164  * Retrieves the symbol information for the current frame element
165  */
166 BOOL stack_get_current_symbol(SYMBOL_INFO* symbol)
167 {
168     IMAGEHLP_STACK_FRAME        ihsf;
169     DWORD64                     disp;
170
171     if (!stack_get_current_frame(&ihsf)) return FALSE;
172     return SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset,
173                        &disp, symbol);
174 }
175
176 static BOOL CALLBACK stack_read_mem(HANDLE hProc, DWORD64 addr, 
177                                     PVOID buffer, DWORD size, PDWORD written)
178 {
179     SIZE_T sz;
180     BOOL ret;
181
182     struct dbg_process* pcs = dbg_get_process_h(hProc);
183     if (!pcs) return FALSE;
184     ret = pcs->process_io->read(hProc, (const void*)(DWORD_PTR)addr, buffer,
185                                 size, &sz);
186     if (written != NULL) *written = sz;
187     return ret;
188 }
189
190 /******************************************************************
191  *              stack_fetch_frames
192  *
193  * Do a backtrace on the current thread
194  */
195 unsigned stack_fetch_frames(const CONTEXT* _ctx)
196 {
197     STACKFRAME64 sf;
198     unsigned     nf = 0;
199     /* as native stackwalk can modify the context passed to it, simply copy
200      * it to avoid any damage
201      */
202     CONTEXT      ctx = *_ctx, prevctx = ctx;
203
204     HeapFree(GetProcessHeap(), 0, dbg_curr_thread->frames);
205     dbg_curr_thread->frames = NULL;
206
207     memset(&sf, 0, sizeof(sf));
208     memory_get_current_frame(&sf.AddrFrame);
209     memory_get_current_pc(&sf.AddrPC);
210     memory_get_current_stack(&sf.AddrStack);
211
212     /* don't confuse StackWalk by passing in inconsistent addresses */
213     if ((sf.AddrPC.Mode == AddrModeFlat) && (sf.AddrFrame.Mode != AddrModeFlat))
214     {
215         sf.AddrFrame.Offset = (ULONG_PTR)memory_to_linear_addr(&sf.AddrFrame);
216         sf.AddrFrame.Mode = AddrModeFlat;
217     }
218
219     while (StackWalk64(be_cpu->machine, dbg_curr_process->handle,
220                        dbg_curr_thread->handle, &sf, &ctx, stack_read_mem,
221                        SymFunctionTableAccess64, SymGetModuleBase64, NULL))
222     {
223         dbg_curr_thread->frames = dbg_heap_realloc(dbg_curr_thread->frames, 
224                                                    (nf + 1) * sizeof(dbg_curr_thread->frames[0]));
225
226         dbg_curr_thread->frames[nf].addr_pc      = sf.AddrPC;
227         dbg_curr_thread->frames[nf].linear_pc    = (DWORD_PTR)memory_to_linear_addr(&sf.AddrPC);
228         dbg_curr_thread->frames[nf].addr_frame   = sf.AddrFrame;
229         dbg_curr_thread->frames[nf].linear_frame = (DWORD_PTR)memory_to_linear_addr(&sf.AddrFrame);
230         dbg_curr_thread->frames[nf].addr_stack   = sf.AddrStack;
231         dbg_curr_thread->frames[nf].linear_stack = (DWORD_PTR)memory_to_linear_addr(&sf.AddrStack);
232         dbg_curr_thread->frames[nf].context      = prevctx;
233         /* FIXME: can this heuristic be improved: we declare first context always valid, and next ones
234          * if it has been modified by the call to StackWalk...
235          */
236         dbg_curr_thread->frames[nf].is_ctx_valid =
237             (nf == 0 ||
238              (dbg_curr_thread->frames[nf - 1].is_ctx_valid &&
239               memcmp(&dbg_curr_thread->frames[nf - 1].context, &ctx, sizeof(ctx))));
240         prevctx = ctx;
241         nf++;
242         /* we've probably gotten ourselves into an infinite loop so bail */
243         if (nf > 200) break;
244     }
245     dbg_curr_thread->curr_frame = -1;
246     dbg_curr_thread->num_frames = nf;
247     stack_set_frame_internal(0);
248     return nf;
249 }
250
251 struct sym_enum
252 {
253     DWORD_PTR   frame;
254     BOOL        first;
255 };
256
257 static BOOL WINAPI sym_enum_cb(PSYMBOL_INFO sym_info, ULONG size, PVOID user)
258 {
259     struct sym_enum*    se = user;
260
261     if (sym_info->Flags & SYMFLAG_PARAMETER)
262     {
263         if (!se->first) dbg_printf(", "); else se->first = FALSE;
264         symbol_print_local(sym_info, se->frame, FALSE);
265     }
266     return TRUE;
267 }
268
269 static void stack_print_addr_and_args(int nf)
270 {
271     char                        buffer[sizeof(SYMBOL_INFO) + 256];
272     SYMBOL_INFO*                si = (SYMBOL_INFO*)buffer;
273     IMAGEHLP_STACK_FRAME        ihsf;
274     IMAGEHLP_LINE64             il;
275     IMAGEHLP_MODULE             im;
276     DWORD64                     disp64;
277
278     print_bare_address(&dbg_curr_thread->frames[nf].addr_pc);
279
280     stack_get_frame(nf, &ihsf);
281
282     /* grab module where symbol is. If we don't have a module, we cannot print more */
283     im.SizeOfStruct = sizeof(im);
284     if (!SymGetModuleInfo(dbg_curr_process->handle, ihsf.InstructionOffset, &im))
285         return;
286
287     si->SizeOfStruct = sizeof(*si);
288     si->MaxNameLen   = 256;
289     if (SymFromAddr(dbg_curr_process->handle, ihsf.InstructionOffset, &disp64, si))
290     {
291         struct sym_enum se;
292         DWORD           disp;
293
294         dbg_printf(" %s", si->Name);
295         if (disp64) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
296
297         SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
298         se.first = TRUE;
299         se.frame = ihsf.FrameOffset;
300         dbg_printf("(");
301         SymEnumSymbols(dbg_curr_process->handle, 0, NULL, sym_enum_cb, &se);
302         dbg_printf(")");
303
304         il.SizeOfStruct = sizeof(il);
305         if (SymGetLineFromAddr64(dbg_curr_process->handle,
306                                  ihsf.InstructionOffset, &disp, &il))
307             dbg_printf(" [%s:%u]", il.FileName, il.LineNumber);
308         dbg_printf(" in %s", im.ModuleName);
309     }
310     else dbg_printf(" in %s (+0x%lx)", 
311                     im.ModuleName, (DWORD_PTR)(ihsf.InstructionOffset - im.BaseOfImage));
312 }
313
314 /******************************************************************
315  *              backtrace
316  *
317  * Do a backtrace on the current thread
318  */
319 static void backtrace(void)
320 {
321     unsigned                    cf = dbg_curr_thread->curr_frame;
322     IMAGEHLP_STACK_FRAME        ihsf;
323
324     dbg_printf("Backtrace:\n");
325     for (dbg_curr_thread->curr_frame = 0;
326          dbg_curr_thread->curr_frame < dbg_curr_thread->num_frames;
327          dbg_curr_thread->curr_frame++)
328     {
329         dbg_printf("%s%d ", 
330                    (cf == dbg_curr_thread->curr_frame ? "=>" : "  "),
331                    dbg_curr_thread->curr_frame);
332         stack_print_addr_and_args(dbg_curr_thread->curr_frame);
333         dbg_printf(" (");
334         print_bare_address(&dbg_curr_thread->frames[dbg_curr_thread->curr_frame].addr_frame);
335         dbg_printf(")\n");
336     }
337     /* reset context to current stack frame */
338     dbg_curr_thread->curr_frame = cf;
339     if (!dbg_curr_thread->frames) return;
340     stack_get_frame(dbg_curr_thread->curr_frame, &ihsf);
341     SymSetContext(dbg_curr_process->handle, &ihsf, NULL);
342 }
343
344 /******************************************************************
345  *              backtrace_tid
346  *
347  * Do a backtrace on a thread from its process and its identifier
348  * (preserves current thread and context information)
349  */
350 static void backtrace_tid(struct dbg_process* pcs, DWORD tid)
351 {
352     struct dbg_thread*  thread = dbg_curr_thread;
353
354     if (!(dbg_curr_thread = dbg_get_thread(pcs, tid)))
355         dbg_printf("Unknown thread id (%04x) in process (%04x)\n", tid, pcs->pid);
356     else
357     {
358         CONTEXT context;
359
360         dbg_curr_tid = dbg_curr_thread->tid;
361         memset(&context, 0, sizeof(context));
362         context.ContextFlags = CONTEXT_FULL;
363         if (SuspendThread(dbg_curr_thread->handle) != -1)
364         {
365             if (!GetThreadContext(dbg_curr_thread->handle, &context))
366             {
367                 dbg_printf("Can't get context for thread %04x in current process\n",
368                            tid);
369             }
370             else
371             {
372                 stack_fetch_frames(&context);
373                 backtrace();
374             }
375             ResumeThread(dbg_curr_thread->handle);
376         }
377         else dbg_printf("Can't suspend thread %04x in current process\n", tid);
378     }
379     dbg_curr_thread = thread;
380     dbg_curr_tid = thread ? thread->tid : 0;
381 }
382
383 /******************************************************************
384  *              backtrace_all
385  *
386  * Do a backtrace on every running thread in the system (except the debugger)
387  * (preserves current process information)
388  */
389 static void backtrace_all(void)
390 {
391     struct dbg_process* process = dbg_curr_process;
392     struct dbg_thread*  thread = dbg_curr_thread;
393     CONTEXT             ctx = dbg_context;
394     DWORD               cpid = dbg_curr_pid;
395     THREADENTRY32       entry;
396     HANDLE              snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
397
398     if (snapshot == INVALID_HANDLE_VALUE)
399     {
400         dbg_printf("Unable to create toolhelp snapshot\n");
401         return;
402     }
403
404     entry.dwSize = sizeof(entry);
405     if (Thread32First(snapshot, &entry))
406     {
407         do
408         {
409             if (entry.th32OwnerProcessID == GetCurrentProcessId()) continue;
410             if (dbg_curr_process && dbg_curr_pid != entry.th32OwnerProcessID &&
411                 cpid != dbg_curr_pid)
412                 dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
413
414             if (entry.th32OwnerProcessID == cpid)
415             {
416                 dbg_curr_process = process;
417                 dbg_curr_pid = cpid;
418             }
419             else if (entry.th32OwnerProcessID != dbg_curr_pid)
420             {
421                 if (!dbg_attach_debuggee(entry.th32OwnerProcessID, FALSE))
422                 {
423                     dbg_printf("\nwarning: could not attach to %04x\n",
424                                entry.th32OwnerProcessID);
425                     continue;
426                 }
427                 dbg_curr_pid = dbg_curr_process->pid;
428                 dbg_active_wait_for_first_exception();
429             }
430
431             dbg_printf("\nBacktracing for thread %04x in process %04lx (%s):\n",
432                        entry.th32ThreadID, dbg_curr_pid,
433                        dbg_W2A(dbg_curr_process->imageName, -1));
434             backtrace_tid(dbg_curr_process, entry.th32ThreadID);
435         }
436         while (Thread32Next(snapshot, &entry));
437
438         if (dbg_curr_process && cpid != dbg_curr_pid)
439             dbg_curr_process->process_io->close_process(dbg_curr_process, FALSE);
440     }
441     CloseHandle(snapshot);
442     dbg_curr_process = process;
443     dbg_curr_pid = cpid;
444     dbg_curr_thread = thread;
445     dbg_curr_tid = thread ? thread->tid : 0;
446     dbg_context = ctx;
447 }
448
449 void stack_backtrace(DWORD tid)
450 {
451     /* backtrace every thread in every process except the debugger itself,
452      * invoking via "bt all"
453      */
454     if (tid == -1) return backtrace_all();
455
456     if (!dbg_curr_process) 
457     {
458         dbg_printf("You must be attached to a process to run this command.\n");
459         return;
460     }
461     
462     if (tid == dbg_curr_tid)
463     {
464         backtrace();
465     }
466     else
467     {
468         backtrace_tid(dbg_curr_process, tid);
469     }
470 }