debuggerd_handler: implement missing fallback functionality.

Allow the fallback implementation to dump traces and create tombstones
in seccomped processes.

Bug: http://b/35858739
Test: debuggerd -b `pidof media.codec`; killall -ABRT media.codec
Change-Id: I381b283de39a66d8900f1c320d32497d6f2b4ec4
(cherry picked from commit e1aa0ca58a2a356039047ffcc8a98d85d1bce8ed)
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index 8d2ea68..af84be9 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -8,17 +8,35 @@
         "-Os",
     ],
 
+    // util.cpp gets async signal safe logging via libc_logging,
+    // which defines its interface in bionic private headers.
+    include_dirs: ["bionic/libc"],
+
     local_include_dirs: ["include"],
 }
 
+// Utility library to tombstoned and get an output fd.
+cc_library_static {
+    name: "libtombstoned_client",
+    defaults: ["debuggerd_defaults"],
+    srcs: [
+        "tombstoned_client.cpp",
+        "util.cpp",
+    ],
+
+    whole_static_libs: [
+        "libc_logging",
+        "libcutils",
+        "libbase",
+    ],
+}
+
+// Core implementation, linked into libdebuggerd_handler and the dynamic linker.
 cc_library_static {
     name: "libdebuggerd_handler_core",
     defaults: ["debuggerd_defaults"],
     srcs: ["handler/debuggerd_handler.cpp"],
 
-    // libdebuggerd_handler gets async signal safe logging via libc_logging,
-    // which defines its interface in bionic private headers.
-    include_dirs: ["bionic/libc"],
     whole_static_libs: [
         "libc_logging",
         "libdebuggerd",
@@ -27,6 +45,7 @@
     export_include_dirs: ["include"],
 }
 
+// Implementation with a no-op fallback.
 cc_library_static {
     name: "libdebuggerd_handler",
     defaults: ["debuggerd_defaults"],
@@ -39,15 +58,18 @@
     export_include_dirs: ["include"],
 }
 
+// Fallback implementation.
 cc_library_static {
     name: "libdebuggerd_handler_fallback",
     defaults: ["debuggerd_defaults"],
-    srcs: ["handler/debuggerd_fallback.cpp"],
+    srcs: [
+        "handler/debuggerd_fallback.cpp",
+    ],
 
-    // libdebuggerd_handler gets async signal safe logging via libc_logging,
-    // which defines its interface in bionic private headers.
-    include_dirs: ["bionic/libc"],
-    static_libs: [
+    whole_static_libs: [
+        "libdebuggerd_handler_core",
+        "libtombstoned_client",
+        "libbase",
         "libdebuggerd",
         "libbacktrace",
         "libunwind",
@@ -70,6 +92,7 @@
         "libbase",
         "libcutils",
     ],
+
     export_include_dirs: ["include"],
 }
 
@@ -187,6 +210,7 @@
     },
 
     static_libs: [
+        "libtombstoned_client",
         "libdebuggerd",
         "libcutils",
     ],
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 0e15472..6585424 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -48,6 +48,7 @@
 
 #include "debuggerd/handler.h"
 #include "debuggerd/protocol.h"
+#include "debuggerd/tombstoned.h"
 #include "debuggerd/util.h"
 
 using android::base::unique_fd;
@@ -128,55 +129,6 @@
   return true;
 }
 
