1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Corkscrew"
18//#define LOG_NDEBUG 0
19
20#include "backtrace-arch.h"
21#include "backtrace-helper.h"
22#include "ptrace-arch.h"
23#include <corkscrew/map_info.h>
24#include <corkscrew/symbol_table.h>
25#include <corkscrew/ptrace.h>
26#include <corkscrew/demangle.h>
27
28#include <unistd.h>
29#include <signal.h>
30#include <stdlib.h>
31#include <string.h>
32#include <pthread.h>
33#include <unwind.h>
34#include <cutils/log.h>
35#include <cutils/atomic.h>
36#include <elf.h>
37
38#if HAVE_DLADDR
39#define __USE_GNU // For dladdr(3) in glibc.
40#include <dlfcn.h>
41#endif
42
43#if defined(__BIONIC__)
44
45// Bionic implements and exports gettid but only implements tgkill.
46extern int tgkill(int tgid, int tid, int sig);
47
48#else
49
50// glibc doesn't implement or export either gettid or tgkill.
51
52#include <unistd.h>
53#include <sys/syscall.h>
54
55static pid_t gettid() {
56  return syscall(__NR_gettid);
57}
58
59static int tgkill(int tgid, int tid, int sig) {
60  return syscall(__NR_tgkill, tgid, tid, sig);
61}
62
63#endif
64
65typedef struct {
66    backtrace_frame_t* backtrace;
67    size_t ignore_depth;
68    size_t max_depth;
69    size_t ignored_frames;
70    size_t returned_frames;
71    memory_t memory;
72} backtrace_state_t;
73
74static _Unwind_Reason_Code unwind_backtrace_callback(struct _Unwind_Context* context, void* arg) {
75    backtrace_state_t* state = (backtrace_state_t*)arg;
76    uintptr_t pc = _Unwind_GetIP(context);
77    if (pc) {
78        // TODO: Get information about the stack layout from the _Unwind_Context.
79        //       This will require a new architecture-specific function to query
80        //       the appropriate registers.  Current callers of unwind_backtrace
81        //       don't need this information, so we won't bother collecting it just yet.
82        add_backtrace_entry(rewind_pc_arch(&state->memory, pc), state->backtrace,
83                state->ignore_depth, state->max_depth,
84                &state->ignored_frames, &state->returned_frames);
85    }
86    return state->returned_frames < state->max_depth ? _URC_NO_REASON : _URC_END_OF_STACK;
87}
88
89ssize_t unwind_backtrace(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
90    ALOGV("Unwinding current thread %d.", gettid());
91
92    map_info_t* milist = acquire_my_map_info_list();
93
94    backtrace_state_t state;
95    state.backtrace = backtrace;
96    state.ignore_depth = ignore_depth;
97    state.max_depth = max_depth;
98    state.ignored_frames = 0;
99    state.returned_frames = 0;
100    init_memory(&state.memory, milist);
101
102    _Unwind_Reason_Code rc =_Unwind_Backtrace(unwind_backtrace_callback, &state);
103
104    release_my_map_info_list(milist);
105
106    if (state.returned_frames) {
107        return state.returned_frames;
108    }
109    return rc == _URC_END_OF_STACK ? 0 : -1;
110}
111
112#ifdef CORKSCREW_HAVE_ARCH
113static const int32_t STATE_DUMPING = -1;
114static const int32_t STATE_DONE = -2;
115static const int32_t STATE_CANCEL = -3;
116
117static pthread_mutex_t g_unwind_signal_mutex = PTHREAD_MUTEX_INITIALIZER;
118static volatile struct {
119    int32_t tid_state;
120    const map_info_t* map_info_list;
121    backtrace_frame_t* backtrace;
122    size_t ignore_depth;
123    size_t max_depth;
124    size_t returned_frames;
125} g_unwind_signal_state;
126
127static void unwind_backtrace_thread_signal_handler(int n __attribute__((unused)), siginfo_t* siginfo, void* sigcontext) {
128    if (!android_atomic_acquire_cas(gettid(), STATE_DUMPING, &g_unwind_signal_state.tid_state)) {
129        g_unwind_signal_state.returned_frames = unwind_backtrace_signal_arch(
130                siginfo, sigcontext,
131                g_unwind_signal_state.map_info_list,
132                g_unwind_signal_state.backtrace,
133                g_unwind_signal_state.ignore_depth,
134                g_unwind_signal_state.max_depth);
135        android_atomic_release_store(STATE_DONE, &g_unwind_signal_state.tid_state);
136    } else {
137        ALOGV("Received spurious SIGURG on thread %d that was intended for thread %d.",
138                gettid(), android_atomic_acquire_load(&g_unwind_signal_state.tid_state));
139    }
140}
141#endif
142
143ssize_t unwind_backtrace_thread(pid_t tid, backtrace_frame_t* backtrace,
144        size_t ignore_depth, size_t max_depth) {
145    if (tid == gettid()) {
146        return unwind_backtrace(backtrace, ignore_depth + 1, max_depth);
147    }
148
149    ALOGV("Unwinding thread %d from thread %d.", tid, gettid());
150
151#ifdef CORKSCREW_HAVE_ARCH
152    struct sigaction act;
153    struct sigaction oact;
154    memset(&act, 0, sizeof(act));
155    act.sa_sigaction = unwind_backtrace_thread_signal_handler;
156    act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
157    sigemptyset(&act.sa_mask);
158
159    pthread_mutex_lock(&g_unwind_signal_mutex);
160    map_info_t* milist = acquire_my_map_info_list();
161
162    ssize_t frames = -1;
163    if (!sigaction(SIGURG, &act, &oact)) {
164        g_unwind_signal_state.map_info_list = milist;
165        g_unwind_signal_state.backtrace = backtrace;
166        g_unwind_signal_state.ignore_depth = ignore_depth;
167        g_unwind_signal_state.max_depth = max_depth;
168        g_unwind_signal_state.returned_frames = 0;
169        android_atomic_release_store(tid, &g_unwind_signal_state.tid_state);
170
171        // Signal the specific thread that we want to dump.
172        int32_t tid_state = tid;
173        if (tgkill(getpid(), tid, SIGURG)) {
174            ALOGV("Failed to send SIGURG to thread %d.", tid);
175        } else {
176            // Wait for the other thread to start dumping the stack, or time out.
177            int wait_millis = 250;
178            for (;;) {
179                tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
180                if (tid_state != tid) {
181                    break;
182                }
183                if (wait_millis--) {
184                    ALOGV("Waiting for thread %d to start dumping the stack...", tid);
185                    usleep(1000);
186                } else {
187                    ALOGV("Timed out waiting for thread %d to start dumping the stack.", tid);
188                    break;
189                }
190            }
191        }
192
193        // Try to cancel the dump if it has not started yet.
194        if (tid_state == tid) {
195            if (!android_atomic_acquire_cas(tid, STATE_CANCEL, &g_unwind_signal_state.tid_state)) {
196                ALOGV("Canceled thread %d stack dump.", tid);
197                tid_state = STATE_CANCEL;
198            } else {
199                tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
200            }
201        }
202
203        // Wait indefinitely for the dump to finish or be canceled.
204        // We cannot apply a timeout here because the other thread is accessing state that
205        // is owned by this thread, such as milist.  It should not take very
206        // long to take the dump once started.
207        while (tid_state == STATE_DUMPING) {
208            ALOGV("Waiting for thread %d to finish dumping the stack...", tid);
209            usleep(1000);
210            tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
211        }
212
213        if (tid_state == STATE_DONE) {
214            frames = g_unwind_signal_state.returned_frames;
215        }
216
217        sigaction(SIGURG, &oact, NULL);
218    }
219
220    release_my_map_info_list(milist);
221    pthread_mutex_unlock(&g_unwind_signal_mutex);
222    return frames;
223#else
224    return -1;
225#endif
226}
227
228ssize_t unwind_backtrace_ptrace(pid_t tid, const ptrace_context_t* context,
229        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
230#ifdef CORKSCREW_HAVE_ARCH
231    return unwind_backtrace_ptrace_arch(tid, context, backtrace, ignore_depth, max_depth);
232#else
233    return -1;
234#endif
235}
236
237static void init_backtrace_symbol(backtrace_symbol_t* symbol, uintptr_t pc) {
238    symbol->relative_pc = pc;
239    symbol->relative_symbol_addr = 0;
240    symbol->map_name = NULL;
241    symbol->symbol_name = NULL;
242    symbol->demangled_name = NULL;
243}
244
245void get_backtrace_symbols(const backtrace_frame_t* backtrace, size_t frames,
246        backtrace_symbol_t* backtrace_symbols) {
247    map_info_t* milist = acquire_my_map_info_list();
248    for (size_t i = 0; i < frames; i++) {
249        const backtrace_frame_t* frame = &backtrace[i];
250        backtrace_symbol_t* symbol = &backtrace_symbols[i];
251        init_backtrace_symbol(symbol, frame->absolute_pc);
252
253        const map_info_t* mi = find_map_info(milist, frame->absolute_pc);
254        if (mi) {
255            symbol->relative_pc = frame->absolute_pc - mi->start;
256            if (mi->name[0]) {
257                symbol->map_name = strdup(mi->name);
258            }
259#if HAVE_DLADDR
260            Dl_info info;
261            if (dladdr((const void*)frame->absolute_pc, &info) && info.dli_sname) {
262                symbol->relative_symbol_addr = (uintptr_t)info.dli_saddr
263                        - (uintptr_t)info.dli_fbase;
264                symbol->symbol_name = strdup(info.dli_sname);
265                symbol->demangled_name = demangle_symbol_name(symbol->symbol_name);
266            }
267#endif
268        }
269    }
270    release_my_map_info_list(milist);
271}
272
273void get_backtrace_symbols_ptrace(const ptrace_context_t* context,
274        const backtrace_frame_t* backtrace, size_t frames,
275        backtrace_symbol_t* backtrace_symbols) {
276    for (size_t i = 0; i < frames; i++) {
277        const backtrace_frame_t* frame = &backtrace[i];
278        backtrace_symbol_t* symbol = &backtrace_symbols[i];
279        init_backtrace_symbol(symbol, frame->absolute_pc);
280
281        const map_info_t* mi;
282        const symbol_t* s;
283        find_symbol_ptrace(context, frame->absolute_pc, &mi, &s);
284        if (mi) {
285            symbol->relative_pc = frame->absolute_pc - mi->start;
286            if (mi->name[0]) {
287                symbol->map_name = strdup(mi->name);
288            }
289        }
290        if (s) {
291            symbol->relative_symbol_addr = s->start;
292            symbol->symbol_name = strdup(s->name);
293            symbol->demangled_name = demangle_symbol_name(symbol->symbol_name);
294        }
295    }
296}
297
298void free_backtrace_symbols(backtrace_symbol_t* backtrace_symbols, size_t frames) {
299    for (size_t i = 0; i < frames; i++) {
300        backtrace_symbol_t* symbol = &backtrace_symbols[i];
301        free(symbol->map_name);
302        free(symbol->symbol_name);
303        free(symbol->demangled_name);
304        init_backtrace_symbol(symbol, 0);
305    }
306}
307
308void format_backtrace_line(unsigned frameNumber, const backtrace_frame_t* frame __attribute__((unused)),
309        const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize) {
310    const char* mapName = symbol->map_name ? symbol->map_name : "<unknown>";
311    const char* symbolName = symbol->demangled_name ? symbol->demangled_name : symbol->symbol_name;
312    size_t fieldWidth = (bufferSize - 80) / 2;
313    if (symbolName) {
314        uint32_t pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
315        if (pc_offset) {
316            snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s (%.*s+%u)",
317                    frameNumber, symbol->relative_pc, fieldWidth, mapName,
318                    fieldWidth, symbolName, pc_offset);
319        } else {
320            snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s (%.*s)",
321                    frameNumber, symbol->relative_pc, fieldWidth, mapName,
322                    fieldWidth, symbolName);
323        }
324    } else {
325        snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s",
326                frameNumber, symbol->relative_pc, fieldWidth, mapName);
327    }
328}
329