Merge changes from topic 'fstab_relocation'

* changes:
  init: replacing fs_mgr_read_fstab() with fs_mgr_read_fstab_default()
  fs_mgr: support reading fstab file from /odm or /vendor partition
  fs_mgr: add fs_mgr_read_fstab_with_dt() API
diff --git a/adb/Android.mk b/adb/Android.mk
index a2ea699..8a43e37 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -145,6 +145,7 @@
 LOCAL_SRC_FILES := \
     $(LIBADB_SRC_FILES) \
     adb_auth_host.cpp \
+    transport_mdns.cpp \
 
 LOCAL_SRC_FILES_darwin := $(LIBADB_darwin_SRC_FILES)
 LOCAL_SRC_FILES_linux := $(LIBADB_linux_SRC_FILES)
@@ -154,7 +155,7 @@
 
 # Even though we're building a static library (and thus there's no link step for
 # this to take effect), this adds the includes to our path.
-LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase
+LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase libmdnssd
 LOCAL_STATIC_LIBRARIES_linux := libusb
 LOCAL_STATIC_LIBRARIES_darwin := libusb
 
@@ -176,7 +177,7 @@
     shell_service_test.cpp \
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
-LOCAL_STATIC_LIBRARIES := libadbd libcrypto_utils libcrypto libusb
+LOCAL_STATIC_LIBRARIES := libadbd libcrypto_utils libcrypto libusb libmdnssd
 LOCAL_SHARED_LIBRARIES := liblog libbase libcutils
 include $(BUILD_NATIVE_TEST)
 
@@ -224,7 +225,8 @@
     libcrypto \
     libcutils \
     libdiagnose_usb \
-    libgmock_host \
+    libmdnssd \
+    libgmock_host
 
 LOCAL_STATIC_LIBRARIES_linux := libusb
 LOCAL_STATIC_LIBRARIES_darwin := libusb
@@ -292,6 +294,7 @@
     libcrypto \
     libdiagnose_usb \
     liblog \
+    libmdnssd
 
 # Don't use libcutils on Windows.
 LOCAL_STATIC_LIBRARIES_darwin := libcutils
@@ -325,6 +328,7 @@
 
 LOCAL_SRC_FILES := \
     daemon/main.cpp \
+    daemon/mdns.cpp \
     services.cpp \
     file_sync_service.cpp \
     framebuffer_service.cpp \
@@ -372,6 +376,7 @@
     libcrypto_utils \
     libcrypto \
     libminijail \
+    libmdnssd \
     libdebuggerd_handler \
 
 include $(BUILD_EXECUTABLE)
diff --git a/adb/adb_mdns.h b/adb/adb_mdns.h
new file mode 100644
index 0000000..2e544d7
--- /dev/null
+++ b/adb/adb_mdns.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _ADB_MDNS_H_
+#define _ADB_MDNS_H_
+
+const char* kADBServiceType = "_adb._tcp";
+
+#endif
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index 97a54fd..606203c 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -117,6 +117,8 @@
 
     init_transport_registration();
 
+    init_mdns_transport_discovery();
+
     usb_init();
     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
 
diff --git a/adb/daemon/main.cpp b/adb/daemon/main.cpp
index 6382b67..7da94ce 100644
--- a/adb/daemon/main.cpp
+++ b/adb/daemon/main.cpp
@@ -45,6 +45,8 @@
 #include "adb_utils.h"
 #include "transport.h"
 
+#include "mdns.h"
+
 static const char* root_seclabel = nullptr;
 
 static void drop_capabilities_bounding_set_if_needed(struct minijail *j) {
@@ -140,6 +142,11 @@
     }
 }
 
