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