1 /* Return backtrace of current program state.
2 Copyright (C) 1998-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
21 #include <unwind-link.h>
26 struct unwind_link
*unwind_link
;
28 void *lastebp
, *lastesp
;
31 static _Unwind_Reason_Code
32 backtrace_helper (struct _Unwind_Context
*ctx
, void *a
)
34 struct trace_arg
*arg
= a
;
36 /* We are first called with address in the __backtrace function.
40 = (void *) UNWIND_LINK_PTR (arg
->unwind_link
, _Unwind_GetIP
) (ctx
);
41 if (++arg
->cnt
== arg
->size
)
42 return _URC_END_OF_STACK
;
44 /* %ebp is DWARF2 register 5 on IA-32. */
46 = (void *) UNWIND_LINK_PTR (arg
->unwind_link
, _Unwind_GetGR
) (ctx
, 5);
48 = (void *) UNWIND_LINK_PTR (arg
->unwind_link
, _Unwind_GetCFA
) (ctx
);
49 return _URC_NO_REASON
;
53 /* This is a global variable set at program start time. It marks the
54 highest used stack address. */
55 extern void *__libc_stack_end
;
58 /* This is the stack layout we see with every stack frame
59 if not compiled without frame pointer.
61 +-----------------+ +-----------------+
62 %ebp -> | %ebp last frame--------> | %ebp last frame--->...
64 | return address | | return address |
65 +-----------------+ +-----------------+
67 First try as far to get as far as possible using
68 _Unwind_Backtrace which handles -fomit-frame-pointer
69 as well, but requires .eh_frame info. Then fall back to
70 walking the stack manually. */
80 __backtrace (void **array
, int size
)
82 struct trace_arg arg
=
85 .unwind_link
= __libc_unwind_link_get (),
90 if (size
<= 0 || arg
.unwind_link
== NULL
)
93 UNWIND_LINK_PTR (arg
.unwind_link
, _Unwind_Backtrace
)
94 (backtrace_helper
, &arg
);
96 if (arg
.cnt
> 1 && arg
.array
[arg
.cnt
- 1] == NULL
)
98 else if (arg
.cnt
< size
)
100 struct layout
*ebp
= (struct layout
*) arg
.lastebp
;
102 while (arg
.cnt
< size
)
104 /* Check for out of range. */
105 if ((void *) ebp
< arg
.lastesp
|| (void *) ebp
> __libc_stack_end
109 array
[arg
.cnt
++] = ebp
->ret
;
113 return arg
.cnt
!= -1 ? arg
.cnt
: 0;
115 weak_alias (__backtrace
, backtrace
)
116 libc_hidden_def (__backtrace
)