Skip to content

Commit

Permalink
utils: Add stacktrace() for debugging purpose
Browse files Browse the repository at this point in the history
Sometimes it's useful to print backtrace or stacktrace by explicitly
write a request inside source code.

Example output:
  Stack trace:
    #0 uftrace() [0x410093]
    #1 uftrace() [0x410602]
    #2 uftrace() [0x4108e7]
    #3 uftrace(command_report+0x374) [0x411995]
    #4 uftrace(main+0x4f7) [0x40c7c5]
    #5 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f5e346d2830]
    #6 uftrace(_start+0x29) [0x40a0d9]

Some functions do not show their name, but it's because they are static functions.

Signed-off-by: Honggyu Kim <[email protected]>
  • Loading branch information
honggyukim committed Jun 6, 2020
1 parent 08ccc15 commit 188ad37
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ LIB_LDFLAGS = $(COMMON_LDFLAGS) $(LDFLAGS_$@) $(LDFLAGS_lib) -Wl,--no-und
TEST_LDFLAGS = $(COMMON_LDFLAGS) -L$(objdir)/libtraceevent -ltraceevent

ifeq ($(DEBUG), 1)
COMMON_CFLAGS += -O0 -g
COMMON_CFLAGS += -O0 -g -rdynamic
else
COMMON_CFLAGS += -O2 -g
endif
Expand Down
17 changes: 17 additions & 0 deletions utils/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,23 @@ char *absolute_dirname(const char *path, char *resolved_path)
return resolved_path;
}

void dump_stacktrace(void **buffer, int nptrs)
{
int i;
char **strings;

pr_yellow("Stack trace:\n");
strings = backtrace_symbols(buffer, nptrs);
for (i = 0; i < nptrs; i++) {
if (strings)
pr_yellow(" #%d %s\n", i, strings[i]);
else
pr_yellow(" #%d %p\n", i, buffer[i]);
}
pr_yellow("\n");
free(strings);
}

#ifdef UNIT_TEST
TEST_CASE(utils_parse_cmdline)
{
Expand Down
10 changes: 10 additions & 0 deletions utils/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <execinfo.h>

#include "compiler.h"

Expand Down Expand Up @@ -366,4 +367,13 @@ struct uftrace_data;
char *get_event_name(struct uftrace_data *handle, unsigned evt_id);
char *absolute_dirname(const char *path, char *resolved_path);

void dump_stacktrace(void **buffer, int nptrs);

#define stacktrace() \
do { \
void *buffer[64]; \
int nptrs = backtrace(buffer, 64); \
dump_stacktrace(buffer, nptrs); \
} while (0)

#endif /* UFTRACE_UTILS_H */

0 comments on commit 188ad37

Please sign in to comment.