Update.
[platform/upstream/glibc.git] / sysdeps / generic / backtrace.c
1 /* Return backtrace of current program state.  Generic version.
2    Copyright (C) 1998 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <execinfo.h>
22
23
24 /* This is a global variable set at program start time.  It marks the
25    highest used stack address.  */
26 extern void *__libc_stack_end;
27
28
29 /* This implementation assumes a stack layout that matches the defaults
30    used by gcc's `__builtin_frame_address' and `__builtin_return_address'
31    (FP is the frame pointer register):
32
33           +-----------------+     +-----------------+
34     FP -> | previous FP --------> | previous FP ------>...
35           |                 |     |                 |
36           | return address  |     | return address  |
37           +-----------------+     +-----------------+
38
39   */
40
41 /* Get some notion of the current stack.  Need not be exactly the top
42    of the stack, just something somewhere in the current frame.  */
43 #ifndef CURRENT_STACK_FRAME
44 # define CURRENT_STACK_FRAME  ({ char __csf; &__csf; })
45 #endif
46
47 struct layout
48 {
49   struct layout *next;
50   void *return_address;
51 };
52
53 int
54 __backtrace (array, size)
55      void **array;
56      int size;
57 {
58   struct layout *current;
59   void *top_frame;
60   void *top_stack;
61   int cnt = 0;
62
63   top_frame = __builtin_frame_address (0);
64   top_stack = CURRENT_STACK_FRAME;
65
66   /* We skip the call to this function, it makes no sense to record it.  */
67   current = (struct layout *) top_frame;
68   while (cnt < size)
69     {
70       if ((void *) current < top_stack || (void *) current > __libc_stack_end)
71        /* This means the address is out of range.  Note that for the
72           toplevel we see a frame pointer with value NULL which clearly is
73           out of range.  */
74         break;
75
76       array[cnt++] = current->return_address;
77
78       current = current->next;
79     }
80
81   return cnt;
82 }
83 weak_alias (__backtrace, backtrace)