-static bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
-  unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
-                                       ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
-  if (sockfd == -1) {
-    PLOG(ERROR) << "failed to connect to tombstoned";
-    return false;
-  }
-
-  TombstonedCrashPacket packet = {};
-  packet.packet_type = CrashPacketType::kDumpRequest;
-  packet.packet.dump_request.pid = pid;
-  if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
-    PLOG(ERROR) << "failed to write DumpRequest packet";
-    return false;
-  }
-
-  unique_fd tmp_output_fd;
-  ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
-  if (rc == -1) {
-    PLOG(ERROR) << "failed to read response to DumpRequest packet";
-    return false;
-  } else if (rc != sizeof(packet)) {
-    LOG(ERROR) << "read DumpRequest response packet of incorrect length (expected "
-               << sizeof(packet) << ", got " << rc << ")";
-    return false;
-  }
-
-  // Make the fd O_APPEND so that our output is guaranteed to be at the end of a file.
-  // (This also makes selinux rules consistent, because selinux distinguishes between writing to
-  // a regular fd, and writing to an fd with O_APPEND).
-  int flags = fcntl(tmp_output_fd.get(), F_GETFL);
-  if (fcntl(tmp_output_fd.get(), F_SETFL, flags | O_APPEND) != 0) {
-    PLOG(WARNING) << "failed to set output fd flags";
-  }
-
-  *tombstoned_socket = std::move(sockfd);
-  *output_fd = std::move(tmp_output_fd);
-  return true;
-}
-
-static bool tombstoned_notify_completion(int tombstoned_socket) {
-  TombstonedCrashPacket packet = {};
-  packet.packet_type = CrashPacketType::kCompletedDump;
-  if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
-    return false;
-  }
-  return true;
-}
-
 static void signal_handler(int) {
   // We can't log easily, because the heap might be corrupt.
   // Just die and let the surrounding log context explain things.
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
index 77ad6ac..5c6c59c 100644
--- a/debuggerd/handler/debuggerd_fallback.cpp
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -26,23 +26,206 @@
  * SUCH DAMAGE.
  */
 
+#include <dirent.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
 #include <stddef.h>
 #include <sys/ucontext.h>
+#include <syscall.h>
 #include <unistd.h>
 
+#include <atomic>
+
+#include <android-base/file.h>
+#include <android-base/unique_fd.h>
+
+#include "debuggerd/handler.h"
+#include "debuggerd/tombstoned.h"
+#include "debuggerd/util.h"
+
+#include "backtrace.h"
 #include "tombstone.h"
 
-extern "C" void __linker_use_fallback_allocator();
+#include "private/libc_logging.h"
 
-extern "C" bool debuggerd_fallback(ucontext_t* ucontext, siginfo_t* siginfo, void* abort_message) {
-  // This is incredibly sketchy to do inside of a signal handler, especially when libbacktrace
-  // uses the C++ standard library throughout, but this code runs in the linker, so we'll be using
-  // the linker's malloc instead of the libc one. Switch it out for a replacement, just in case.
-  //
-  // This isn't the default method of dumping because it can fail in cases such as memory space
-  // exhaustion.
-  __linker_use_fallback_allocator();
-  engrave_tombstone_ucontext(-1, getpid(), gettid(), reinterpret_cast<uintptr_t>(abort_message),
-                             siginfo, ucontext);
-  return true;
+using android::base::unique_fd;
+
+extern "C" void __linker_enable_fallback_allocator();
+extern "C" void __linker_disable_fallback_allocator();
+
+// This is incredibly sketchy to do inside of a signal handler, especially when libbacktrace
+// uses the C++ standard library throughout, but this code runs in the linker, so we'll be using
+// the linker's malloc instead of the libc one. Switch it out for a replacement, just in case.
+//
+// This isn't the default method of dumping because it can fail in cases such as address space
+// exhaustion.
+static void debuggerd_fallback_trace(int output_fd, ucontext_t* ucontext) {
+  __linker_enable_fallback_allocator();
+  dump_backtrace_ucontext(output_fd, ucontext);
+  __linker_disable_fallback_allocator();
+}
+
+static void debuggerd_fallback_tombstone(int output_fd, ucontext_t* ucontext, siginfo_t* siginfo,
+                                         void* abort_message) {
+  __linker_enable_fallback_allocator();
+  engrave_tombstone_ucontext(output_fd, reinterpret_cast<uintptr_t>(abort_message), siginfo,
+                             ucontext);
+  __linker_disable_fallback_allocator();
+}
+
+static void iterate_siblings(bool (*callback)(pid_t, int), int output_fd) {
+  pid_t current_tid = gettid();
+  char buf[BUFSIZ];
+  snprintf(buf, sizeof(buf), "/proc/%d/task", current_tid);
+  DIR* dir = opendir(buf);
+
+  if (!dir) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to open %s: %s", buf, strerror(errno));
+    return;
+  }
+
+  struct dirent* ent;
+  while ((ent = readdir(dir))) {
+    char* end;
+    long tid = strtol(ent->d_name, &end, 10);
+    if (end == ent->d_name || *end != '\0') {
+      continue;
+    }
+
+    if (tid != current_tid) {
+      callback(tid, output_fd);
+    }
+  }
+  closedir(dir);
+}
+
+static bool forward_output(int src_fd, int dst_fd) {
+  // Make sure the thread actually got the signal.
+  struct pollfd pfd = {
+    .fd = src_fd, .events = POLLIN,
+  };
+
+  // Wait for up to a second for output to start flowing.
+  if (poll(&pfd, 1, 1000) != 1) {
+    return false;
+  }
+
+  while (true) {
+    char buf[512];
+    ssize_t rc = TEMP_FAILURE_RETRY(read(src_fd, buf, sizeof(buf)));
+    if (rc == 0) {
+      return true;
+    } else if (rc < 0) {
+      return false;
+    }
+
+    if (!android::base::WriteFully(dst_fd, buf, rc)) {
+      // We failed to write to tombstoned, but there's not much we can do.
+      // Keep reading from src_fd to keep things going.
+      continue;
+    }
+  }
+}
+
+static void trace_handler(siginfo_t* info, ucontext_t* ucontext) {
+  static std::atomic<int> trace_output_fd(-1);
+
+  if (info->si_value.sival_int == ~0) {
+    // Asked to dump by the original signal recipient.
+    debuggerd_fallback_trace(trace_output_fd, ucontext);
+
+    int tmp = trace_output_fd.load();
+    trace_output_fd.store(-1);
+    close(tmp);
+    return;
+  }
+
+  // Only allow one thread to perform a trace at a time.
+  static pthread_mutex_t trace_mutex = PTHREAD_MUTEX_INITIALIZER;
+  int ret = pthread_mutex_trylock(&trace_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_try_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  // Fetch output fd from tombstoned.
+  unique_fd tombstone_socket, output_fd;
+  if (!tombstoned_connect(getpid(), &tombstone_socket, &output_fd)) {
+    goto exit;
+  }
+
+  dump_backtrace_header(output_fd.get());
+
+  // Dump our own stack.
+  debuggerd_fallback_trace(output_fd.get(), ucontext);
+
+  // Send a signal to all of our siblings, asking them to dump their stack.
+  iterate_siblings(
+    [](pid_t tid, int output_fd) {
+      // Use a pipe, to be able to detect situations where the thread gracefully exits before
+      // receiving our signal.
+      unique_fd pipe_read, pipe_write;
+      if (!Pipe(&pipe_read, &pipe_write)) {
+        __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to create pipe: %s", strerror(errno));
+        return false;
+      }
+
+      trace_output_fd.store(pipe_write.get());
+
+      siginfo_t siginfo = {};
+      siginfo.si_code = SI_QUEUE;
+      siginfo.si_value.sival_int = ~0;
+      siginfo.si_pid = getpid();
+      siginfo.si_uid = getuid();
+
+      if (syscall(__NR_rt_tgsigqueueinfo, getpid(), tid, DEBUGGER_SIGNAL, &siginfo) != 0) {
+        __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to send trace signal to %d: %s", tid,
+                          strerror(errno));
+        return false;
+      }
+
+      bool success = forward_output(pipe_read.get(), output_fd);
+      if (success) {
+        // The signaled thread has closed trace_output_fd already.
+        (void)pipe_write.release();
+      } else {
+        trace_output_fd.store(-1);
+      }
+
+      return true;
+    },
+    output_fd.get());
+
+  dump_backtrace_footer(output_fd.get());
+  tombstoned_notify_completion(tombstone_socket.get());
+
+exit:
+  pthread_mutex_unlock(&trace_mutex);
+}
+
+static void crash_handler(siginfo_t* info, ucontext_t* ucontext, void* abort_message) {
+  // Only allow one thread to handle a crash.
+  static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
+  int ret = pthread_mutex_lock(&crash_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  unique_fd tombstone_socket, output_fd;
+  bool tombstoned_connected = tombstoned_connect(getpid(), &tombstone_socket, &output_fd);
+  debuggerd_fallback_tombstone(output_fd.get(), ucontext, info, abort_message);
+  if (tombstoned_connected) {
+    tombstoned_notify_completion(tombstone_socket.get());
+  }
+}
+
+extern "C" void debuggerd_fallback_handler(siginfo_t* info, ucontext_t* ucontext,
+                                           void* abort_message) {
+  if (info->si_signo == DEBUGGER_SIGNAL) {
+    return trace_handler(info, ucontext);
+  } else {
+    return crash_handler(info, ucontext, abort_message);
+  }
 }
diff --git a/debuggerd/handler/debuggerd_fallback_nop.cpp b/debuggerd/handler/debuggerd_fallback_nop.cpp
index 9b3053f..331301f 100644
--- a/debuggerd/handler/debuggerd_fallback_nop.cpp
+++ b/debuggerd/handler/debuggerd_fallback_nop.cpp
@@ -26,10 +26,5 @@
  * SUCH DAMAGE.
  */
 
-#include <stddef.h>
-#include <sys/ucontext.h>
-#include <unistd.h>
-
-extern "C" bool debuggerd_fallback(ucontext_t*, siginfo_t*, void*) {
-  return false;
+extern "C" void debuggerd_fallback_handler(struct siginfo_t*, struct ucontext_t*, void*) {
 }
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 67c26e2..c09c2f3 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -62,7 +62,7 @@
 
 #define CRASH_DUMP_PATH "/system/bin/" CRASH_DUMP_NAME
 
-extern "C" bool debuggerd_fallback(ucontext_t*, siginfo_t*, void*);
+extern "C" void debuggerd_fallback_handler(siginfo_t*, ucontext_t*, void*);
 
 static debuggerd_callbacks_t g_callbacks;
 
@@ -323,21 +323,11 @@
       fatal_errno("failed to resend signal during crash");
     }
   }
-
-  if (info->si_signo == DEBUGGER_SIGNAL) {
-    pthread_mutex_unlock(&crash_mutex);
-  }
 }
 
 // Handler that does crash dumping by forking and doing the processing in the child.
 // Do this by ptracing the relevant thread, and then execing debuggerd to do the actual dump.
 static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void* context) {
-  int ret = pthread_mutex_lock(&crash_mutex);
-  if (ret != 0) {
-    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
-    return;
-  }
-
   // It's possible somebody cleared the SA_SIGINFO flag, which would mean
   // our "info" arg holds an undefined value.
   if (!have_siginfo(signal_number)) {
@@ -359,24 +349,29 @@
     // check to allow all si_code values in calls coming from inside the house.
   }
 
-  log_signal_summary(signal_number, info);
-
   void* abort_message = nullptr;
   if (g_callbacks.get_abort_message) {
     abort_message = g_callbacks.get_abort_message();
   }
 
   if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
-    ucontext_t* ucontext = static_cast<ucontext_t*>(context);
-    if (signal_number == DEBUGGER_SIGNAL || !debuggerd_fallback(ucontext, info, abort_message)) {
-      // The process has NO_NEW_PRIVS enabled, so we can't transition to the crash_dump context.
-      __libc_format_log(ANDROID_LOG_INFO, "libc",
-                        "Suppressing debuggerd output because prctl(PR_GET_NO_NEW_PRIVS)==1");
-    }
+    // This check might be racy if another thread sets NO_NEW_PRIVS, but this should be unlikely,
+    // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
+    // ANR trace.
+    debuggerd_fallback_handler(info, static_cast<ucontext_t*>(context), abort_message);
     resend_signal(info, false);
     return;
   }
 
