Merge "adb: add `adb reconnect offline` to reconnect offline devices."
diff --git a/adb/adb_trace.cpp b/adb/adb_trace.cpp
index 369dec9..002d061 100644
--- a/adb/adb_trace.cpp
+++ b/adb/adb_trace.cpp
@@ -155,7 +155,24 @@
     }
 #endif
 
+#if !defined(_WIN32)
+    // adb historically ignored $ANDROID_LOG_TAGS but passed it through to logcat.
+    // If set, move it out of the way so that libbase logging doesn't try to parse it.
+    std::string log_tags;
+    char* ANDROID_LOG_TAGS = getenv("ANDROID_LOG_TAGS");
+    if (ANDROID_LOG_TAGS) {
+        log_tags = ANDROID_LOG_TAGS;
+        unsetenv("ANDROID_LOG_TAGS");
+    }
+#endif
+
     android::base::InitLogging(argv, &AdbLogger);
+
+#if !defined(_WIN32)
+    // Put $ANDROID_LOG_TAGS back so we can pass it to logcat.
+    if (!log_tags.empty()) setenv("ANDROID_LOG_TAGS", log_tags.c_str(), 1);
+#endif
+
     setup_trace_mask();
 
     VLOG(ADB) << adb_version();
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index 767b3b3..67104cc 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -341,6 +341,17 @@
     return 0;
 }
 