+static void setup_port(int port) {
+    local_init(port);
+    setup_mdns(port);
+}
+
 int adbd_main(int server_port) {
     umask(0);
 
@@ -188,10 +195,10 @@
     if (sscanf(prop_port.c_str(), "%d", &port) == 1 && port > 0) {
         D("using port=%d", port);
         // Listen on TCP port specified by service.adb.tcp.port property.
-        local_init(port);
+        setup_port(port);
     } else if (!is_usb) {
         // Listen on default port.
-        local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
+        setup_port(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
     }
 
     D("adbd_main(): pre init_jdwp()");
diff --git a/adb/daemon/mdns.cpp b/adb/daemon/mdns.cpp
new file mode 100644
index 0000000..7811143
--- /dev/null
+++ b/adb/daemon/mdns.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2016 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 "adb_mdns.h"
+#include "sysdeps.h"
+
+#include <chrono>
+#include <dns_sd.h>
+#include <endian.h>
+#include <mutex>
+#include <unistd.h>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
+using namespace std::chrono_literals;
+
+static std::mutex& mdns_lock = *new std::mutex();
+static int port;
+static DNSServiceRef mdns_ref;
+static bool mdns_registered = false;
+
+static void start_mdns() {
+    if (android::base::GetProperty("init.svc.mdnsd", "") == "running") {
+        return;
+    }
+
+    android::base::SetProperty("ctl.start", "mdnsd");
+
+    if (! android::base::WaitForProperty("init.svc.mdnsd", "running", 5s)) {
+        LOG(ERROR) << "Could not start mdnsd.";
+    }
+}
+
+static void mdns_callback(DNSServiceRef /*ref*/,
+                          DNSServiceFlags /*flags*/,
+                          DNSServiceErrorType errorCode,
+                          const char* /*name*/,
+                          const char* /*regtype*/,
+                          const char* /*domain*/,
+                          void* /*context*/) {
+    if (errorCode != kDNSServiceErr_NoError) {
+        LOG(ERROR) << "Encountered mDNS registration error ("
+            << errorCode << ").";
+    }
+}
+
+static void setup_mdns_thread(void* /* unused */) {
+    start_mdns();
+    std::lock_guard<std::mutex> lock(mdns_lock);
+
+    std::string hostname = "adb-";
+    hostname += android::base::GetProperty("ro.serialno", "unidentified");
+
+    auto error = DNSServiceRegister(&mdns_ref, 0, 0, hostname.c_str(),
+                                    kADBServiceType, nullptr, nullptr,
+                                    htobe16((uint16_t)port), 0, nullptr,
+                                    mdns_callback, nullptr);
+
+    if (error != kDNSServiceErr_NoError) {
+        LOG(ERROR) << "Could not register mDNS service (" << error << ").";
+        mdns_registered = false;
+    }
+
+    mdns_registered = true;
+}
+
+static void teardown_mdns() {
+    std::lock_guard<std::mutex> lock(mdns_lock);
+
+    if (mdns_registered) {
+        DNSServiceRefDeallocate(mdns_ref);
+    }
+}
+
+void setup_mdns(int port_in) {
+    port = port_in;
+    adb_thread_create(setup_mdns_thread, nullptr, nullptr);
+
+    // TODO: Make this more robust against a hard kill.
+    atexit(teardown_mdns);
+}
diff --git a/adb/daemon/mdns.h b/adb/daemon/mdns.h
new file mode 100644
index 0000000..4c6b1ca
--- /dev/null
+++ b/adb/daemon/mdns.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _DAEMON_MDNS_H_
+#define _DAEMON_MDNS_H_
+
+void setup_mdns(int port);
+
+#endif  // _DAEMON_MDNS_H_
diff --git a/adb/services.cpp b/adb/services.cpp
index a48d855..47f0a03 100644
--- a/adb/services.cpp
+++ b/adb/services.cpp
@@ -377,45 +377,6 @@
     D("wait_for_state is done");
 }
 
-static void connect_device(const std::string& address, std::string* response) {
-    if (address.empty()) {
-        *response = "empty address";
-        return;
-    }
-
-    std::string serial;
-    std::string host;
-    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
-    if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
-        return;
-    }
-
-    std::string error;
-    int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error);
-    if (fd == -1) {
-        *response = android::base::StringPrintf("unable to connect to %s: %s",
-                                                serial.c_str(), error.c_str());
-        return;
-    }
-
-    D("client: connected %s remote on fd %d", serial.c_str(), fd);
-    close_on_exec(fd);
-    disable_tcp_nagle(fd);
-
-    // Send a TCP keepalive ping to the device every second so we can detect disconnects.
-    if (!set_tcp_keepalive(fd, 1)) {
-        D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
-    }
-
-    int ret = register_socket_transport(fd, serial.c_str(), port, 0);
-    if (ret < 0) {
-        adb_close(fd);
-        *response = android::base::StringPrintf("already connected to %s", serial.c_str());
-    } else {
-        *response = android::base::StringPrintf("connected to %s", serial.c_str());
-    }
-}
-
 void connect_emulator(const std::string& port_spec, std::string* response) {
     std::vector<std::string> pieces = android::base::Split(port_spec, ",");
     if (pieces.size() != 2) {
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 654072c..f195b4e 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -197,6 +197,7 @@
 extern int  adb_lseek(int  fd, int  pos, int  where);
 extern int  adb_shutdown(int  fd);
 extern int  adb_close(int  fd);
+extern int  adb_register_socket(SOCKET s);
 
 // See the comments for the !defined(_WIN32) version of unix_close().
 static __inline__ int  unix_close(int fd)
@@ -523,6 +524,12 @@
 #undef   close
 #define  close   ____xxx_close
 
+// On Windows, ADB has an indirection layer for file descriptors. If we get a
+// Win32 SOCKET object from an external library, we have to map it in to that
+// indirection layer, which this does.
+__inline__ int  adb_register_socket(int s) {
+    return s;
+}
 
 static __inline__  int  adb_read(int  fd, void*  buf, size_t  len)
 {
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index a4b5e69..f997e6b 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -126,10 +126,7 @@
         SOCKET      socket;
     } u;
 
-    int       mask;
-
     char  name[32];
-
 } FHRec;
 
 #define  fh_handle  u.handle
@@ -577,7 +574,6 @@
 
 static void _fh_socket_init(FH f) {
     f->fh_socket = INVALID_SOCKET;
-    f->mask      = 0;
 }
 
 static int _fh_socket_close( FH  f ) {
@@ -598,7 +594,6 @@
         }
         f->fh_socket = INVALID_SOCKET;
     }