+  // Only allow one thread to handle a signal at a time.
+  int ret = pthread_mutex_lock(&crash_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  log_signal_summary(signal_number, info);
+
   // Populate si_value with the abort message address, if found.
   if (abort_message) {
     info->si_value.sival_ptr = abort_message;
@@ -427,6 +422,11 @@
   }
 
   resend_signal(info, thread_info.crash_dump_started);
+  if (info->si_signo == DEBUGGER_SIGNAL) {
+    // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
+    // starting to dump right before our death.
+    pthread_mutex_unlock(&crash_mutex);
+  }
 }
 
 void debuggerd_init(debuggerd_callbacks_t* callbacks) {
diff --git a/debuggerd/include/debuggerd/tombstoned.h b/debuggerd/include/debuggerd/tombstoned.h
new file mode 100644
index 0000000..d158d50
--- /dev/null
+++ b/debuggerd/include/debuggerd/tombstoned.h
@@ -0,0 +1,26 @@
+#pragma once
+
+/*
+ * Copyright 2017, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sys/types.h>
+
+#include <android-base/unique_fd.h>
+
+bool tombstoned_connect(pid_t pid, android::base::unique_fd* tombstoned_socket,
+                        android::base::unique_fd* output_fd);
+
+bool tombstoned_notify_completion(int tombstoned_socket);
diff --git a/debuggerd/libdebuggerd/backtrace.cpp b/debuggerd/libdebuggerd/backtrace.cpp
index 0664442..df49aef 100644
--- a/debuggerd/libdebuggerd/backtrace.cpp
+++ b/debuggerd/libdebuggerd/backtrace.cpp
@@ -67,15 +67,15 @@
   _LOG(log, logtype::BACKTRACE, "\n----- end %d -----\n", pid);
 }
 
-static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid) {
-  char path[PATH_MAX];
-  char threadnamebuf[1024];
-  char* threadname = NULL;
+static void log_thread_name(log_t* log, pid_t tid) {
   FILE* fp;
+  char buf[1024];
+  char path[PATH_MAX];
+  char* threadname = NULL;
 
   snprintf(path, sizeof(path), "/proc/%d/comm", tid);
   if ((fp = fopen(path, "r"))) {
-    threadname = fgets(threadnamebuf, sizeof(threadnamebuf), fp);
+    threadname = fgets(buf, sizeof(buf), fp);
     fclose(fp);
     if (threadname) {
       size_t len = strlen(threadname);
@@ -84,8 +84,11 @@
       }
     }
   }
-
   _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", threadname ? threadname : "<unknown>", tid);
+}
+
+static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid) {
+  log_thread_name(log, tid);
 
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
   if (backtrace->Unwind(0)) {
@@ -112,6 +115,41 @@
   dump_process_footer(&log, pid);
 }
 
+void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext) {
+  pid_t pid = getpid();
+  pid_t tid = gettid();
+
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  log_thread_name(&log, tid);
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
+  if (backtrace->Unwind(0, ucontext)) {
+    dump_backtrace_to_log(backtrace.get(), &log, "  ");
+  } else {
+    ALOGE("Unwind failed: tid = %d: %s", tid,
+          backtrace->GetErrorString(backtrace->GetError()).c_str());
+  }
+}
+
+void dump_backtrace_header(int output_fd) {
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  dump_process_header(&log, getpid());
+}
+
+void dump_backtrace_footer(int output_fd) {
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  dump_process_footer(&log, getpid());
+}
+
 void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix) {
   for (size_t i = 0; i < backtrace->NumFrames(); i++) {
     _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, backtrace->FormatFrameData(i).c_str());
diff --git a/debuggerd/libdebuggerd/include/backtrace.h b/debuggerd/libdebuggerd/include/backtrace.h
index acd5eaa..5bfdac8 100644
--- a/debuggerd/libdebuggerd/include/backtrace.h
+++ b/debuggerd/libdebuggerd/include/backtrace.h
@@ -18,6 +18,7 @@
 #define _DEBUGGERD_BACKTRACE_H
 
 #include <sys/types.h>
+#include <sys/ucontext.h>
 
 #include <set>
 #include <string>
@@ -35,4 +36,8 @@
 /* Dumps the backtrace in the backtrace data structure to the log. */
 void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix);
 