+static int test_access(char *device) {
+    int tries = 25;
+    while (tries--) {
+        if (!access(device, F_OK) || errno != ENOENT) {
+            return 0;
+        }
+        usleep(40 * 1000);
+    }
+    return -1;
+}
+
 static int check_verity_restart(const char *fname)
 {
     char buffer[VERITY_KMSG_BUFSIZE + 1];
@@ -1020,6 +1031,11 @@
     fstab->blk_device = verity_blk_name;
     verity_blk_name = 0;
 
+    // make sure we've set everything up properly
+    if (test_access(fstab->blk_device) < 0) {
+        goto out;
+    }
+
     retval = FS_MGR_SETUP_VERITY_SUCCESS;
 
 out:
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 167a6d9..c364317 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -95,6 +95,7 @@
 #define AID_DNS           1051  /* DNS resolution daemon (system: netd) */
 #define AID_DNS_TETHER    1052  /* DNS resolution daemon (tether: dnsmasq) */
 #define AID_WEBVIEW_ZYGOTE 1053 /* WebView zygote process */
+#define AID_VEHICLE_NETWORK 1054 /* Vehicle network service */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
@@ -208,6 +209,7 @@
     { "dns",           AID_DNS, },
     { "dns_tether",    AID_DNS_TETHER, },
     { "webview_zygote", AID_WEBVIEW_ZYGOTE, },
+    { "vehicle_network", AID_VEHICLE_NETWORK, },
 
     { "shell",         AID_SHELL, },
     { "cache",         AID_CACHE, },
diff --git a/init/bootchart.cpp b/init/bootchart.cpp
index 467a838..8fb55f0 100644
--- a/init/bootchart.cpp
+++ b/init/bootchart.cpp
@@ -241,6 +241,7 @@
     fclose(log_disks);
     fclose(log_procs);
     acct(NULL);
+    LOG(INFO) << "Bootcharting finished";
 }
 
 void bootchart_sample(int* timeout) {
@@ -253,12 +254,12 @@
     int elapsed_time = current_time - g_last_bootchart_time;
 
     if (elapsed_time >= BOOTCHART_POLLING_MS) {
-        /* count missed samples */
+        // Count missed samples.
         while (elapsed_time >= BOOTCHART_POLLING_MS) {
             elapsed_time -= BOOTCHART_POLLING_MS;
             g_remaining_samples--;
         }
-        /* count may be negative, take a sample anyway */
+        // Count may be negative, take a sample anyway.
         g_last_bootchart_time = current_time;
         if (bootchart_step() < 0 || g_remaining_samples <= 0) {
             bootchart_finish();
diff --git a/init/init.cpp b/init/init.cpp
index 957527b..7c37d28 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -585,19 +585,43 @@
         mount("devpts", "/dev/pts", "devpts", 0, NULL);
         #define MAKE_STR(x) __STRING(x)
         mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
+        gid_t groups[] = { AID_READPROC };
+        setgroups(arraysize(groups), groups);
         mount("sysfs", "/sys", "sysfs", 0, NULL);
         mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
         mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
-        early_mount();
     }
 
     // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
     // talk to the outside world...
     InitKernelLogging(argv);
 
-    LOG(INFO) << "init " << (is_first_stage ? "first stage" : "second stage") << " started!";
+    if (is_first_stage) {
+        LOG(INFO) << "init first stage started!";
 
-    if (!is_first_stage) {
+        // Mount devices defined in android.early.* kernel commandline
+        early_mount();
+
+        // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
+        selinux_initialize(true);
+
+        // If we're in the kernel domain, re-exec init to transition to the init domain now
+        // that the SELinux policy has been loaded.
+
+        if (restorecon("/init") == -1) {
+            PLOG(ERROR) << "restorecon failed";
+            security_failure();
+        }
+        char* path = argv[0];
+        char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
+        if (execv(path, args) == -1) {
+            PLOG(ERROR) << "execv(\"" << path << "\") failed";
+            security_failure();
+        }
+
+    } else {
+        LOG(INFO) << "init second stage started!";
+
         // Indicate that booting is in progress to background fw loaders, etc.
         close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
 
@@ -611,24 +635,9 @@
         // Propagate the kernel variables to internal variables
         // used by init as well as the current required properties.
         export_kernel_boot_props();
-    }
 
-    // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
-    selinux_initialize(is_first_stage);
-
-    // If we're in the kernel domain, re-exec init to transition to the init domain now
-    // that the SELinux policy has been loaded.
-    if (is_first_stage) {
-        if (restorecon("/init") == -1) {
-            PLOG(ERROR) << "restorecon failed";
-            security_failure();
-        }
-        char* path = argv[0];
-        char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
-        if (execv(path, args) == -1) {
-            PLOG(ERROR) << "execv(\"" << path << "\") failed";
-            security_failure();
-        }
+        // Now set up SELinux for second stage
+        selinux_initialize(false);
     }
 
     // These directories were necessarily created before initial policy load
diff --git a/init/service.cpp b/init/service.cpp
index 6460e71..92f1615 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -233,10 +233,8 @@
             PLOG(FATAL) << "setgid failed for " << name_;
         }
     }
-    if (!supp_gids_.empty()) {
-        if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
-            PLOG(FATAL) << "setgroups failed for " << name_;
-        }
+    if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
+        PLOG(FATAL) << "setgroups failed for " << name_;
     }
     if (uid_) {
         if (setuid(uid_) != 0) {
diff --git a/libappfuse/Android.bp b/libappfuse/Android.bp
new file mode 100644
index 0000000..8b46154
--- /dev/null
+++ b/libappfuse/Android.bp
@@ -0,0 +1,26 @@
+// Copyright 2016 The Android Open Source Project
+
+cc_defaults {
+    name: "libappfuse_defaults",
+    local_include_dirs: ["include"],
+    shared_libs: ["libbase"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    clang: true
+}
+
+cc_library_shared {
+    name: "libappfuse",
+    defaults: ["libappfuse_defaults"],
+    export_include_dirs: ["include"],
+    srcs: ["FuseBuffer.cc", "FuseBridgeLoop.cc"]
+}
+
+cc_test {
+    name: "libappfuse_test",
+    defaults: ["libappfuse_defaults"],
+    shared_libs: ["libappfuse"],
+    srcs: ["tests/FuseBridgeLoopTest.cc", "tests/FuseBufferTest.cc"]
+}
diff --git a/libappfuse/FuseBridgeLoop.cc b/libappfuse/FuseBridgeLoop.cc
new file mode 100644
index 0000000..332556d
--- /dev/null
+++ b/libappfuse/FuseBridgeLoop.cc
@@ -0,0 +1,79 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBridgeLoop.h"
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+
+bool FuseBridgeLoop::Start(
+    int raw_dev_fd, int raw_proxy_fd, FuseBridgeLoop::Callback* callback) {
+  base::unique_fd dev_fd(raw_dev_fd);
+  base::unique_fd proxy_fd(raw_proxy_fd);
+
+  LOG(DEBUG) << "Start fuse loop.";
+  while (true) {
+    if (!buffer_.request.Read(dev_fd)) {
+      return false;
+    }
+
+    const uint32_t opcode = buffer_.request.header.opcode;
+    LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
+    switch (opcode) {
+      case FUSE_FORGET:
+        // Do not reply to FUSE_FORGET.
+        continue;
+
+      case FUSE_LOOKUP:
+      case FUSE_GETATTR:
+      case FUSE_OPEN:
+      case FUSE_READ:
+      case FUSE_WRITE:
+      case FUSE_RELEASE:
+      case FUSE_FLUSH:
+        if (!buffer_.request.Write(proxy_fd)) {
+          LOG(ERROR) << "Failed to write a request to the proxy.";
+          return false;
+        }
+        if (!buffer_.response.Read(proxy_fd)) {
+          LOG(ERROR) << "Failed to read a response from the proxy.";
+          return false;
+        }
+        break;
+
+      case FUSE_INIT:
+        buffer_.HandleInit();
+        break;
+
+      default:
+        buffer_.HandleNotImpl();
+        break;
+    }
+
+    if (!buffer_.response.Write(dev_fd)) {
+      LOG(ERROR) << "Failed to write a response to the device.";
+      return false;
+    }
+
+    if (opcode == FUSE_INIT) {
+      callback->OnMount();
+    }
+  }
+}
+
+}  // namespace android
diff --git a/libappfuse/FuseBuffer.cc b/libappfuse/FuseBuffer.cc
new file mode 100644
index 0000000..45280a5
--- /dev/null
+++ b/libappfuse/FuseBuffer.cc
@@ -0,0 +1,136 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBuffer.h"
+
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <algorithm>
+
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+
+namespace android {
+
+template <typename T, typename Header>
+bool FuseMessage<T, Header>::CheckHeaderLength() const {
+  if (sizeof(Header) <= header.len && header.len <= sizeof(T)) {
+    return true;
+  } else {
+    LOG(ERROR) << "Packet size is invalid=" << header.len;
+    return false;
+  }
+}
+
+template <typename T, typename Header>
+bool FuseMessage<T, Header>::CheckResult(
+    int result, const char* operation_name) const {
+  if (result >= 0 && static_cast<uint32_t>(result) == header.len) {
+    return true;
+  } else {
+    PLOG(ERROR) << "Failed to " << operation_name
+        << " a packet from FD. result=" << result << " header.len="
+        << header.len;
+    return false;
+  }
+}
+
+template <typename T, typename Header>
+bool FuseMessage<T, Header>::Read(int fd) {
+  const ssize_t result = TEMP_FAILURE_RETRY(::read(fd, this, sizeof(T)));
+  return CheckHeaderLength() && CheckResult(result, "read");
+}
+
+template <typename T, typename Header>
+bool FuseMessage<T, Header>::Write(int fd) const {
+  if (!CheckHeaderLength()) {
+    return false;
+  }
+  const ssize_t result = TEMP_FAILURE_RETRY(::write(fd, this, header.len));
+  return CheckResult(result, "write");
+}
+
+template struct FuseMessage<FuseRequest, fuse_in_header>;
+template struct FuseMessage<FuseResponse, fuse_out_header>;
+
+void FuseResponse::ResetHeader(
+    uint32_t data_length, int32_t error, uint64_t unique) {
+  CHECK_LE(error, 0) << "error should be zero or negative.";
+  header.len = sizeof(fuse_out_header) + data_length;
+  header.error = error;
+  header.unique = unique;
+}
+
+void FuseResponse::Reset(uint32_t data_length, int32_t error, uint64_t unique) {
+  memset(this, 0, sizeof(fuse_out_header) + data_length);
+  ResetHeader(data_length, error, unique);
+}
+
+void FuseBuffer::HandleInit() {
+  const fuse_init_in* const in = &request.init_in;
+
+  // Before writing |out|, we need to copy data from |in|.
+  const uint64_t unique = request.header.unique;
+  const uint32_t minor = in->minor;
+  const uint32_t max_readahead = in->max_readahead;
+
+  // Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
+  // defined (fuse version 7.6). The structure is the same from 7.6 through
+  // 7.22. Beginning with 7.23, the structure increased in size and added
+  // new parameters.
+  if (in->major != FUSE_KERNEL_VERSION || in->minor < 6) {
+    LOG(ERROR) << "Fuse kernel version mismatch: Kernel version " << in->major
+        << "." << in->minor << " Expected at least " << FUSE_KERNEL_VERSION
+        << ".6";
+    response.Reset(0, -EPERM, unique);
+    return;
+  }
+
+  // We limit ourselves to 15 because we don't handle BATCH_FORGET yet
+  size_t response_size = sizeof(fuse_init_out);
+#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
+  // FUSE_KERNEL_VERSION >= 23.
+
+  // If the kernel only works on minor revs older than or equal to 22,
+  // then use the older structure size since this code only uses the 7.22
+  // version of the structure.
+  if (minor <= 22) {
+    response_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
+  }
+#endif
+
+  response.Reset(response_size, kFuseSuccess, unique);
+  fuse_init_out* const out = &response.init_out;
+  out->major = FUSE_KERNEL_VERSION;
+  // We limit ourselves to 15 because we don't handle BATCH_FORGET yet.
+  out->minor = std::min(minor, 15u);
+  out->max_readahead = max_readahead;
+  out->flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
+  out->max_background = 32;
+  out->congestion_threshold = 32;
+  out->max_write = kFuseMaxWrite;
+}
+
+void FuseBuffer::HandleNotImpl() {
+  LOG(VERBOSE) << "NOTIMPL op=" << request.header.opcode << " uniq="
+      << request.header.unique << " nid=" << request.header.nodeid;
+  const uint64_t unique = request.header.unique;
+  response.Reset(0, -ENOSYS, unique);
+}
+
+}  // namespace android
diff --git a/libappfuse/include/libappfuse/FuseBridgeLoop.h b/libappfuse/include/libappfuse/FuseBridgeLoop.h
new file mode 100644
index 0000000..2006532
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseBridgeLoop.h
@@ -0,0 +1,40 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
+#define ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
+
+#include "libappfuse/FuseBuffer.h"
+
+namespace android {
+
+class FuseBridgeLoop {
+ public:
+  class Callback {
+   public:
+    virtual void OnMount() = 0;
+    virtual ~Callback() = default;
+  };
+
+  bool Start(int dev_fd, int proxy_fd, Callback* callback);
+
+ private:
+  FuseBuffer buffer_;
+};
+
+}  // namespace android
+
+#endif  // ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
diff --git a/libappfuse/include/libappfuse/FuseBuffer.h b/libappfuse/include/libappfuse/FuseBuffer.h
new file mode 100644
index 0000000..071b777
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseBuffer.h
@@ -0,0 +1,89 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
+#define ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
+
+#include <linux/fuse.h>
+
+namespace android {
+
+// The numbers came from sdcard.c.
+// Maximum number of bytes to write/read in one request/one reply.
+constexpr size_t kFuseMaxWrite = 256 * 1024;
+constexpr size_t kFuseMaxRead = 128 * 1024;
+constexpr int32_t kFuseSuccess = 0;
+
+template<typename T, typename Header>
+struct FuseMessage {
+  Header header;
+  bool Read(int fd);
+  bool Write(int fd) const;
+ private:
+  bool CheckHeaderLength() const;
+  bool CheckResult(int result, const char* operation_name) const;
+};
+
+struct FuseRequest : public FuseMessage<FuseRequest, fuse_in_header> {
+  union {
+    struct {
+      fuse_write_in write_in;
+      char write_data[kFuseMaxWrite];
+    };
+    fuse_open_in open_in;
+    fuse_init_in init_in;
+    fuse_read_in read_in;
+    char lookup_name[0];
+  };
+};
+
+struct FuseResponse : public FuseMessage<FuseResponse, fuse_out_header> {
+  union {
+    fuse_init_out init_out;
+    fuse_entry_out entry_out;
+    fuse_attr_out attr_out;
+    fuse_open_out open_out;
+    char read_data[kFuseMaxRead];
+    fuse_write_out write_out;
+  };
+  void Reset(uint32_t data_length, int32_t error, uint64_t unique);
+  void ResetHeader(uint32_t data_length, int32_t error, uint64_t unique);
+};
+
+union FuseBuffer {
+  FuseRequest request;
+  FuseResponse response;
+
+  void HandleInit();
+  void HandleNotImpl();
+};
+
+class FuseProxyLoop {
+  class IFuseProxyLoopCallback {
+   public:
+    virtual void OnMount() = 0;
+    virtual ~IFuseProxyLoopCallback() = default;
+  };
+
+  bool Start(int dev_fd, int proxy_fd, IFuseProxyLoopCallback* callback);
+
+ private:
+  FuseBuffer buffer_;
+};
+
+}  // namespace android
+
+#endif  // ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
diff --git a/libappfuse/tests/FuseBridgeLoopTest.cc b/libappfuse/tests/FuseBridgeLoopTest.cc
new file mode 100644
index 0000000..31e3690
--- /dev/null
+++ b/libappfuse/tests/FuseBridgeLoopTest.cc
@@ -0,0 +1,196 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBridgeLoop.h"
+
+#include <sys/socket.h>
+
+#include <sstream>
+#include <thread>
+
+#include <gtest/gtest.h>
+
+namespace android {
+
+class Callback : public FuseBridgeLoop::Callback {
+ public:
+  bool mounted;
+  Callback() : mounted(false) {}
+  void OnMount() override {
+    mounted = true;
+  }
+};
+
+class FuseBridgeLoopTest : public ::testing::Test {
+ protected:
+  int dev_sockets_[2];
+  int proxy_sockets_[2];
+  Callback callback_;
+  std::thread thread_;
+
+  FuseRequest request_;
+  FuseResponse response_;
+
+  void SetUp() {
+    ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, dev_sockets_));
+    ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, proxy_sockets_));
+    thread_ = std::thread([this] {
+      FuseBridgeLoop loop;
+      loop.Start(dev_sockets_[1], proxy_sockets_[0], &callback_);
+    });
+  }
+
+  void CheckNotImpl(uint32_t opcode) {
+    SCOPED_TRACE((std::ostringstream() << "opcode: " << opcode).str());
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = opcode;
+    request_.header.len = sizeof(fuse_in_header);
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+    EXPECT_EQ(-ENOSYS, response_.header.error);
+  }
+
+  void CheckProxy(uint32_t opcode) {
+    SCOPED_TRACE((std::ostringstream() << "opcode: " << opcode).str());
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = opcode;
+    request_.header.unique = opcode; // Use opcode as unique.
+    request_.header.len = sizeof(fuse_in_header);
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    ASSERT_TRUE(request_.Read(proxy_sockets_[1]));
+    EXPECT_EQ(opcode, request_.header.opcode);
+    EXPECT_EQ(opcode, request_.header.unique);
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    response_.header.len = sizeof(fuse_out_header);
+    response_.header.unique = opcode;  // Use opcode as unique.
+    response_.header.error = kFuseSuccess;
+    ASSERT_TRUE(response_.Write(proxy_sockets_[1]));
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+    EXPECT_EQ(opcode, response_.header.unique);
+    EXPECT_EQ(kFuseSuccess, response_.header.error);
+  }
+
+  void SendInitRequest(uint64_t unique) {
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = FUSE_INIT;
+    request_.header.unique = unique;
+    request_.header.len = sizeof(fuse_in_header) + sizeof(fuse_init_in);
+    request_.init_in.major = FUSE_KERNEL_VERSION;
+    request_.init_in.minor = FUSE_KERNEL_MINOR_VERSION;
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+  }
+
+  void Close() {
+    close(dev_sockets_[0]);
+    close(dev_sockets_[1]);
+    close(proxy_sockets_[0]);
+    close(proxy_sockets_[1]);
+    if (thread_.joinable()) {
+      thread_.join();
+    }
+  }
+
+  void TearDown() {
+    Close();
+  }
+};
+
+TEST_F(FuseBridgeLoopTest, FuseInit) {
+  SendInitRequest(1u);
+
+  memset(&response_, 0, sizeof(FuseResponse));
+  ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+  EXPECT_EQ(kFuseSuccess, response_.header.error);
+  EXPECT_EQ(1u, response_.header.unique);
+
+  // Unmount.
+  Close();
+  EXPECT_TRUE(callback_.mounted);
+}
+
+TEST_F(FuseBridgeLoopTest, FuseForget) {
+  memset(&request_, 0, sizeof(FuseRequest));
+  request_.header.opcode = FUSE_FORGET;
+  request_.header.unique = 1u;
+  request_.header.len = sizeof(fuse_in_header) + sizeof(fuse_forget_in);
+  ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+  SendInitRequest(2u);
+
+  memset(&response_, 0, sizeof(FuseResponse));
+  ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+  EXPECT_EQ(2u, response_.header.unique) <<
+      "The loop must not respond to FUSE_FORGET";
+}
+
+TEST_F(FuseBridgeLoopTest, FuseNotImpl) {
+  CheckNotImpl(FUSE_SETATTR);
+  CheckNotImpl(FUSE_READLINK);
+  CheckNotImpl(FUSE_SYMLINK);
+  CheckNotImpl(FUSE_MKNOD);
+  CheckNotImpl(FUSE_MKDIR);
+  CheckNotImpl(FUSE_UNLINK);
+  CheckNotImpl(FUSE_RMDIR);
+  CheckNotImpl(FUSE_RENAME);
+  CheckNotImpl(FUSE_LINK);
+  CheckNotImpl(FUSE_STATFS);
+  CheckNotImpl(FUSE_FSYNC);
+  CheckNotImpl(FUSE_SETXATTR);
+  CheckNotImpl(FUSE_GETXATTR);
+  CheckNotImpl(FUSE_LISTXATTR);
+  CheckNotImpl(FUSE_REMOVEXATTR);
+  CheckNotImpl(FUSE_OPENDIR);
+  CheckNotImpl(FUSE_READDIR);
+  CheckNotImpl(FUSE_RELEASEDIR);
+  CheckNotImpl(FUSE_FSYNCDIR);
+  CheckNotImpl(FUSE_GETLK);
+  CheckNotImpl(FUSE_SETLK);
+  CheckNotImpl(FUSE_SETLKW);
+  CheckNotImpl(FUSE_ACCESS);
+  CheckNotImpl(FUSE_CREATE);
+  CheckNotImpl(FUSE_INTERRUPT);
+  CheckNotImpl(FUSE_BMAP);
+  CheckNotImpl(FUSE_DESTROY);
+  CheckNotImpl(FUSE_IOCTL);
+  CheckNotImpl(FUSE_POLL);
+  CheckNotImpl(FUSE_NOTIFY_REPLY);
+  CheckNotImpl(FUSE_BATCH_FORGET);
+  CheckNotImpl(FUSE_FALLOCATE);
+  CheckNotImpl(FUSE_READDIRPLUS);
+  CheckNotImpl(FUSE_RENAME2);
+  CheckNotImpl(FUSE_LSEEK);
+}
+
+TEST_F(FuseBridgeLoopTest, Proxy) {
+  CheckProxy(FUSE_LOOKUP);
+  CheckProxy(FUSE_GETATTR);
+  CheckProxy(FUSE_OPEN);
+  CheckProxy(FUSE_READ);
+  CheckProxy(FUSE_WRITE);
+  CheckProxy(FUSE_RELEASE);
+  CheckProxy(FUSE_FLUSH);
+}
+
+}  // android
diff --git a/libappfuse/tests/FuseBufferTest.cc b/libappfuse/tests/FuseBufferTest.cc
new file mode 100644
index 0000000..1aacfe3
--- /dev/null
+++ b/libappfuse/tests/FuseBufferTest.cc
@@ -0,0 +1,187 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBuffer.h"
+
+#include <fcntl.h>
+#include <string.h>
+#include <sys/socket.h>
+
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+
+namespace android {
+
+constexpr char kTempFile[] = "/data/local/tmp/appfuse_test_dump";
+
+void OpenTempFile(android::base::unique_fd* fd) {
+  fd->reset(open(kTempFile, O_CREAT | O_RDWR));
+  ASSERT_NE(-1, *fd) << strerror(errno);
+  unlink(kTempFile);
+  ASSERT_NE(-1, *fd) << strerror(errno);
+}
+
+void TestReadInvalidLength(size_t headerSize, size_t write_size) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  char buffer[std::max(headerSize, sizeof(FuseRequest))];
+  FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer);
+  packet->header.len = headerSize;
+  ASSERT_NE(-1, write(fd, packet, write_size)) << strerror(errno);
+
+  lseek(fd, 0, SEEK_SET);
+  EXPECT_FALSE(packet->Read(fd));
+}
+
+void TestWriteInvalidLength(size_t size) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  char buffer[std::max(size, sizeof(FuseRequest))];
+  FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer);
+  packet->header.len = size;
+  EXPECT_FALSE(packet->Write(fd));
+}
+
+// Use FuseRequest as a template instance of FuseMessage.
+
+TEST(FuseMessageTest, ReadAndWrite) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  FuseRequest request;
+  request.header.len = sizeof(FuseRequest);
+  request.header.opcode = 1;
+  request.header.unique = 2;
+  request.header.nodeid = 3;
+  request.header.uid = 4;
+  request.header.gid = 5;
+  request.header.pid = 6;
+  strcpy(request.lookup_name, "test");
+
+  ASSERT_TRUE(request.Write(fd));
+
+  memset(&request, 0, sizeof(FuseRequest));
+  lseek(fd, 0, SEEK_SET);
+
+  ASSERT_TRUE(request.Read(fd));
+  EXPECT_EQ(sizeof(FuseRequest), request.header.len);
+  EXPECT_EQ(1u, request.header.opcode);
+  EXPECT_EQ(2u, request.header.unique);
+  EXPECT_EQ(3u, request.header.nodeid);
+  EXPECT_EQ(4u, request.header.uid);
+  EXPECT_EQ(5u, request.header.gid);
+  EXPECT_EQ(6u, request.header.pid);
+  EXPECT_STREQ("test", request.lookup_name);
+}
+
+TEST(FuseMessageTest, Read_InconsistentLength) {
+  TestReadInvalidLength(sizeof(fuse_in_header), sizeof(fuse_in_header) + 1);
+}
+
+TEST(FuseMessageTest, Read_TooLong) {
+  TestReadInvalidLength(sizeof(FuseRequest) + 1, sizeof(FuseRequest) + 1);
+}
+
+TEST(FuseMessageTest, Read_TooShort) {
+  TestReadInvalidLength(sizeof(fuse_in_header) - 1, sizeof(fuse_in_header) - 1);
+}
+
+TEST(FuseMessageTest, Write_TooLong) {
+  TestWriteInvalidLength(sizeof(FuseRequest) + 1);
+}
+
+TEST(FuseMessageTest, Write_TooShort) {
+  TestWriteInvalidLength(sizeof(fuse_in_header) - 1);
+}
+
+TEST(FuseResponseTest, Reset) {
+  FuseResponse response;
+  // Write 1 to the first ten bytes.
+  memset(response.read_data, 'a', 10);
+
+  response.Reset(0, -1, 2);
+  EXPECT_EQ(sizeof(fuse_out_header), response.header.len);
+  EXPECT_EQ(-1, response.header.error);
+  EXPECT_EQ(2u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+
+  response.Reset(5, -4, 3);
+  EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len);
+  EXPECT_EQ(-4, response.header.error);
+  EXPECT_EQ(3u, response.header.unique);
+  EXPECT_EQ(0, response.read_data[0]);
+  EXPECT_EQ(0, response.read_data[1]);
+  EXPECT_EQ(0, response.read_data[2]);
+  EXPECT_EQ(0, response.read_data[3]);
+  EXPECT_EQ(0, response.read_data[4]);
+  EXPECT_EQ('a', response.read_data[5]);
+}
+
+TEST(FuseResponseTest, ResetHeader) {
+  FuseResponse response;
+  // Write 1 to the first ten bytes.
+  memset(response.read_data, 'a', 10);
+
+  response.ResetHeader(0, -1, 2);
+  EXPECT_EQ(sizeof(fuse_out_header), response.header.len);
+  EXPECT_EQ(-1, response.header.error);
+  EXPECT_EQ(2u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+
+  response.ResetHeader(5, -4, 3);
+  EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len);
+  EXPECT_EQ(-4, response.header.error);
+  EXPECT_EQ(3u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+}
+
+TEST(FuseBufferTest, HandleInit) {
+  FuseBuffer buffer;
+  memset(&buffer, 0, sizeof(FuseBuffer));
+
+  buffer.request.header.opcode = FUSE_INIT;
+  buffer.request.init_in.major = FUSE_KERNEL_VERSION;
+  buffer.request.init_in.minor = FUSE_KERNEL_MINOR_VERSION;
+
+  buffer.HandleInit();
+
+  ASSERT_EQ(sizeof(fuse_out_header) + sizeof(fuse_init_out),
+            buffer.response.header.len);
+  EXPECT_EQ(kFuseSuccess, buffer.response.header.error);
+  EXPECT_EQ(static_cast<unsigned int>(FUSE_KERNEL_VERSION),
+            buffer.response.init_out.major);
+  EXPECT_EQ(15u, buffer.response.init_out.minor);
+  EXPECT_EQ(static_cast<unsigned int>(FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES),
+      buffer.response.init_out.flags);
+  EXPECT_EQ(kFuseMaxWrite, buffer.response.init_out.max_write);
+}
+
+TEST(FuseBufferTest, HandleNotImpl) {
+  FuseBuffer buffer;
+  memset(&buffer, 0, sizeof(FuseBuffer));
+
+  buffer.HandleNotImpl();
+
+  ASSERT_EQ(sizeof(fuse_out_header), buffer.response.header.len);
+  EXPECT_EQ(-ENOSYS, buffer.response.header.error);
+}
+}
+  // namespace android
diff --git a/liblog/log_is_loggable.c b/liblog/log_is_loggable.c
index 132d96f..dda09e0 100644
--- a/liblog/log_is_loggable.c
+++ b/liblog/log_is_loggable.c
@@ -23,8 +23,6 @@
 #include <sys/_system_properties.h>
 #include <unistd.h>
 
-#include <android/log.h>
-#include <log/logger.h>
 #include <private/android_logger.h>
 
 #include "log_portability.h"