Skip to content

Commit

Permalink
libia2: Replace libc backtrace with libunwind
Browse files Browse the repository at this point in the history
backtrace(3) doesn't support unwinding through PLT stubs so this commit
replaces it with libunwind. Since we want backtraces on by default I'm not sure
if this is exactly what we want but it's good enough for now.
  • Loading branch information
ayrtonm committed Nov 5, 2024
1 parent fa3b731 commit 6f9ac54
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
5 changes: 5 additions & 0 deletions runtime/libia2/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ endif()

target_link_options(libia2
INTERFACE
"-lunwind"
"-pthread"
"-Wl,--wrap=pthread_create"
"-Wl,--wrap=main"
Expand All @@ -29,6 +30,10 @@ target_link_options(libia2
"-Wl,-z,relro"
)

if (LIBIA2_X86_64)
target_link_options(libia2 INTERFACE "-lunwind-x86_64")
endif()

target_link_libraries(libia2 PRIVATE dl)

target_include_directories(libia2 PUBLIC include)
Expand Down
24 changes: 15 additions & 9 deletions runtime/libia2/ia2.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <execinfo.h>
#include <libunwind.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
Expand Down Expand Up @@ -511,15 +511,21 @@ int protect_pages(struct dl_phdr_info *info, size_t size, void *data) {

#if IA2_DEBUG
void ia2_print_backtrace(void) {
#define IA2_BT_SZ 10
void *ra_buf[IA2_BT_SZ];
int num_ra = backtrace(ra_buf, IA2_BT_SZ);
char **fn_names = backtrace_symbols(ra_buf, num_ra);
for (size_t i = 0; i < num_ra; i++) {
if (fn_names) {
fprintf(stderr, "#%d %p in %s ()\n", i, ra_buf[i], fn_names[i]);
unw_cursor_t cursor;
unw_context_t uc;
unw_word_t pc;

unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
int i = 0;
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &pc);
Dl_info dlinf = {0};
bool found = dladdr((void *)pc, &dlinf) != 0;
if (found) {
fprintf(stderr, "#%d %p in %s ()\n", i++, (void *)pc, dlinf.dli_sname);
} else {
fprintf(stderr, "#%d %p ()\n", i, ra_buf[i]);
fprintf(stderr, "#%d %p ()\n", i++, (void *)pc);
}
}
fflush(stderr);
Expand Down

0 comments on commit 6f9ac54

Please sign in to comment.