+void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext);
+void dump_backtrace_header(int output_fd);
+void dump_backtrace_footer(int output_fd);
+
 #endif // _DEBUGGERD_BACKTRACE_H
diff --git a/debuggerd/libdebuggerd/include/tombstone.h b/debuggerd/libdebuggerd/include/tombstone.h
index aed71de..bed371b 100644
--- a/debuggerd/libdebuggerd/include/tombstone.h
+++ b/debuggerd/libdebuggerd/include/tombstone.h
@@ -39,7 +39,7 @@
                        const std::set<pid_t>* siblings, uintptr_t abort_msg_address,
                        std::string* amfd_data);
 
-void engrave_tombstone_ucontext(int tombstone_fd, pid_t pid, pid_t tid, uintptr_t abort_msg_address,
-                                siginfo_t* siginfo, ucontext_t* ucontext);
+void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+                                ucontext_t* ucontext);
 
 #endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index 4686bfd..c05ccc3 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -751,8 +751,11 @@
   dump_crash(&log, map, open_files, pid, tid, siblings, abort_msg_address);
 }
 
-void engrave_tombstone_ucontext(int tombstone_fd, pid_t pid, pid_t tid, uintptr_t abort_msg_address,
-                                siginfo_t* siginfo, ucontext_t* ucontext) {
+void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+                                ucontext_t* ucontext) {
+  pid_t pid = getpid();
+  pid_t tid = gettid();
+
   log_t log;
   log.current_tid = tid;
   log.crashed_tid = tid;
diff --git a/debuggerd/tombstoned_client.cpp b/debuggerd/tombstoned_client.cpp
new file mode 100644
index 0000000..03b4a20
--- /dev/null
+++ b/debuggerd/tombstoned_client.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2017, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "debuggerd/tombstoned.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <utility>
+
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+
+#include "debuggerd/protocol.h"
+#include "debuggerd/util.h"
+#include "private/libc_logging.h"
+
+using android::base::unique_fd;
+
+bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
+  unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
+                                       ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
+  if (sockfd == -1) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to connect to tombstoned: %s",
+                      strerror(errno));
+    return false;
+  }
+
+  TombstonedCrashPacket packet = {};
+  packet.packet_type = CrashPacketType::kDumpRequest;
+  packet.packet.dump_request.pid = pid;
+  if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to write DumpRequest packet: %s",
+                      strerror(errno));
+    return false;
+  }
+
+  unique_fd tmp_output_fd;
+  ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
+  if (rc == -1) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc",
+                      "failed to read response to DumpRequest packet: %s", strerror(errno));
+    return false;
+  } else if (rc != sizeof(packet)) {
+    __libc_format_log(
+      ANDROID_LOG_ERROR, "libc",
+      "received DumpRequest response packet of incorrect length (expected %zu, got %zd)",
+      sizeof(packet), rc);
+    return false;
+  }
+
+  // Make the fd O_APPEND so that our output is guaranteed to be at the end of a file.
+  // (This also makes selinux rules consistent, because selinux distinguishes between writing to
+  // a regular fd, and writing to an fd with O_APPEND).
+  int flags = fcntl(tmp_output_fd.get(), F_GETFL);
+  if (fcntl(tmp_output_fd.get(), F_SETFL, flags | O_APPEND) != 0) {
+    __libc_format_log(ANDROID_LOG_WARN, "libc", "failed to set output fd flags: %s",
+                      strerror(errno));
+  }
+
+  *tombstoned_socket = std::move(sockfd);
+  *output_fd = std::move(tmp_output_fd);
+  return true;
+}
+
+bool tombstoned_notify_completion(int tombstoned_socket) {
+  TombstonedCrashPacket packet = {};
+  packet.packet_type = CrashPacketType::kCompletedDump;
+  if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
+    return false;
+  }
+  return true;
+}
diff --git a/debuggerd/util.cpp b/debuggerd/util.cpp
index 738abdf..4c015d7 100644
--- a/debuggerd/util.cpp
+++ b/debuggerd/util.cpp
@@ -22,8 +22,13 @@
 
 #include <android-base/unique_fd.h>
 #include <cutils/sockets.h>
