]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/coregrind/m_stacktrace.c
update
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / coregrind / m_stacktrace.c
1
2 /*--------------------------------------------------------------------*/
3 /*--- Take snapshots of client stacks.              m_stacktrace.c ---*/
4 /*--------------------------------------------------------------------*/
5
6 /*
7    This file is part of Valgrind, a dynamic binary instrumentation
8    framework.
9
10    Copyright (C) 2000-2010 Julian Seward 
11       jseward@acm.org
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of the
16    License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful, but
19    WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26    02111-1307, USA.
27
28    The GNU General Public License is contained in the file COPYING.
29 */
30
31 #include "pub_core_basics.h"
32 #include "pub_core_vki.h"
33 #include "pub_core_threadstate.h"
34 #include "pub_core_debuginfo.h"     // XXX: circular dependency
35 #include "pub_core_aspacemgr.h"     // For VG_(is_addressable)()
36 #include "pub_core_libcbase.h"
37 #include "pub_core_libcassert.h"
38 #include "pub_core_libcprint.h"
39 #include "pub_core_machine.h"
40 #include "pub_core_options.h"
41 #include "pub_core_stacks.h"        // VG_(stack_limits)
42 #include "pub_core_stacktrace.h"
43 #include "pub_core_xarray.h"
44 #include "pub_core_clientstate.h"   // VG_(client__dl_sysinfo_int80)
45 #include "pub_core_trampoline.h"
46
47
48 /*------------------------------------------------------------*/
49 /*---                                                      ---*/
50 /*--- BEGIN platform-dependent unwinder worker functions   ---*/
51 /*---                                                      ---*/
52 /*------------------------------------------------------------*/
53
54 /* Take a snapshot of the client's stack, putting up to 'max_n_ips'
55    IPs into 'ips'.  In order to be thread-safe, we pass in the
56    thread's IP SP, FP if that's meaningful, and LR if that's
57    meaningful.  Returns number of IPs put in 'ips'.
58
59    If you know what the thread ID for this stack is, send that as the
60    first parameter, else send zero.  This helps generate better stack
61    traces on ppc64-linux and has no effect on other platforms.
62 */
63
64 /* ------------------------ x86 ------------------------- */
65
66 #if defined(VGP_x86_linux) || defined(VGP_x86_darwin) || defined(VGP_x86_l4re)
67
68 UInt VG_(get_StackTrace_wrk) ( ThreadId tid_if_known,
69                                /*OUT*/Addr* ips, UInt max_n_ips,
70                                /*OUT*/Addr* sps, /*OUT*/Addr* fps,
71                                UnwindStartRegs* startRegs,
72                                Addr fp_max_orig )
73 {
74    Bool  debug = False;
75    Int   i;
76    Addr  fp_max;
77    UInt  n_found = 0;
78
79    vg_assert(sizeof(Addr) == sizeof(UWord));
80    vg_assert(sizeof(Addr) == sizeof(void*));
81
82    D3UnwindRegs uregs;
83    uregs.xip = (Addr)startRegs->r_pc;
84    uregs.xsp = (Addr)startRegs->r_sp;
85    uregs.xbp = startRegs->misc.X86.r_ebp;
86    Addr fp_min = uregs.xsp;
87
88    /* Snaffle IPs from the client's stack into ips[0 .. max_n_ips-1],
89       stopping when the trail goes cold, which we guess to be
90       when FP is not a reasonable stack location. */
91
92    // JRS 2002-sep-17: hack, to round up fp_max to the end of the
93    // current page, at least.  Dunno if it helps.
94    // NJN 2002-sep-17: seems to -- stack traces look like 1.0.X again
95    fp_max = VG_PGROUNDUP(fp_max_orig);
96    if (fp_max >= sizeof(Addr))
97       fp_max -= sizeof(Addr);
98
99    if (debug)
100       VG_(printf)("max_n_ips=%d fp_min=0x%lx fp_max_orig=0x%lx, "
101                   "fp_max=0x%lx ip=0x%lx fp=0x%lx\n",
102                   max_n_ips, fp_min, fp_max_orig, fp_max,
103                   uregs.xip, uregs.xbp);
104
105    /* Assertion broken before main() is reached in pthreaded programs;  the
106     * offending stack traces only have one item.  --njn, 2002-aug-16 */
107    /* vg_assert(fp_min <= fp_max);*/
108    // On Darwin, this kicks in for pthread-related stack traces, so they're
109    // only 1 entry long which is wrong.
110 #  if !defined(VGO_darwin)
111    if (fp_min + 512 >= fp_max) {
112       /* If the stack limits look bogus, don't poke around ... but
113          don't bomb out either. */
114       if (sps) sps[0] = uregs.xsp;
115       if (fps) fps[0] = uregs.xbp;
116       ips[0] = uregs.xip;
117       return 1;
118    } 
119 #  endif
120
121    /* fp is %ebp.  sp is %esp.  ip is %eip. */
122
123    if (sps) sps[0] = uregs.xsp;
124    if (fps) fps[0] = uregs.xbp;
125    ips[0] = uregs.xip;
126    i = 1;
127
128    /* Loop unwinding the stack. Note that the IP value we get on
129     * each pass (whether from CFI info or a stack frame) is a
130     * return address so is actually after the calling instruction
131     * in the calling function.
132     *
133     * Because of this we subtract one from the IP after each pass
134     * of the loop so that we find the right CFI block on the next
135     * pass - otherwise we can find the wrong CFI info if it happens
136     * to change after the calling instruction and that will mean
137     * that we will fail to unwind the next step.
138     *
139     * This most frequently happens at the end of a function when
140     * a tail call occurs and we wind up using the CFI info for the
141     * next function which is completely wrong.
142     */
143    while (True) {
144
145       if (i >= max_n_ips)
146          break;
147
148       /* Try to derive a new (ip,sp,fp) triple from the current
149          set. */
150
151       /* On x86, first try the old-fashioned method of following the
152          %ebp-chain.  Code which doesn't use this (that is, compiled
153          with -fomit-frame-pointer) is not ABI compliant and so
154          relatively rare.  Besides, trying the CFI first almost always
155          fails, and is expensive. */
156       /* Deal with frames resulting from functions which begin "pushl%
157          ebp ; movl %esp, %ebp" which is the ABI-mandated preamble. */
158       if (fp_min <= uregs.xbp &&
159           uregs.xbp <= fp_max - 1 * sizeof(UWord)/*see comment below*/)
160       {
161          /* fp looks sane, so use it. */
162          uregs.xip = (((UWord*)uregs.xbp)[1]);
163          // We stop if we hit a zero (the traditional end-of-stack
164          // marker) or a one -- these correspond to recorded IPs of 0 or -1.
165          // The latter because r8818 (in this file) changes the meaning of
166          // entries [1] and above in a stack trace, by subtracting 1 from
167          // them.  Hence stacks that used to end with a zero value now end in
168          // -1 and so we must detect that too.
169          if (0 == uregs.xip || 1 == uregs.xip) break;
170          uregs.xsp = uregs.xbp + sizeof(Addr) /*saved %ebp*/ 
171                                + sizeof(Addr) /*ra*/;
172          uregs.xbp = (((UWord*)uregs.xbp)[0]);
173          if (sps) sps[i] = uregs.xsp;
174          if (fps) fps[i] = uregs.xbp;
175          ips[i++] = uregs.xip - 1; /* -1: refer to calling insn, not the RA */
176          if (debug)
177             VG_(printf)("     ipsF[%d]=0x%08lx\n", i-1, ips[i-1]);
178          uregs.xip = uregs.xip - 1;
179             /* as per comment at the head of this loop */
180          continue;
181       }
182
183       /* That didn't work out, so see if there is any CF info to hand
184          which can be used. */
185       if ( VG_(use_CF_info)( &uregs, fp_min, fp_max ) ) {
186          if (0 == uregs.xip || 1 == uregs.xip) break;
187          if (sps) sps[i] = uregs.xsp;
188          if (fps) fps[i] = uregs.xbp;
189          ips[i++] = uregs.xip - 1; /* -1: refer to calling insn, not the RA */
190          if (debug)
191             VG_(printf)("     ipsC[%d]=0x%08lx\n", i-1, ips[i-1]);
192          uregs.xip = uregs.xip - 1;
193             /* as per comment at the head of this loop */
194          continue;
195       }
196
197       /* And, similarly, try for MSVC FPO unwind info. */
198       if ( VG_(use_FPO_info)( &uregs.xip, &uregs.xsp, &uregs.xbp,
199                               fp_min, fp_max ) ) {
200          if (0 == uregs.xip || 1 == uregs.xip) break;
201          if (sps) sps[i] = uregs.xsp;
202          if (fps) fps[i] = uregs.xbp;
203          ips[i++] = uregs.xip;
204          if (debug)
205             VG_(printf)("     ipsC[%d]=0x%08lx\n", i-1, ips[i-1]);
206          uregs.xip = uregs.xip - 1;
207          continue;
208       }
209
210       /* No luck.  We have to give up. */
211       break;
212    }
213
214    n_found = i;
215    return n_found;
216 }
217
218 #endif
219
220 /* ----------------------- amd64 ------------------------ */
221
222 #if defined(VGP_amd64_linux) || defined(VGP_amd64_darwin)
223
224 UInt VG_(get_StackTrace_wrk) ( ThreadId tid_if_known,
225                                /*OUT*/Addr* ips, UInt max_n_ips,
226                                /*OUT*/Addr* sps, /*OUT*/Addr* fps,
227                                UnwindStartRegs* startRegs,
228                                Addr fp_max_orig )
229 {
230    Bool  debug = False;
231    Int   i;
232    Addr  fp_max;
233    UInt  n_found = 0;
234
235    vg_assert(sizeof(Addr) == sizeof(UWord));
236    vg_assert(sizeof(Addr) == sizeof(void*));
237
238    D3UnwindRegs uregs;
239    uregs.xip = startRegs->r_pc;
240    uregs.xsp = startRegs->r_sp;
241    uregs.xbp = startRegs->misc.AMD64.r_rbp;
242    Addr fp_min = uregs.xsp;
243
244    /* Snaffle IPs from the client's stack into ips[0 .. max_n_ips-1],
245       stopping when the trail goes cold, which we guess to be
246       when FP is not a reasonable stack location. */
247
248    // JRS 2002-sep-17: hack, to round up fp_max to the end of the
249    // current page, at least.  Dunno if it helps.
250    // NJN 2002-sep-17: seems to -- stack traces look like 1.0.X again
251    fp_max = VG_PGROUNDUP(fp_max_orig);
252    if (fp_max >= sizeof(Addr))
253       fp_max -= sizeof(Addr);
254
255    if (debug)
256       VG_(printf)("max_n_ips=%d fp_min=0x%lx fp_max_orig=0x%lx, "
257                   "fp_max=0x%lx ip=0x%lx fp=0x%lx\n",
258                   max_n_ips, fp_min, fp_max_orig, fp_max,
259                   uregs.xip, uregs.xbp);
260
261    /* Assertion broken before main() is reached in pthreaded programs;  the
262     * offending stack traces only have one item.  --njn, 2002-aug-16 */
263    /* vg_assert(fp_min <= fp_max);*/
264    // On Darwin, this kicks in for pthread-related stack traces, so they're
265    // only 1 entry long which is wrong.
266 #  if !defined(VGO_darwin)
267    if (fp_min + 512 >= fp_max) {
268       /* If the stack limits look bogus, don't poke around ... but
269          don't bomb out either. */
270       if (sps) sps[0] = uregs.xsp;
271       if (fps) fps[0] = uregs.xbp;
272       ips[0] = uregs.xip;
273       return 1;
274    } 
275 #  endif
276
277    /* fp is %rbp.  sp is %rsp.  ip is %rip. */
278
279    ips[0] = uregs.xip;
280    if (sps) sps[0] = uregs.xsp;
281    if (fps) fps[0] = uregs.xbp;
282    i = 1;
283
284    /* Loop unwinding the stack. Note that the IP value we get on
285     * each pass (whether from CFI info or a stack frame) is a
286     * return address so is actually after the calling instruction
287     * in the calling function.
288     *
289     * Because of this we subtract one from the IP after each pass
290     * of the loop so that we find the right CFI block on the next
291     * pass - otherwise we can find the wrong CFI info if it happens
292     * to change after the calling instruction and that will mean
293     * that we will fail to unwind the next step.
294     *
295     * This most frequently happens at the end of a function when
296     * a tail call occurs and we wind up using the CFI info for the
297     * next function which is completely wrong.
298     */
299    while (True) {
300
301       if (i >= max_n_ips)
302          break;
303
304       /* Try to derive a new (ip,sp,fp) triple from the current set. */
305
306       /* First off, see if there is any CFI info to hand which can
307          be used. */
308       if ( VG_(use_CF_info)( &uregs, fp_min, fp_max ) ) {
309          if (0 == uregs.xip || 1 == uregs.xip) break;
310          if (sps) sps[i] = uregs.xsp;
311          if (fps) fps[i] = uregs.xbp;
312          ips[i++] = uregs.xip - 1; /* -1: refer to calling insn, not the RA */
313          if (debug)
314             VG_(printf)("     ipsC[%d]=%#08lx\n", i-1, ips[i-1]);
315          uregs.xip = uregs.xip - 1; /* as per comment at the head of this loop */
316          continue;
317       }
318
319       /* If VG_(use_CF_info) fails, it won't modify ip/sp/fp, so
320          we can safely try the old-fashioned method. */
321       /* This bit is supposed to deal with frames resulting from
322          functions which begin "pushq %rbp ; movq %rsp, %rbp".
323          Unfortunately, since we can't (easily) look at the insns at
324          the start of the fn, like GDB does, there's no reliable way
325          to tell.  Hence the hack of first trying out CFI, and if that
326          fails, then use this as a fallback. */
327       /* Note: re "- 1 * sizeof(UWord)", need to take account of the
328          fact that we are prodding at & ((UWord*)fp)[1] and so need to
329          adjust the limit check accordingly.  Omitting this has been
330          observed to cause segfaults on rare occasions. */
331       if (fp_min <= uregs.xbp && uregs.xbp <= fp_max - 1 * sizeof(UWord)) {
332          /* fp looks sane, so use it. */
333          uregs.xip = (((UWord*)uregs.xbp)[1]);
334          if (0 == uregs.xip || 1 == uregs.xip) break;
335          uregs.xsp = uregs.xbp + sizeof(Addr) /*saved %rbp*/ 
336                                + sizeof(Addr) /*ra*/;
337          uregs.xbp = (((UWord*)uregs.xbp)[0]);
338          if (sps) sps[i] = uregs.xsp;
339          if (fps) fps[i] = uregs.xbp;
340          ips[i++] = uregs.xip - 1; /* -1: refer to calling insn, not the RA */
341          if (debug)
342             VG_(printf)("     ipsF[%d]=%#08lx\n", i-1, ips[i-1]);
343          uregs.xip = uregs.xip - 1; /* as per comment at the head of this loop */
344          continue;
345       }
346
347       /* Last-ditch hack (evidently GDB does something similar).  We
348          are in the middle of nowhere and we have a nonsense value for
349          the frame pointer.  If the stack pointer is still valid,
350          assume that what it points at is a return address.  Yes,
351          desperate measures.  Could do better here:
352          - check that the supposed return address is in
353            an executable page
354          - check that the supposed return address is just after a call insn
355          - given those two checks, don't just consider *sp as the return 
356            address; instead scan a likely section of stack (eg sp .. sp+256)
357            and use suitable values found there.
358       */
359       if (fp_min <= uregs.xsp && uregs.xsp < fp_max) {
360          uregs.xip = ((UWord*)uregs.xsp)[0];
361          if (0 == uregs.xip || 1 == uregs.xip) break;
362          if (sps) sps[i] = uregs.xsp;
363          if (fps) fps[i] = uregs.xbp;
364          ips[i++] = uregs.xip == 0 
365                     ? 0 /* sp[0] == 0 ==> stuck at the bottom of a
366                            thread stack */
367                     : uregs.xip - 1;
368                         /* -1: refer to calling insn, not the RA */
369          if (debug)
370             VG_(printf)("     ipsH[%d]=%#08lx\n", i-1, ips[i-1]);
371          uregs.xip = uregs.xip - 1; /* as per comment at the head of this loop */
372          uregs.xsp += 8;
373          continue;
374       }
375
376       /* No luck at all.  We have to give up. */
377       break;
378    }
379
380    n_found = i;
381    return n_found;
382 }
383
384 #endif
385
386 /* -----------------------ppc32/64 ---------------------- */
387
388 #if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux) \
389     || defined(VGP_ppc32_aix5) || defined(VGP_ppc64_aix5)
390
391 UInt VG_(get_StackTrace_wrk) ( ThreadId tid_if_known,
392                                /*OUT*/Addr* ips, UInt max_n_ips,
393                                /*OUT*/Addr* sps, /*OUT*/Addr* fps,
394                                UnwindStartRegs* startRegs,
395                                Addr fp_max_orig )
396 {
397    Bool  lr_is_first_RA = False;
398 #  if defined(VG_PLAT_USES_PPCTOC)
399    Word redir_stack_size = 0;
400    Word redirs_used      = 0;
401 #  endif
402
403    Bool  debug = False;
404    Int   i;
405    Addr  fp_max;
406    UInt  n_found = 0;
407
408    vg_assert(sizeof(Addr) == sizeof(UWord));
409    vg_assert(sizeof(Addr) == sizeof(void*));
410
411    Addr ip = (Addr)startRegs->r_pc;
412    Addr sp = (Addr)startRegs->r_sp;
413    Addr fp = sp;
414 #  if defined(VGP_ppc32_linux) || defined(VGP_ppc32_aix5)
415    Addr lr = startRegs->misc.PPC32.r_lr;
416 #  elif defined(VGP_ppc64_linux) || defined(VGP_ppc64_aix5)
417    Addr lr = startRegs->misc.PPC64.r_lr;
418 #  endif
419    Addr fp_min = sp;
420
421    /* Snaffle IPs from the client's stack into ips[0 .. max_n_ips-1],
422       stopping when the trail goes cold, which we guess to be
423       when FP is not a reasonable stack location. */
424
425    // JRS 2002-sep-17: hack, to round up fp_max to the end of the
426    // current page, at least.  Dunno if it helps.
427    // NJN 2002-sep-17: seems to -- stack traces look like 1.0.X again
428    fp_max = VG_PGROUNDUP(fp_max_orig);
429    if (fp_max >= sizeof(Addr))
430       fp_max -= sizeof(Addr);
431
432    if (debug)
433       VG_(printf)("max_n_ips=%d fp_min=0x%lx fp_max_orig=0x%lx, "
434                   "fp_max=0x%lx ip=0x%lx fp=0x%lx\n",
435                   max_n_ips, fp_min, fp_max_orig, fp_max, ip, fp);
436
437    /* Assertion broken before main() is reached in pthreaded programs;  the
438     * offending stack traces only have one item.  --njn, 2002-aug-16 */
439    /* vg_assert(fp_min <= fp_max);*/
440    if (fp_min + 512 >= fp_max) {
441       /* If the stack limits look bogus, don't poke around ... but
442          don't bomb out either. */
443       if (sps) sps[0] = sp;
444       if (fps) fps[0] = fp;
445       ips[0] = ip;
446       return 1;
447    } 
448
449    /* fp is %r1.  ip is %cia.  Note, ppc uses r1 as both the stack and
450       frame pointers. */
451
452 #  if defined(VGP_ppc64_linux) || defined(VGP_ppc64_aix5)
453    redir_stack_size = VEX_GUEST_PPC64_REDIR_STACK_SIZE;
454    redirs_used      = 0;
455 #  elif defined(VGP_ppc32_aix5)
456    redir_stack_size = VEX_GUEST_PPC32_REDIR_STACK_SIZE;
457    redirs_used      = 0;
458 #  endif
459
460 #  if defined(VG_PLAT_USES_PPCTOC)
461    /* Deal with bogus LR values caused by function
462       interception/wrapping on ppc-TOC platforms; see comment on
463       similar code a few lines further down. */
464    if (ULong_to_Ptr(lr) == (void*)&VG_(ppctoc_magic_redirect_return_stub)
465        && VG_(is_valid_tid)(tid_if_known)) {
466       Word hsp = VG_(threads)[tid_if_known].arch.vex.guest_REDIR_SP;
467       redirs_used++;
468       if (hsp >= 1 && hsp < redir_stack_size)
469          lr = VG_(threads)[tid_if_known]
470                  .arch.vex.guest_REDIR_STACK[hsp-1];
471    }
472 #  endif
473
474    /* We have to determine whether or not LR currently holds this fn
475       (call it F)'s return address.  It might not if F has previously
476       called some other function, hence overwriting LR with a pointer
477       to some part of F.  Hence if LR and IP point to the same
478       function then we conclude LR does not hold this function's
479       return address; instead the LR at entry must have been saved in
480       the stack by F's prologue and so we must get it from there
481       instead.  Note all this guff only applies to the innermost
482       frame. */
483    lr_is_first_RA = False;
484    {
485 #     define M_VG_ERRTXT 1000
486       UChar buf_lr[M_VG_ERRTXT], buf_ip[M_VG_ERRTXT];
487       /* The following conditional looks grossly inefficient and
488          surely could be majorly improved, with not much effort. */
489       if (VG_(get_fnname_raw) (lr, buf_lr, M_VG_ERRTXT))
490          if (VG_(get_fnname_raw) (ip, buf_ip, M_VG_ERRTXT))
491             if (VG_(strncmp)(buf_lr, buf_ip, M_VG_ERRTXT))
492                lr_is_first_RA = True;
493 #     undef M_VG_ERRTXT
494    }
495
496    if (sps) sps[0] = fp; /* NB. not sp */
497    if (fps) fps[0] = fp;
498    ips[0] = ip;
499    i = 1;
500
501    if (fp_min <= fp && fp < fp_max-VG_WORDSIZE+1) {
502
503       /* initial FP is sane; keep going */
504       fp = (((UWord*)fp)[0]);
505
506       while (True) {
507
508         /* On ppc64-linux (ppc64-elf, really), and on AIX, the lr save
509            slot is 2 words back from sp, whereas on ppc32-elf(?) it's
510            only one word back. */
511 #        if defined(VG_PLAT_USES_PPCTOC)
512          const Int lr_offset = 2;
513 #        else
514          const Int lr_offset = 1;
515 #        endif
516
517          if (i >= max_n_ips)
518             break;
519
520          /* Try to derive a new (ip,fp) pair from the current set. */
521
522          if (fp_min <= fp && fp <= fp_max - lr_offset * sizeof(UWord)) {
523             /* fp looks sane, so use it. */
524
525             if (i == 1 && lr_is_first_RA)
526                ip = lr;
527             else
528                ip = (((UWord*)fp)[lr_offset]);
529
530 #           if defined(VG_PLAT_USES_PPCTOC)
531             /* Nasty hack to do with function replacement/wrapping on
532                ppc64-linux/ppc64-aix/ppc32-aix.  If LR points to our
533                magic return stub, then we are in a wrapped or
534                intercepted function, in which LR has been messed with.
535                The original LR will have been pushed onto the thread's
536                hidden REDIR stack one down from the top (top element
537                is the saved R2) and so we should restore the value
538                from there instead.  Since nested redirections can and
539                do happen, we keep track of the number of nested LRs
540                used by the unwinding so far with 'redirs_used'. */
541             if (ip == (Addr)&VG_(ppctoc_magic_redirect_return_stub)
542                 && VG_(is_valid_tid)(tid_if_known)) {
543                Word hsp = VG_(threads)[tid_if_known]
544                              .arch.vex.guest_REDIR_SP;
545                hsp -= 2 * redirs_used;
546                redirs_used ++;
547                if (hsp >= 1 && hsp < redir_stack_size)
548                   ip = VG_(threads)[tid_if_known]
549                           .arch.vex.guest_REDIR_STACK[hsp-1];
550             }
551 #           endif
552
553             if (0 == ip || 1 == ip) break;
554             if (sps) sps[i] = fp; /* NB. not sp */
555             if (fps) fps[i] = fp;
556             fp = (((UWord*)fp)[0]);
557             ips[i++] = ip - 1; /* -1: refer to calling insn, not the RA */
558             if (debug)
559                VG_(printf)("     ipsF[%d]=%#08lx\n", i-1, ips[i-1]);
560             ip = ip - 1; /* ip is probably dead at this point, but
561                             play safe, a la x86/amd64 above.  See
562                             extensive comments above. */
563             continue;
564          }
565
566          /* No luck there.  We have to give up. */
567          break;
568       }
569    }
570
571    n_found = i;
572    return n_found;
573 }
574
575 #endif
576
577 /* ------------------------ arm ------------------------- */
578
579 #if defined(VGP_arm_linux)
580
581 UInt VG_(get_StackTrace_wrk) ( ThreadId tid_if_known,
582                                /*OUT*/Addr* ips, UInt max_n_ips,
583                                /*OUT*/Addr* sps, /*OUT*/Addr* fps,
584                                UnwindStartRegs* startRegs,
585                                Addr fp_max_orig )
586 {
587    Bool  debug = False;
588    Int   i;
589    Addr  fp_max;
590    UInt  n_found = 0;
591
592    vg_assert(sizeof(Addr) == sizeof(UWord));
593    vg_assert(sizeof(Addr) == sizeof(void*));
594
595    D3UnwindRegs uregs;
596    uregs.r15 = startRegs->r_pc;
597    uregs.r14 = startRegs->misc.ARM.r14;
598    uregs.r13 = startRegs->r_sp;
599    uregs.r12 = startRegs->misc.ARM.r12;
600    uregs.r11 = startRegs->misc.ARM.r11;
601    Addr fp_min = uregs.r13;
602
603    /* Snaffle IPs from the client's stack into ips[0 .. max_n_ips-1],
604       stopping when the trail goes cold, which we guess to be
605       when FP is not a reasonable stack location. */
606
607    // JRS 2002-sep-17: hack, to round up fp_max to the end of the
608    // current page, at least.  Dunno if it helps.
609    // NJN 2002-sep-17: seems to -- stack traces look like 1.0.X again
610    fp_max = VG_PGROUNDUP(fp_max_orig);
611    if (fp_max >= sizeof(Addr))
612       fp_max -= sizeof(Addr);
613
614    if (debug)
615       VG_(printf)("max_n_ips=%d fp_min=0x%lx fp_max_orig=0x%lx, "
616                   "fp_max=0x%lx r15=0x%lx r13=0x%lx\n",
617                   max_n_ips, fp_min, fp_max_orig, fp_max,
618                   uregs.r15, uregs.r13);
619
620    /* Assertion broken before main() is reached in pthreaded programs;  the
621     * offending stack traces only have one item.  --njn, 2002-aug-16 */
622    /* vg_assert(fp_min <= fp_max);*/
623    // On Darwin, this kicks in for pthread-related stack traces, so they're
624    // only 1 entry long which is wrong.
625    if (fp_min + 512 >= fp_max) {
626       /* If the stack limits look bogus, don't poke around ... but
627          don't bomb out either. */
628       if (sps) sps[0] = uregs.r13;
629       if (fps) fps[0] = 0;
630       ips[0] = uregs.r15;
631       return 1;
632    } 
633
634    /* */
635
636    if (sps) sps[0] = uregs.r13;
637    if (fps) fps[0] = 0;
638    ips[0] = uregs.r15;
639    i = 1;
640
641    /* Loop unwinding the stack. */
642
643    while (True) {
644       if (debug) {
645          VG_(printf)("i: %d, r15: 0x%lx, r13: 0x%lx\n",
646                      i, uregs.r15, uregs.r13);
647       }
648
649       if (i >= max_n_ips)
650          break;
651
652       if (VG_(use_CF_info)( &uregs, fp_min, fp_max )) {
653          if (sps) sps[i] = uregs.r13;
654          if (fps) fps[i] = 0;
655          ips[i++] = uregs.r15 -1;
656          if (debug)
657             VG_(printf)("USING CFI: r15: 0x%lx, r13: 0x%lx\n",
658                         uregs.r15, uregs.r13);
659          uregs.r15 = uregs.r15 - 1;
660          continue;
661       }
662       /* No luck.  We have to give up. */
663       break;
664    }
665
666    n_found = i;
667    return n_found;
668 }
669
670 #endif
671
672 /*------------------------------------------------------------*/
673 /*---                                                      ---*/
674 /*--- END platform-dependent unwinder worker functions     ---*/
675 /*---                                                      ---*/
676 /*------------------------------------------------------------*/
677
678 /*------------------------------------------------------------*/
679 /*--- Exported functions.                                  ---*/
680 /*------------------------------------------------------------*/
681
682 UInt VG_(get_StackTrace) ( ThreadId tid, 
683                            /*OUT*/StackTrace ips, UInt max_n_ips,
684                            /*OUT*/StackTrace sps,
685                            /*OUT*/StackTrace fps,
686                            Word first_ip_delta )
687 {
688    /* Get the register values with which to start the unwind. */
689    UnwindStartRegs startRegs;
690    VG_(memset)( &startRegs, 0, sizeof(startRegs) );
691    VG_(get_UnwindStartRegs)( &startRegs, tid );
692
693    Addr stack_highest_word = VG_(threads)[tid].client_stack_highest_word;
694    Addr stack_lowest_word  = 0;
695
696 #  if defined(VGP_x86_linux)
697    /* Nasty little hack to deal with syscalls - if libc is using its
698       _dl_sysinfo_int80 function for syscalls (the TLS version does),
699       then ip will always appear to be in that function when doing a
700       syscall, not the actual libc function doing the syscall.  This
701       check sees if IP is within that function, and pops the return
702       address off the stack so that ip is placed within the library
703       function calling the syscall.  This makes stack backtraces much
704       more useful.
705
706       The function is assumed to look like this (from glibc-2.3.6 sources):
707          _dl_sysinfo_int80:
708             int $0x80
709             ret
710       That is 3 (2+1) bytes long.  We could be more thorough and check
711       the 3 bytes of the function are as expected, but I can't be
712       bothered.
713    */
714    if (VG_(client__dl_sysinfo_int80) != 0 /* we know its address */
715        && startRegs.r_pc >= VG_(client__dl_sysinfo_int80)
716        && startRegs.r_pc < VG_(client__dl_sysinfo_int80)+3
717        && VG_(am_is_valid_for_client)(startRegs.r_pc, sizeof(Addr),
718                                       VKI_PROT_READ)) {
719       startRegs.r_pc  = (ULong) *(Addr*)(UWord)startRegs.r_sp;
720       startRegs.r_sp += (ULong) sizeof(Addr);
721    }
722 #  endif
723
724    /* See if we can get a better idea of the stack limits */
725    VG_(stack_limits)( (Addr)startRegs.r_sp,
726                       &stack_lowest_word, &stack_highest_word );
727
728    /* Take into account the first_ip_delta. */
729    startRegs.r_pc += (Long)(Word)first_ip_delta;
730
731    if (0)
732       VG_(printf)("tid %d: stack_highest=0x%08lx ip=0x%010llx "
733                   "sp=0x%010llx\n",
734                   tid, stack_highest_word,
735                   startRegs.r_pc, startRegs.r_sp);
736
737    return VG_(get_StackTrace_wrk)(tid, ips, max_n_ips, 
738                                        sps, fps,
739                                        &startRegs,
740                                        stack_highest_word);
741 }
742
743 static void printIpDesc(UInt n, Addr ip, void* uu_opaque)
744 {
745    #define BUF_LEN   4096
746    
747    static UChar buf[BUF_LEN];
748
749    VG_(describe_IP)(ip, buf, BUF_LEN);
750
751    if (VG_(clo_xml)) {
752       VG_(printf_xml)("    %s\n", buf);
753    } else {
754       VG_(message)(Vg_UserMsg, "   %s %s\n", ( n == 0 ? "at" : "by" ), buf);
755    }
756 }
757
758 /* Print a StackTrace. */
759 void VG_(pp_StackTrace) ( StackTrace ips, UInt n_ips )
760 {
761    vg_assert( n_ips > 0 );
762
763    if (VG_(clo_xml))
764       VG_(printf_xml)("  <stack>\n");
765
766    VG_(apply_StackTrace)( printIpDesc, NULL, ips, n_ips );
767
768    if (VG_(clo_xml))
769       VG_(printf_xml)("  </stack>\n");
770 }
771
772 /* Get and immediately print a StackTrace. */
773 void VG_(get_and_pp_StackTrace) ( ThreadId tid, UInt max_n_ips )
774 {
775    Addr ips[max_n_ips];
776    UInt n_ips
777       = VG_(get_StackTrace)(tid, ips, max_n_ips,
778                             NULL/*array to dump SP values in*/,
779                             NULL/*array to dump FP values in*/,
780                             0/*first_ip_delta*/);
781    VG_(pp_StackTrace)(ips, n_ips);
782 }
783
784 void VG_(apply_StackTrace)(
785         void(*action)(UInt n, Addr ip, void* opaque),
786         void* opaque,
787         StackTrace ips, UInt n_ips
788      )
789 {
790    Bool main_done = False;
791    Int i = 0;
792
793    vg_assert(n_ips > 0);
794    do {
795       Addr ip = ips[i];
796
797       // Stop after the first appearance of "main" or one of the other names
798       // (the appearance of which is a pretty good sign that we've gone past
799       // main without seeing it, for whatever reason)
800       if ( ! VG_(clo_show_below_main) ) {
801          Vg_FnNameKind kind = VG_(get_fnname_kind_from_IP)(ip);
802          if (Vg_FnNameMain == kind || Vg_FnNameBelowMain == kind) {
803             main_done = True;
804          }
805       }
806
807       // Act on the ip
808       action(i, ip, opaque);
809
810       i++;
811    } while (i < n_ips && !main_done);
812
813    #undef MYBUF_LEN
814 }
815
816
817 /*--------------------------------------------------------------------*/
818 /*--- end                                                          ---*/
819 /*--------------------------------------------------------------------*/