-    f->mask = 0;
     return 0;
 }
 
@@ -913,6 +908,12 @@
     return fd;
 }
 
+int  adb_register_socket(SOCKET s) {
+    FH f = _fh_alloc( &_fh_socket_class );
+    f->fh_socket = s;
+    return _fh_to_int(f);
+}
+
 #undef accept
 int  adb_socket_accept(int  serverfd, struct sockaddr*  addr, socklen_t  *addrlen)
 {
@@ -1113,18 +1114,22 @@
 
     if (!fh || !fh->used) {
         errno = EBADF;
+        D("Setting nonblocking on bad file descriptor %d", fd);
         return false;
     }
 
     if (fh->clazz == &_fh_socket_class) {
         u_long x = !block;
         if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
-            _socket_set_errno(WSAGetLastError());
+            int error = WSAGetLastError();
+            _socket_set_errno(error);
+            D("Setting %d nonblocking failed (%d)", fd, error);
             return false;
         }
         return true;
     } else {
         errno = ENOTSOCK;
+        D("Setting nonblocking on non-socket %d", fd);
         return false;
     }
 }
diff --git a/adb/transport.h b/adb/transport.h
index 490e513..4d97fc7 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -187,6 +187,7 @@
 void update_transports(void);
 
 void init_transport_registration(void);
+void init_mdns_transport_discovery(void);
 std::string list_transports(bool long_listing);
 atransport* find_transport(const char* serial);
 void kick_all_tcp_devices();
@@ -194,6 +195,9 @@
 void register_usb_transport(usb_handle* h, const char* serial,
                             const char* devpath, unsigned writeable);
 
+/* Connect to a network address and register it as a device */
+void connect_device(const std::string& address, std::string* response);
+
 /* cause new transports to be init'd and added to the list */
 int register_socket_transport(int s, const char* serial, int port, int local);
 
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index b5d0ef0..12b98ba 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -30,6 +30,7 @@
 #include <thread>
 #include <vector>
 
+#include <android-base/parsenetaddress.h>
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
 
@@ -101,6 +102,46 @@
     return local_connect_arbitrary_ports(port-1, port, &dummy) == 0;
 }
 
+void connect_device(const std::string& address, std::string* response) {
+    if (address.empty()) {
+        *response = "empty address";
+        return;
+    }
+
+    std::string serial;
+    std::string host;
+    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
+        return;
+    }
+
+    std::string error;
+    int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error);
+    if (fd == -1) {
+        *response = android::base::StringPrintf("unable to connect to %s: %s",
+                                                serial.c_str(), error.c_str());
+        return;
+    }
+
+    D("client: connected %s remote on fd %d", serial.c_str(), fd);
+    close_on_exec(fd);
+    disable_tcp_nagle(fd);
+
+    // Send a TCP keepalive ping to the device every second so we can detect disconnects.
+    if (!set_tcp_keepalive(fd, 1)) {
+        D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
+    }
+
+    int ret = register_socket_transport(fd, serial.c_str(), port, 0);
+    if (ret < 0) {
+        adb_close(fd);
+        *response = android::base::StringPrintf("already connected to %s", serial.c_str());
+    } else {
+        *response = android::base::StringPrintf("connected to %s", serial.c_str());
+    }
+}
+
+
 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
     int fd = -1;
 