+#include <debuggerd/protocol.h>
 
-ssize_t send_fd(int sockfd, const void* data, size_t len, android::base::unique_fd fd) {
+#include "private/libc_logging.h"
+
+using android::base::unique_fd;
+
+ssize_t send_fd(int sockfd, const void* data, size_t len, unique_fd fd) {
   char cmsg_buf[CMSG_SPACE(sizeof(int))];
 
   iovec iov = { .iov_base = const_cast<void*>(data), .iov_len = len };
@@ -39,8 +44,7 @@
   return TEMP_FAILURE_RETRY(sendmsg(sockfd, &msg, 0));
 }
 
-ssize_t recv_fd(int sockfd, void* _Nonnull data, size_t len,
-                android::base::unique_fd* _Nullable out_fd) {
+ssize_t recv_fd(int sockfd, void* _Nonnull data, size_t len, unique_fd* _Nullable out_fd) {
   char cmsg_buf[CMSG_SPACE(sizeof(int))];
 
   iovec iov = { .iov_base = const_cast<void*>(data), .iov_len = len };
@@ -61,7 +65,7 @@
     return -1;
   }
 
-  android::base::unique_fd fd;
+  unique_fd fd;
   bool received_fd = msg.msg_controllen == sizeof(cmsg_buf);
   if (received_fd) {
     fd.reset(*reinterpret_cast<int*>(CMSG_DATA(cmsg)));
@@ -85,7 +89,7 @@
   return result;
 }
 
-bool Pipe(android::base::unique_fd* read, android::base::unique_fd* write) {
+bool Pipe(unique_fd* read, unique_fd* write) {
   int pipefds[2];
   if (pipe(pipefds) != 0) {
     return false;