Improve stack unwinder robustness.

Keep track of whether memory maps are readable.  Use the information
in try_get_word to try to avoid accidentally dereferencing an invalid
pointer within the current process.  (Note that I haven't ever
seen that happen during normal unwinding, but it pays to be
a little more careful.)

Refactored try_get_word a little to make it easier to pass it the
needed state for validation checks by way of a little memory_t struct.

Improved how the memory map for the current process is cached.  This is
important because we need up to date information about readable maps.
Use a 5 second cache expiration.

Improved the PC -> LR fallback logic in the unwinder so we can
eke out an extra frame sometimes.

Fixed a bug reading ELF program headers.  The phnum & phentsize
fields are half-words.  We were incorrectly interpreting
phnum as a whole word.

Used android_atomic_* operations carefully in the unwinder
to prevent possible memory races between the dumper and the dumpee.
This was highly unlikely (or even impossible due to the presence
of other barriers along the way) but the code is clearer now about
its invariants.

Fixed a bug in debuggerd where the pid was being passed to have
its stack dump taken instead of the tid, resulting in short
stacks because ptrace couldn't read the data if pid != tid.
Did a full sweep to ensure that we use pid / tid correctly everywhere.

Ported old code from debuggerd to rewind the program counter back
one instruction so that it points to the branch instruction itself
instead of the return address.

Change-Id: Icc4eb08320052975a4ae7f0f5f0ac9308a2d33d7
diff --git a/libcorkscrew/backtrace.c b/libcorkscrew/backtrace.c
index b03c43f..f9a49ec 100644
--- a/libcorkscrew/backtrace.c
+++ b/libcorkscrew/backtrace.c
@@ -31,6 +31,7 @@
 #include <unwind.h>
 #include <sys/exec_elf.h>
 #include <cutils/log.h>
+#include <cutils/atomic.h>
 
 #if HAVE_DLADDR
 #include <dlfcn.h>
@@ -42,6 +43,7 @@
     size_t max_depth;
     size_t ignored_frames;
     size_t returned_frames;