diff --git a/adb/transport_mdns.cpp b/adb/transport_mdns.cpp
new file mode 100644
index 0000000..e49b1c6
--- /dev/null
+++ b/adb/transport_mdns.cpp
@@ -0,0 +1,280 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define TRACE_TAG TRANSPORT
+
+#include "transport.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <arpa/inet.h>
+#endif
+
+#include <android-base/stringprintf.h>
+#include <dns_sd.h>
+
+#include "adb_mdns.h"
+#include "adb_trace.h"
+#include "fdevent.h"
+#include "sysdeps.h"
+
+static DNSServiceRef service_ref;
+static fdevent service_ref_fde;
+
+// Use adb_DNSServiceRefSockFD() instead of calling DNSServiceRefSockFD()
+// directly so that the socket is put through the appropriate compatibility
+// layers to work with the rest of ADB's internal APIs.
+static inline int adb_DNSServiceRefSockFD(DNSServiceRef ref) {
+    return adb_register_socket(DNSServiceRefSockFD(ref));
+}
+#define DNSServiceRefSockFD ___xxx_DNSServiceRefSockFD
+
+static void DNSSD_API register_service_ip(DNSServiceRef sdRef,
+                                          DNSServiceFlags flags,
+                                          uint32_t interfaceIndex,
+                                          DNSServiceErrorType errorCode,
+                                          const char* hostname,
+                                          const sockaddr* address,
+                                          uint32_t ttl,
+                                          void* context);
+
+static void pump_service_ref(int /*fd*/, unsigned ev, void* data) {
+    DNSServiceRef* ref = reinterpret_cast<DNSServiceRef*>(data);
+
+    if (ev & FDE_READ)
+        DNSServiceProcessResult(*ref);
+}
+
+class AsyncServiceRef {
+  public:
+    bool Initialized() {
+        return initialized_;
+    }
+
+    virtual ~AsyncServiceRef() {
+        if (! initialized_) {
+            return;
+        }
+
+        DNSServiceRefDeallocate(sdRef_);
+        fdevent_remove(&fde_);
+    }
+
+  protected:
+    DNSServiceRef sdRef_;
+
+    void Initialize() {
+        fdevent_install(&fde_, adb_DNSServiceRefSockFD(sdRef_),
+                        pump_service_ref, &sdRef_);
+        fdevent_set(&fde_, FDE_READ);
+        initialized_ = true;
+    }
+
+  private:
+    bool initialized_;
+    fdevent fde_;
+};
+
+class ResolvedService : public AsyncServiceRef {
+  public:
+    virtual ~ResolvedService() = default;
+
+    ResolvedService(std::string name, uint32_t interfaceIndex,
+                    const char* hosttarget, uint16_t port) :
+            name_(name),
+            port_(port) {
+
+        /* TODO: We should be able to get IPv6 support by adding
+         * kDNSServiceProtocol_IPv6 to the flags below. However, when we do
+         * this, we get served link-local addresses that are usually useless to
+         * connect to. What's more, we seem to /only/ get those and nothing else.
+         * If we want IPv6 in the future we'll have to figure out why.
+         */
+        DNSServiceErrorType ret =
+            DNSServiceGetAddrInfo(
+                &sdRef_, 0, interfaceIndex,
+                kDNSServiceProtocol_IPv4, hosttarget,
+                register_service_ip, reinterpret_cast<void*>(this));
+
+        if (ret != kDNSServiceErr_NoError) {
+            D("Got %d from DNSServiceGetAddrInfo.", ret);
+        } else {
+            Initialize();
+        }
+    }
+
+    void Connect(const sockaddr* address) {
+        char ip_addr[INET6_ADDRSTRLEN];
+        const void* ip_addr_data;
+        const char* addr_format;
+
+        if (address->sa_family == AF_INET) {
+            ip_addr_data =
+                &reinterpret_cast<const sockaddr_in*>(address)->sin_addr;
+            addr_format = "%s:%hu";
+        } else if (address->sa_family == AF_INET6) {
+            ip_addr_data =
+                &reinterpret_cast<const sockaddr_in6*>(address)->sin6_addr;
+            addr_format = "[%s]:%hu";
+        } else { // Should be impossible
+            D("mDNS resolved non-IP address.");
+            return;
+        }
+
+        // Winsock version requires the const cast Because Microsoft.
+        if (!inet_ntop(address->sa_family, const_cast<void*>(ip_addr_data),
+                       ip_addr, INET6_ADDRSTRLEN)) {
+            D("Could not convert IP address to string.");
+            return;
+        }
+
+        std::string response;
+        connect_device(android::base::StringPrintf(addr_format, ip_addr, port_),
+                       &response);
+        D("Connect to %s (%s:%hu) : %s", name_.c_str(), ip_addr, port_,
+          response.c_str());
+    }
+
+  private:
+    std::string name_;
+    const uint16_t port_;
+};
+
+static void DNSSD_API register_service_ip(DNSServiceRef /*sdRef*/,
+                                          DNSServiceFlags /*flags*/,
+                                          uint32_t /*interfaceIndex*/,
+                                          DNSServiceErrorType /*errorCode*/,
+                                          const char* /*hostname*/,
+                                          const sockaddr* address,
+                                          uint32_t /*ttl*/,
+                                          void* context) {
+    D("Got IP for service.");
+    std::unique_ptr<ResolvedService> data(
+        reinterpret_cast<ResolvedService*>(context));
+    data->Connect(address);
+}
+
+static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
+                                                     DNSServiceFlags flags,
+                                                     uint32_t interfaceIndex,
+                                                     DNSServiceErrorType errorCode,
+                                                     const char* fullname,
+                                                     const char* hosttarget,
+                                                     uint16_t port,
+                                                     uint16_t txtLen,
+                                                     const unsigned char* txtRecord,
+                                                     void* context);
+
+class DiscoveredService : public AsyncServiceRef {
+  public:
+    DiscoveredService(uint32_t interfaceIndex, const char* serviceName,
+                      const char* regtype, const char* domain)
+        : serviceName_(serviceName) {
+
+        DNSServiceErrorType ret =
+            DNSServiceResolve(&sdRef_, 0, interfaceIndex, serviceName, regtype,
+                              domain, register_resolved_mdns_service,
+                              reinterpret_cast<void*>(this));
+
+        if (ret != kDNSServiceErr_NoError) {
+            D("Got %d from DNSServiceResolve.", ret);
+        } else {
+            Initialize();
+        }
+    }
+
+    const char* ServiceName() {
+        return serviceName_.c_str();
+    }
+
+  private:
+    std::string serviceName_;
+};
+
+static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
+                                                     DNSServiceFlags flags,
+                                                     uint32_t interfaceIndex,
+                                                     DNSServiceErrorType errorCode,
+                                                     const char* fullname,
+                                                     const char* hosttarget,
+                                                     uint16_t port,
+                                                     uint16_t /*txtLen*/,
+                                                     const unsigned char* /*txtRecord*/,
+                                                     void* context) {
+    D("Resolved a service.");
+    std::unique_ptr<DiscoveredService> discovered(
+        reinterpret_cast<DiscoveredService*>(context));
+
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got error %d resolving service.", errorCode);
+        return;
+    }
+
+
+    auto resolved =
+        new ResolvedService(discovered->ServiceName(),
+                            interfaceIndex, hosttarget, ntohs(port));
+
+    if (! resolved->Initialized()) {
+        delete resolved;
+    }
+
+    if (flags) { /* Only ever equals MoreComing or 0 */
+        discovered.release();
+    }
+}
+
+static void DNSSD_API register_mdns_transport(DNSServiceRef sdRef,
+                                              DNSServiceFlags flags,
+                                              uint32_t interfaceIndex,
+                                              DNSServiceErrorType errorCode,
+                                              const char* serviceName,
+                                              const char* regtype,
+                                              const char* domain,
+                                              void*  /*context*/) {
+    D("Registering a transport.");
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got error %d during mDNS browse.", errorCode);
+        DNSServiceRefDeallocate(sdRef);
+        fdevent_remove(&service_ref_fde);
+        return;
+    }
+
+    auto discovered = new DiscoveredService(interfaceIndex, serviceName,
+                                            regtype, domain);
+
+    if (! discovered->Initialized()) {
+        delete discovered;
+    }
+}
+
+void init_mdns_transport_discovery(void) {
+    DNSServiceErrorType errorCode =
+        DNSServiceBrowse(&service_ref, 0, 0, kADBServiceType, nullptr,
+                         register_mdns_transport, nullptr);
+
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got %d initiating mDNS browse.", errorCode);
+        return;
+    }
+
+    fdevent_install(&service_ref_fde,
+                    adb_DNSServiceRefSockFD(service_ref),
+                    pump_service_ref,
+                    &service_ref);
+    fdevent_set(&service_ref_fde, FDE_READ);
+}
diff --git a/adb/transport_mdns_unsupported.cpp b/adb/transport_mdns_unsupported.cpp
new file mode 100644
index 0000000..387d341
--- /dev/null
+++ b/adb/transport_mdns_unsupported.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+/* For when mDNS discovery is unsupported */
+void init_mdns_transport_discovery(void) {}
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..8e60278 100644
--- a/debuggerd/libdebuggerd/include/tombstone.h
+++ b/debuggerd/libdebuggerd/include/tombstone.h
@@ -39,7 +39,13 @@
                        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);
