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