autoupdate
[gnulib.git] / lib / stack-trace-impl.h
blob529afad7a6fb3d127196caa36aeb9e37516f8317
1 /* print_stack_trace() function that prints a stack trace.
2 Copyright (C) 2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #if HAVE_LIBBACKTRACE
19 # include <backtrace.h>
21 static struct backtrace_state *state /* = NULL */;
23 static inline void
24 # if (__GNUC__ >= 3) || (__clang_major__ >= 4)
25 __attribute__ ((always_inline))
26 # endif
27 print_stack_trace_to (FILE *stream)
29 if (state == NULL)
30 state = backtrace_create_state (NULL, 0, NULL, NULL);
31 fprintf (stream, "Stack trace:\n");
32 /* Pass skip=0, to work around <https://github.com/ianlancetaylor/libbacktrace/issues/60>. */
33 backtrace_print (state, 0, stream);
36 #elif HAVE_LIBASAN
38 # include <stdio.h>
40 /* We need only one declaration from <sanitizer/asan_interface.h>. */
41 extern
42 # ifdef __cplusplus
43 "C"
44 # endif
45 void __sanitizer_print_stack_trace (void);
47 /* The only supported stream, in this case, is stderr. */
48 static inline void
49 # if (__GNUC__ >= 3) || (__clang_major__ >= 4)
50 __attribute__ ((always_inline))
51 # endif
52 print_stack_trace_to (FILE *stream)
54 fprintf (stream, "Stack trace:\n");
55 __sanitizer_print_stack_trace ();
58 #elif HAVE_EXECINFO_H
60 # include <stdio.h>
62 # include "execinfo.h"
64 static inline void
65 # if (__GNUC__ >= 3) || (__clang_major__ >= 4)
66 __attribute__ ((always_inline))
67 # endif
68 print_stack_trace_to (FILE *stream)
70 void *buffer[100];
71 int max_size = sizeof (buffer) / sizeof (buffer[0]);
72 int size = backtrace (buffer, max_size);
73 if (size > 0)
75 char **symbols = backtrace_symbols (buffer, size);
76 if (symbols != NULL)
78 int i;
80 fprintf (stream, "Stack trace:\n");
81 for (i = 0; i < size; i++)
82 fprintf (stream, "%s\n", symbols[i]);
83 fflush (stream);
85 free (symbols);
90 #endif