2 * Copyright (c) 2013 Luca Clementi <luca.clementi@gmail.com>
3 * Copyright (c) 2013-2018 The strace developers.
5 * SPDX-License-Identifier: LGPL-2.1-or-later
11 #include "mmap_cache.h"
12 #include <libunwind-ptrace.h>
14 static unw_addr_space_t libunwind_as;
21 libunwind_as = unw_create_addr_space(&_UPT_accessors, 0);
23 error_msg_and_die("failed to create address space"
24 " for stack tracing");
25 unw_set_caching_policy(libunwind_as, UNW_CACHE_GLOBAL);
29 tcb_init(struct tcb *tcp)
31 void *r = _UPT_create(tcp->pid);
34 perror_msg_and_die("_UPT_create");
39 tcb_fin(struct tcb *tcp)
41 _UPT_destroy(tcp->unwind_ctx);
45 get_symbol_name(unw_cursor_t *cursor, char **name,
46 size_t *size, unw_word_t *offset)
49 int rc = unw_get_proc_name(cursor, *name, *size, offset);
53 if (rc != -UNW_ENOMEM) {
58 *name = xgrowarray(*name, size, 1);
63 print_stack_frame(struct tcb *tcp,
64 unwind_call_action_fn call_action,
65 unwind_error_action_fn error_action,
69 size_t *symbol_name_size)
73 if (unw_get_reg(cursor, UNW_REG_IP, &ip) < 0) {
74 perror_msg("cannot walk the stack of process %d", tcp->pid);
78 struct mmap_cache_entry_t *entry = mmap_cache_search(tcp, ip);
81 /* ignore mappings that have no PROT_EXEC bit set */
82 && (entry->protections & MMAP_CACHE_PROT_EXECUTABLE)) {
83 unw_word_t function_offset;
85 get_symbol_name(cursor, symbol_name, symbol_name_size,
87 unsigned long true_offset =
88 ip - entry->start_addr + entry->mmap_offset;
90 entry->binary_filename,
99 * there is a bug in libunwind >= 1.0
100 * after a set_tid_address syscall
101 * unw_get_reg returns IP == 0
104 error_action(data, "unexpected_backtracing_error", ip);
109 walk(struct tcb *tcp,
110 unwind_call_action_fn call_action,
111 unwind_error_action_fn error_action,
115 size_t symbol_name_size = 40;
119 if (!tcp->mmap_cache)
120 error_func_msg_and_die("mmap_cache is NULL");
122 symbol_name = xmalloc(symbol_name_size);
124 if (unw_init_remote(&cursor, libunwind_as, tcp->unwind_ctx) < 0)
125 perror_func_msg_and_die("cannot initialize libunwind");
127 for (stack_depth = 0; stack_depth < 256; ++stack_depth) {
128 if (print_stack_frame(tcp, call_action, error_action, data,
129 &cursor, &symbol_name, &symbol_name_size) < 0)
131 if (unw_step(&cursor) <= 0)
134 if (stack_depth >= 256)
135 error_action(data, "too many stack frames", 0);
141 tcb_walk(struct tcb *tcp,
142 unwind_call_action_fn call_action,
143 unwind_error_action_fn error_action,
146 switch (mmap_cache_rebuild_if_invalid(tcp, __func__)) {
147 case MMAP_CACHE_REBUILD_RENEWED:
149 * Rebuild the unwinder internal cache.
150 * Called when mmap cache subsystem detects a
151 * change of tracee memory mapping.
153 unw_flush_cache(libunwind_as, 0, 0);
154 ATTRIBUTE_FALLTHROUGH;
155 case MMAP_CACHE_REBUILD_READY:
156 walk(tcp, call_action, error_action, data);
164 const struct unwind_unwinder_t unwinder = {
167 .tcb_init = tcb_init,
169 .tcb_walk = tcb_walk,