+    memory_t memory;
 } backtrace_state_t;
 
 static _Unwind_Reason_Code unwind_backtrace_callback(struct _Unwind_Context* context, void* arg) {
@@ -52,7 +54,7 @@
         //       This will require a new architecture-specific function to query
         //       the appropriate registers.  Current callers of unwind_backtrace
         //       don't need this information, so we won't bother collecting it just yet.
-        add_backtrace_entry(pc, state->backtrace,
+        add_backtrace_entry(rewind_pc_arch(&state->memory, pc), state->backtrace,
                 state->ignore_depth, state->max_depth,
                 &state->ignored_frames, &state->returned_frames);
     }
@@ -60,14 +62,22 @@
 }
 
 ssize_t unwind_backtrace(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    ALOGV("Unwinding current thread %d.", gettid());
+
+    map_info_t* milist = acquire_my_map_info_list();
+
     backtrace_state_t state;
     state.backtrace = backtrace;
     state.ignore_depth = ignore_depth;
     state.max_depth = max_depth;
     state.ignored_frames = 0;
     state.returned_frames = 0;
+    init_memory(&state.memory, milist);
 
     _Unwind_Reason_Code rc =_Unwind_Backtrace(unwind_backtrace_callback, &state);
+
+    release_my_map_info_list(milist);
+
     if (state.returned_frames) {
         return state.returned_frames;
     }
@@ -77,28 +87,39 @@
 #ifdef CORKSCREW_HAVE_ARCH
 static pthread_mutex_t g_unwind_signal_mutex = PTHREAD_MUTEX_INITIALIZER;
 static volatile struct {
+    int32_t tid;
+    const map_info_t* map_info_list;
     backtrace_frame_t* backtrace;
     size_t ignore_depth;
     size_t max_depth;
     size_t returned_frames;
-    bool done;
 } g_unwind_signal_state;
 
 static void unwind_backtrace_thread_signal_handler(int n, siginfo_t* siginfo, void* sigcontext) {
-    backtrace_frame_t* backtrace = g_unwind_signal_state.backtrace;
-    if (backtrace) {
-        g_unwind_signal_state.backtrace = NULL;
+    int32_t tid = android_atomic_acquire_load(&g_unwind_signal_state.tid);
+    if (tid == gettid()) {
         g_unwind_signal_state.returned_frames = unwind_backtrace_signal_arch(
-                siginfo, sigcontext, backtrace,
+                siginfo, sigcontext,
+                g_unwind_signal_state.map_info_list,
+                g_unwind_signal_state.backtrace,
                 g_unwind_signal_state.ignore_depth,
                 g_unwind_signal_state.max_depth);
-        g_unwind_signal_state.done = true;
+        android_atomic_release_store(-1, &g_unwind_signal_state.tid);
+    } else {
+        ALOGV("Received spurious SIGURG on thread %d that was intended for thread %d.",
+                gettid(), tid);
     }
 }
 #endif
 
 ssize_t unwind_backtrace_thread(pid_t tid, backtrace_frame_t* backtrace,
         size_t ignore_depth, size_t max_depth) {
+    if (tid == gettid()) {
+        return unwind_backtrace(backtrace, ignore_depth + 1, max_depth);
+    }
+
+    ALOGV("Unwinding thread %d from thread %d.", tid, gettid());
+
 #ifdef CORKSCREW_HAVE_ARCH
     struct sigaction act;
     struct sigaction oact;
@@ -108,26 +129,32 @@
     sigemptyset(&act.sa_mask);
 
     pthread_mutex_lock(&g_unwind_signal_mutex);
-
-    g_unwind_signal_state.backtrace = backtrace;
-    g_unwind_signal_state.ignore_depth = ignore_depth;
-    g_unwind_signal_state.max_depth = max_depth;
-    g_unwind_signal_state.returned_frames = 0;
-    g_unwind_signal_state.done = false;
+    map_info_t* milist = acquire_my_map_info_list();
 
     ssize_t frames = -1;
     if (!sigaction(SIGURG, &act, &oact)) {
-        if (!kill(tid, SIGURG)) {
-            while (!g_unwind_signal_state.done) {
+        g_unwind_signal_state.map_info_list = milist;
+        g_unwind_signal_state.backtrace = backtrace;
+        g_unwind_signal_state.ignore_depth = ignore_depth;
+        g_unwind_signal_state.max_depth = max_depth;
+        g_unwind_signal_state.returned_frames = 0;
+        android_atomic_release_store(tid, &g_unwind_signal_state.tid);
+
+        if (kill(tid, SIGURG)) {
+            ALOGV("Failed to send SIGURG to thread %d.", tid);
+            android_atomic_release_store(-1, &g_unwind_signal_state.tid);
+        } else {
+            while (android_atomic_acquire_load(&g_unwind_signal_state.tid) == tid) {
+                ALOGV("Waiting for response from thread %d...", tid);
                 usleep(1000);
             }
             frames = g_unwind_signal_state.returned_frames;
         }
+
         sigaction(SIGURG, &oact, NULL);
     }
 
-    g_unwind_signal_state.backtrace = NULL;
-
+    release_my_map_info_list(milist);
     pthread_mutex_unlock(&g_unwind_signal_mutex);
     return frames;
 #else
@@ -146,14 +173,14 @@
 
 static void init_backtrace_symbol(backtrace_symbol_t* symbol, uintptr_t pc) {
     symbol->relative_pc = pc;
-    symbol->map_info = NULL;
+    symbol->map_name = NULL;
     symbol->name = NULL;
     symbol->demangled_name = NULL;
 }
 
 void get_backtrace_symbols(const backtrace_frame_t* backtrace, size_t frames,
         backtrace_symbol_t* backtrace_symbols) {
-    const map_info_t* milist = my_map_info_list();
+    map_info_t* milist = acquire_my_map_info_list();
     for (size_t i = 0; i < frames; i++) {
         const backtrace_frame_t* frame = &backtrace[i];
         backtrace_symbol_t* symbol = &backtrace_symbols[i];
@@ -162,16 +189,19 @@
         const map_info_t* mi = find_map_info(milist, frame->absolute_pc);
         if (mi) {
             symbol->relative_pc = frame->absolute_pc - mi->start;
-            symbol->map_info = mi;
+            if (mi->name[0]) {
+                symbol->map_name = strdup(mi->name);
+            }
 #if HAVE_DLADDR
             Dl_info info;
             if (dladdr((const void*)frame->absolute_pc, &info) && info.dli_sname) {
-                symbol->name = info.dli_sname;
+                symbol->name = strdup(info.dli_sname);
                 symbol->demangled_name = demangle_symbol_name(symbol->name);
             }
 #endif
         }
     }
+    release_my_map_info_list(milist);
 }
 
 void get_backtrace_symbols_ptrace(const ptrace_context_t* context,
@@ -187,10 +217,12 @@
         find_symbol_ptrace(context, frame->absolute_pc, &mi, &s);
         if (mi) {
             symbol->relative_pc = frame->absolute_pc - mi->start;
-            symbol->map_info = mi;
+            if (mi->name[0]) {
+                symbol->map_name = strdup(mi->name);
+            }
         }
         if (s) {
-            symbol->name = s->name;
+            symbol->name = strdup(s->name);
             symbol->demangled_name = demangle_symbol_name(symbol->name);
         }
     }
@@ -199,6 +231,8 @@
 void free_backtrace_symbols(backtrace_symbol_t* backtrace_symbols, size_t frames) {
     for (size_t i = 0; i < frames; i++) {
         backtrace_symbol_t* symbol = &backtrace_symbols[i];
+        free(symbol->map_name);
+        free(symbol->name);
         free(symbol->demangled_name);
         init_backtrace_symbol(symbol, 0);
     }