+
+// Compatibility shim.
+static void engrave_tombstone_ucontext(int tombstone_fd, pid_t, pid_t, uintptr_t abort_msg_address,
+                                       siginfo_t* siginfo, ucontext_t* ucontext) {
+  engrave_tombstone_ucontext(tombstone_fd, abort_msg_address, siginfo, 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;
diff --git a/init/init.cpp b/init/init.cpp
index 38178a7..5ab421b 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -790,6 +790,14 @@
 
     LOG(INFO) << "Compiling SELinux policy";
 
+    // Determine the highest policy language version supported by the kernel
+    set_selinuxmnt("/sys/fs/selinux");
+    int max_policy_version = security_policyvers();
+    if (max_policy_version == -1) {
+        PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
+        return false;
+    }
+
     // We store the output of the compilation on /dev because this is the most convenient tmpfs
     // storage mount available this early in the boot sequence.
     char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
@@ -799,14 +807,20 @@
         return false;
     }
 
-    const char* compile_args[] = {"/system/bin/secilc", plat_policy_cil_file, "-M", "true", "-c",
-                                  "30",  // TODO: pass in SELinux policy version from build system
-                                  "/vendor/etc/selinux/mapping_sepolicy.cil",
-                                  "/vendor/etc/selinux/nonplat_sepolicy.cil", "-o",
-                                  compiled_sepolicy,
-                                  // We don't care about file_contexts output by the compiler
-                                  "-f", "/sys/fs/selinux/null",  // /dev/null is not yet available
-                                  nullptr};
+    // clang-format off
+    const char* compile_args[] = {
+        "/system/bin/secilc",
+        plat_policy_cil_file,
+        "-M", "true",
+        // Target the highest policy language version supported by the kernel
+        "-c", std::to_string(max_policy_version).c_str(),
+        "/vendor/etc/selinux/mapping_sepolicy.cil",
+        "/vendor/etc/selinux/nonplat_sepolicy.cil",
+        "-o", compiled_sepolicy,
+        // We don't care about file_contexts output by the compiler
+        "-f", "/sys/fs/selinux/null",  // /dev/null is not yet available
+        nullptr};
+    // clang-format on
 
     if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
         unlink(compiled_sepolicy);
diff --git a/rootdir/init.rc b/rootdir/init.rc
index f1b047e..4a91189 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -302,12 +302,6 @@
     trigger early-boot
     trigger boot
 
-on post-fs-data && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
-    start netd
-
-on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
-    start zygote
-
 on post-fs
     start logd
     # once everything is setup, no need to modify /
@@ -499,6 +493,13 @@
     # Set indication (checked by vold) that we have finished this action
     #setprop vold.post_fs_data_done 1
 
+# This trigger will be triggered before 'zygote-start' since there is no zygote-start defined in
+# current init.rc. It is recommended to put unnecessary data/ initialization from post-fs-data
+# to start-zygote to unblock zygote start.
+on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
+   start netd
+   start zygote
+
 on boot
     # basic network init
     ifup lo