Merge changes from topic "squashfs+overlayfs"

* changes:
  init: add fs_mgr_overlayfs_mount_all to FirstStageMount
  adb: add overlayfs handling for readonly system filesystems
  fs_mgr: get fs_mgr_mount_all to call fs_mgr_overlayfs_mount_all
  fs_mgr: add overlayfs handling for squashfs system filesystems
diff --git a/adb/Android.bp b/adb/Android.bp
index 906c5e3..dabc5ce 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -449,7 +449,7 @@
     test_suites: ["device-tests"],
 }
 
-python_binary_host {
+python_test_host {
     name: "adb_integration_test_adb",
     main: "test_adb.py",
     srcs: [
@@ -458,6 +458,8 @@
     libs: [
         "adb_py",
     ],
+    test_config: "adb_integration_test_adb.xml",
+    test_suites: ["general-tests"],
     version: {
         py2: {
             enabled: true,
diff --git a/adb/adb_integration_test_adb.xml b/adb/adb_integration_test_adb.xml
new file mode 100644
index 0000000..e722956
--- /dev/null
+++ b/adb/adb_integration_test_adb.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 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.
+-->
+<configuration description="Config to run adb integration tests">
+    <option name="test-suite-tag" value="adb_tests" />
+    <option name="test-suite-tag" value="adb_integration" />
+    <target_preparer class="com.android.tradefed.targetprep.SemaphoreTokenTargetPreparer">
+        <option name="disable" value="false" />
+    </target_preparer>
+
+    <target_preparer class="com.android.tradefed.targetprep.adb.AdbStopServerPreparer" />
+    <test class="com.android.tradefed.testtype.python.PythonBinaryHostTest" >
+        <option name="par-file-name" value="adb_integration_test_adb" />
+        <option name="inject-android-serial" value="true" />
+        <option name="test-timeout" value="2m" />
+    </test>
+</configuration>
diff --git a/base/Android.bp b/base/Android.bp
index 46a0233..3d80d97 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -135,7 +135,6 @@
         "strings_test.cpp",
         "test_main.cpp",
         "test_utils_test.cpp",
-        "unique_fd_test.cpp",
     ],
     target: {
         android: {
diff --git a/base/include/android-base/parsedouble.h b/base/include/android-base/parsedouble.h
index c273c61..7b1c648 100644
--- a/base/include/android-base/parsedouble.h
+++ b/base/include/android-base/parsedouble.h
@@ -24,24 +24,43 @@
 namespace android {
 namespace base {
 
-// Parse double value in the string 's' and sets 'out' to that value.
+// Parse floating value in the string 's' and sets 'out' to that value if it exists.
 // Optionally allows the caller to define a 'min' and 'max' beyond which
 // otherwise valid values will be rejected. Returns boolean success.
-static inline bool ParseDouble(const char* s, double* out,
-                               double min = std::numeric_limits<double>::lowest(),
-                               double max = std::numeric_limits<double>::max()) {
+template <typename T, T (*strtox)(const char* str, char** endptr)>
+static inline bool ParseFloatingPoint(const char* s, T* out, T min, T max) {
   errno = 0;
   char* end;
-  double result = strtod(s, &end);
+  T result = strtox(s, &end);
   if (errno != 0 || s == end || *end != '\0') {
     return false;
   }
   if (result < min || max < result) {
     return false;
   }
-  *out = result;
+  if (out != nullptr) {
+    *out = result;
+  }
   return true;
 }
 
+// Parse double value in the string 's' and sets 'out' to that value if it exists.
+// Optionally allows the caller to define a 'min' and 'max' beyond which
+// otherwise valid values will be rejected. Returns boolean success.
+static inline bool ParseDouble(const char* s, double* out,
+                               double min = std::numeric_limits<double>::lowest(),
+                               double max = std::numeric_limits<double>::max()) {
+  return ParseFloatingPoint<double, strtod>(s, out, min, max);
+}
+
+// Parse float value in the string 's' and sets 'out' to that value if it exists.
+// Optionally allows the caller to define a 'min' and 'max' beyond which
+// otherwise valid values will be rejected. Returns boolean success.
+static inline bool ParseFloat(const char* s, float* out,
+                              float min = std::numeric_limits<float>::lowest(),
+                              float max = std::numeric_limits<float>::max()) {
+  return ParseFloatingPoint<float, strtof>(s, out, min, max);
+}
+
 }  // namespace base
 }  // namespace android
diff --git a/base/include/android-base/parseint.h b/base/include/android-base/parseint.h
index bb54c99..55f1ed3 100644
--- a/base/include/android-base/parseint.h
+++ b/base/include/android-base/parseint.h
@@ -27,9 +27,9 @@
 namespace base {
 
 // Parses the unsigned decimal or hexadecimal integer in the string 's' and sets
-// 'out' to that value. Optionally allows the caller to define a 'max' beyond
-// which otherwise valid values will be rejected. Returns boolean success; 'out'
-// is untouched if parsing fails.
+// 'out' to that value if it is specified. Optionally allows the caller to define
+// a 'max' beyond which otherwise valid values will be rejected. Returns boolean
+// success; 'out' is untouched if parsing fails.
 template <typename T>
 bool ParseUint(const char* s, T* out, T max = std::numeric_limits<T>::max(),
                bool allow_suffixes = false) {
@@ -72,9 +72,9 @@
 }
 
 // Parses the signed decimal or hexadecimal integer in the string 's' and sets
-// 'out' to that value. Optionally allows the caller to define a 'min' and 'max'
-// beyond which otherwise valid values will be rejected. Returns boolean
-// success; 'out' is untouched if parsing fails.
+// 'out' to that value if it is specified. Optionally allows the caller to define
+// a 'min' and 'max' beyond which otherwise valid values will be rejected. Returns
+// boolean success; 'out' is untouched if parsing fails.
 template <typename T>
 bool ParseInt(const char* s, T* out,
               T min = std::numeric_limits<T>::min(),
diff --git a/base/parsedouble_test.cpp b/base/parsedouble_test.cpp
index 8734c42..ec3c10c 100644
--- a/base/parsedouble_test.cpp
+++ b/base/parsedouble_test.cpp
@@ -18,7 +18,7 @@
 
 #include <gtest/gtest.h>
 
-TEST(parsedouble, smoke) {
+TEST(parsedouble, double_smoke) {
   double d;
   ASSERT_FALSE(android::base::ParseDouble("", &d));
   ASSERT_FALSE(android::base::ParseDouble("x", &d));
@@ -35,4 +35,33 @@
   ASSERT_FALSE(android::base::ParseDouble("3.0", &d, -1.0, 2.0));
   ASSERT_TRUE(android::base::ParseDouble("1.0", &d, 0.0, 2.0));
   ASSERT_DOUBLE_EQ(1.0, d);
+
+  ASSERT_FALSE(android::base::ParseDouble("123.4x", nullptr));
+  ASSERT_TRUE(android::base::ParseDouble("-123.4", nullptr));
+  ASSERT_FALSE(android::base::ParseDouble("3.0", nullptr, -1.0, 2.0));
+  ASSERT_TRUE(android::base::ParseDouble("1.0", nullptr, 0.0, 2.0));
+}
+
+TEST(parsedouble, float_smoke) {
+  float f;
+  ASSERT_FALSE(android::base::ParseFloat("", &f));
+  ASSERT_FALSE(android::base::ParseFloat("x", &f));
+  ASSERT_FALSE(android::base::ParseFloat("123.4x", &f));
+
+  ASSERT_TRUE(android::base::ParseFloat("123.4", &f));
+  ASSERT_FLOAT_EQ(123.4, f);
+  ASSERT_TRUE(android::base::ParseFloat("-123.4", &f));
+  ASSERT_FLOAT_EQ(-123.4, f);
+
+  ASSERT_TRUE(android::base::ParseFloat("0", &f, 0.0));
+  ASSERT_FLOAT_EQ(0.0, f);
+  ASSERT_FALSE(android::base::ParseFloat("0", &f, 1e-9));
+  ASSERT_FALSE(android::base::ParseFloat("3.0", &f, -1.0, 2.0));
+  ASSERT_TRUE(android::base::ParseFloat("1.0", &f, 0.0, 2.0));
+  ASSERT_FLOAT_EQ(1.0, f);
+
+  ASSERT_FALSE(android::base::ParseFloat("123.4x", nullptr));
+  ASSERT_TRUE(android::base::ParseFloat("-123.4", nullptr));
+  ASSERT_FALSE(android::base::ParseFloat("3.0", nullptr, -1.0, 2.0));
+  ASSERT_TRUE(android::base::ParseFloat("1.0", nullptr, 0.0, 2.0));
 }
diff --git a/base/unique_fd_test.cpp b/base/unique_fd_test.cpp
deleted file mode 100644
index 3fdf12a..0000000
--- a/base/unique_fd_test.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2018 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 "android-base/unique_fd.h"
-
-#include <gtest/gtest.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-using android::base::unique_fd;
-
-TEST(unique_fd, unowned_close) {
-#if defined(__BIONIC__)
-  unique_fd fd(open("/dev/null", O_RDONLY));
-  EXPECT_DEATH(close(fd.get()), "incorrect tag");
-#endif
-}
-
-TEST(unique_fd, untag_on_release) {
-  unique_fd fd(open("/dev/null", O_RDONLY));
-  close(fd.release());
-}
-
-TEST(unique_fd, move) {
-  unique_fd fd(open("/dev/null", O_RDONLY));
-  unique_fd fd_moved = std::move(fd);
-  ASSERT_EQ(-1, fd.get());
-  ASSERT_GT(fd_moved.get(), -1);
-}
-
-TEST(unique_fd, unowned_close_after_move) {
-#if defined(__BIONIC__)
-  unique_fd fd(open("/dev/null", O_RDONLY));
-  unique_fd fd_moved = std::move(fd);
-  ASSERT_EQ(-1, fd.get());
-  ASSERT_GT(fd_moved.get(), -1);
-  EXPECT_DEATH(close(fd_moved.get()), "incorrect tag");
-#endif
-}
diff --git a/fastboot/Android.bp b/fastboot/Android.bp
index aa88a8a..9995052 100644
--- a/fastboot/Android.bp
+++ b/fastboot/Android.bp
@@ -94,6 +94,7 @@
     srcs: [
         "device/commands.cpp",
         "device/fastboot_device.cpp",
+        "device/flashing.cpp",
         "device/main.cpp",
         "device/usb_client.cpp",
         "device/utility.cpp",
@@ -101,23 +102,21 @@
     ],
 
     shared_libs: [
-        "libasyncio",
-        "libext4_utils",
-        "libsparse",
-        "liblog",
         "android.hardware.boot@1.0",
-        "libbootloader_message",
-        "libhidltransport",
-        "libhidlbase",
-        "libhwbinder",
-        "libbase",
-        "libutils",
-        "libcutils",
-        "libfs_mgr",
-    ],
-
-    static_libs: [
         "libadbd",
+        "libasyncio",
+        "libbase",
+        "libbootloader_message",
+        "libcutils",
+        "libext4_utils",
+        "libfs_mgr",
+        "libhidlbase",
+        "libhidltransport",
+        "libhwbinder",
+        "liblog",
+        "liblp",
+        "libsparse",
+        "libutils",
     ],
 
     cpp_std: "c++17",
diff --git a/fastboot/device/commands.cpp b/fastboot/device/commands.cpp
index ac381fb..7eaefe6 100644
--- a/fastboot/device/commands.cpp
+++ b/fastboot/device/commands.cpp
@@ -26,9 +26,11 @@
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <cutils/android_reboot.h>
+#include <ext4_utils/wipe.h>
 
 #include "constants.h"
 #include "fastboot_device.h"
+#include "flashing.h"
 #include "utility.h"
 
 using ::android::hardware::hidl_string;
@@ -37,8 +39,7 @@
 using ::android::hardware::boot::V1_0::Slot;
 
 bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
-    using VariableHandler =
-            std::function<std::string(FastbootDevice*, const std::vector<std::string>&)>;
+    using VariableHandler = std::function<bool(FastbootDevice*, const std::vector<std::string>&)>;
     const std::unordered_map<std::string, VariableHandler> kVariableMap = {
             {FB_VAR_VERSION, GetVersion},
             {FB_VAR_VERSION_BOOTLOADER, GetBootloaderVersion},
@@ -52,7 +53,8 @@
             {FB_VAR_SLOT_COUNT, GetSlotCount},
             {FB_VAR_HAS_SLOT, GetHasSlot},
             {FB_VAR_SLOT_SUCCESSFUL, GetSlotSuccessful},
-            {FB_VAR_SLOT_UNBOOTABLE, GetSlotUnbootable}};
+            {FB_VAR_SLOT_UNBOOTABLE, GetSlotUnbootable},
+            {FB_VAR_PARTITION_SIZE, GetPartitionSize}};
 
     // args[0] is command name, args[1] is variable.
     auto found_variable = kVariableMap.find(args[1]);
@@ -61,8 +63,21 @@
     }
 
     std::vector<std::string> getvar_args(args.begin() + 2, args.end());
-    auto result = found_variable->second(device, getvar_args);
-    return device->WriteStatus(FastbootResult::OKAY, result);
+    return found_variable->second(device, getvar_args);
+}
+
+bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
+    if (args.size() < 2) {
+        return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
+    }
+    PartitionHandle handle;
+    if (!OpenPartition(device, args[1], &handle)) {
+        return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
+    }
+    if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
+        return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
+    }
+    return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
 }
 
 bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
@@ -74,12 +89,12 @@
     if (!android::base::ParseUint("0x" + args[1], &size, UINT_MAX)) {
         return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
     }
-    device->get_download_data().resize(size);
+    device->download_data().resize(size);
     if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
         return false;
     }
 
-    if (device->HandleData(true, &device->get_download_data())) {
+    if (device->HandleData(true, &device->download_data())) {
         return device->WriteStatus(FastbootResult::OKAY, "");
     }
 
@@ -87,6 +102,17 @@
     return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
 }
 
+bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
+    if (args.size() < 2) {
+        return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
+    }
+    int ret = Flash(device, args[1]);
+    if (ret < 0) {
+        return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
+    }
+    return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
+}
+
 bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
     if (args.size() < 2) {
         return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
diff --git a/fastboot/device/commands.h b/fastboot/device/commands.h
index 8785b91..830eb55 100644
--- a/fastboot/device/commands.h
+++ b/fastboot/device/commands.h
@@ -39,3 +39,5 @@
 bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& args);
 bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& args);
 bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args);
+bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args);
+bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args);
diff --git a/fastboot/device/fastboot_device.cpp b/fastboot/device/fastboot_device.cpp
index f61e5c2..b94fbb0 100644
--- a/fastboot/device/fastboot_device.cpp
+++ b/fastboot/device/fastboot_device.cpp
@@ -23,6 +23,7 @@
 #include <algorithm>
 
 #include "constants.h"
+#include "flashing.h"
 #include "usb_client.h"
 
 using ::android::hardware::hidl_string;
@@ -40,6 +41,8 @@
               {FB_CMD_REBOOT_BOOTLOADER, RebootBootloaderHandler},
               {FB_CMD_REBOOT_FASTBOOT, RebootFastbootHandler},
               {FB_CMD_REBOOT_RECOVERY, RebootRecoveryHandler},
+              {FB_CMD_ERASE, EraseHandler},
+              {FB_CMD_FLASH, FlashHandler},
       }),
       transport_(std::make_unique<ClientUsbTransport>()),
       boot_control_hal_(IBootControl::getService()) {}
@@ -122,3 +125,11 @@
         }
     }
 }
+
+bool FastbootDevice::WriteOkay(const std::string& message) {
+    return WriteStatus(FastbootResult::OKAY, message);
+}
+
+bool FastbootDevice::WriteFail(const std::string& message) {
+    return WriteStatus(FastbootResult::FAIL, message);
+}
diff --git a/fastboot/device/fastboot_device.h b/fastboot/device/fastboot_device.h
index 1092499..addc2ef 100644
--- a/fastboot/device/fastboot_device.h
+++ b/fastboot/device/fastboot_device.h
@@ -39,9 +39,11 @@
     bool HandleData(bool read, std::vector<char>* data);
     std::string GetCurrentSlot();
 
-    std::vector<char>& get_download_data() { return download_data_; }
-    void set_upload_data(const std::vector<char>& data) { upload_data_ = data; }
-    void set_upload_data(std::vector<char>&& data) { upload_data_ = std::move(data); }
+    // Shortcuts for writing OKAY and FAIL status results.
+    bool WriteOkay(const std::string& message);
+    bool WriteFail(const std::string& message);
+
+    std::vector<char>& download_data() { return download_data_; }
     Transport* get_transport() { return transport_.get(); }
     android::sp<android::hardware::boot::V1_0::IBootControl> boot_control_hal() {
         return boot_control_hal_;
@@ -53,5 +55,4 @@
     std::unique_ptr<Transport> transport_;
     android::sp<android::hardware::boot::V1_0::IBootControl> boot_control_hal_;
     std::vector<char> download_data_;
-    std::vector<char> upload_data_;
 };
diff --git a/fastboot/device/flashing.cpp b/fastboot/device/flashing.cpp
new file mode 100644
index 0000000..b5ed170
--- /dev/null
+++ b/fastboot/device/flashing.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2018 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 "flashing.h"
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <memory>
+
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <ext4_utils/ext4_utils.h>
+#include <sparse/sparse.h>
+
+#include "fastboot_device.h"
+#include "utility.h"
+
+namespace {
+
+constexpr uint32_t SPARSE_HEADER_MAGIC = 0xed26ff3a;
+
+}  // namespace
+
+int FlashRawDataChunk(int fd, const char* data, size_t len) {
+    size_t ret = 0;
+    while (ret < len) {
+        int this_len = std::min(static_cast<size_t>(1048576UL * 8), len - ret);
+        int this_ret = write(fd, data, this_len);
+        if (this_ret < 0) {
+            PLOG(ERROR) << "Failed to flash data of len " << len;
+            return -1;
+        }
+        data += this_ret;
+        ret += this_ret;
+    }
+    return 0;
+}
+
+int FlashRawData(int fd, const std::vector<char>& downloaded_data) {
+    int ret = FlashRawDataChunk(fd, downloaded_data.data(), downloaded_data.size());
+    if (ret < 0) {
+        return -errno;
+    }
+    return ret;
+}
+
+int WriteCallback(void* priv, const void* data, size_t len) {
+    int fd = reinterpret_cast<long long>(priv);
+    if (!data) {
+        return lseek64(fd, len, SEEK_CUR) >= 0 ? 0 : -errno;
+    }
+    return FlashRawDataChunk(fd, reinterpret_cast<const char*>(data), len);
+}
+
+int FlashSparseData(int fd, std::vector<char>& downloaded_data) {
+    struct sparse_file* file = sparse_file_import_buf(downloaded_data.data(), true, false);
+    if (!file) {
+        return -ENOENT;
+    }
+    return sparse_file_callback(file, false, false, WriteCallback, reinterpret_cast<void*>(fd));
+}
+
+int FlashBlockDevice(int fd, std::vector<char>& downloaded_data) {
+    lseek64(fd, 0, SEEK_SET);
+    if (downloaded_data.size() >= sizeof(SPARSE_HEADER_MAGIC) &&
+        *reinterpret_cast<uint32_t*>(downloaded_data.data()) == SPARSE_HEADER_MAGIC) {
+        return FlashSparseData(fd, downloaded_data);
+    } else {
+        return FlashRawData(fd, downloaded_data);
+    }
+}
+
+int Flash(FastbootDevice* device, const std::string& partition_name) {
+    PartitionHandle handle;
+    if (!OpenPartition(device, partition_name, &handle)) {
+        return -ENOENT;
+    }
+
+    std::vector<char> data = std::move(device->download_data());
+    if (data.size() == 0) {
+        return -EINVAL;
+    } else if (data.size() > get_block_device_size(handle.fd())) {
+        return -EOVERFLOW;
+    }
+    return FlashBlockDevice(handle.fd(), data);
+}
diff --git a/fastboot/device/flashing.h b/fastboot/device/flashing.h
new file mode 100644
index 0000000..206a407
--- /dev/null
+++ b/fastboot/device/flashing.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+
+class FastbootDevice;
+
+int Flash(FastbootDevice* device, const std::string& partition_name);
diff --git a/fastboot/device/utility.cpp b/fastboot/device/utility.cpp
index c8d2b3e..ec84576 100644
--- a/fastboot/device/utility.cpp
+++ b/fastboot/device/utility.cpp
@@ -16,8 +16,103 @@
 
 #include "utility.h"
 
+#include <android-base/logging.h>
+#include <fs_mgr_dm_linear.h>
+#include <liblp/liblp.h>
+
+#include "fastboot_device.h"
+
+using namespace android::fs_mgr;
+using android::base::unique_fd;
 using android::hardware::boot::V1_0::Slot;
 
+static bool OpenPhysicalPartition(const std::string& name, PartitionHandle* handle) {
+    std::optional<std::string> path = FindPhysicalPartition(name);
+    if (!path) {
+        return false;
+    }
+    *handle = PartitionHandle(*path);
+    return true;
+}
+
+static bool OpenLogicalPartition(const std::string& name, const std::string& slot,
+                                 PartitionHandle* handle) {
+    std::optional<std::string> path = FindPhysicalPartition(LP_METADATA_PARTITION_NAME);
+    if (!path) {
+        return false;
+    }
+    uint32_t slot_number = SlotNumberForSlotSuffix(slot);
+    std::string dm_path;
+    if (!CreateLogicalPartition(path->c_str(), slot_number, name, true, &dm_path)) {
+        LOG(ERROR) << "Could not map partition: " << name;
+        return false;
+    }
+    auto closer = [name]() -> void { DestroyLogicalPartition(name); };
+    *handle = PartitionHandle(dm_path, std::move(closer));
+    return true;
+}
+
+bool OpenPartition(FastbootDevice* device, const std::string& name, PartitionHandle* handle) {
+    // We prioritize logical partitions over physical ones, and do this
+    // consistently for other partition operations (like getvar:partition-size).
+    if (LogicalPartitionExists(name, device->GetCurrentSlot())) {
+        if (!OpenLogicalPartition(name, device->GetCurrentSlot(), handle)) {
+            return false;
+        }
+    } else if (!OpenPhysicalPartition(name, handle)) {
+        LOG(ERROR) << "No such partition: " << name;
+        return false;
+    }
+
+    unique_fd fd(TEMP_FAILURE_RETRY(open(handle->path().c_str(), O_WRONLY | O_EXCL)));
+    if (fd < 0) {
+        PLOG(ERROR) << "Failed to open block device: " << handle->path();
+        return false;
+    }
+    handle->set_fd(std::move(fd));
+    return true;
+}
+
+std::optional<std::string> FindPhysicalPartition(const std::string& name) {
+    std::string path = "/dev/block/by-name/" + name;
+    if (access(path.c_str(), R_OK | W_OK) < 0) {
+        return {};
+    }
+    return path;
+}
+
+static const LpMetadataPartition* FindLogicalPartition(const LpMetadata& metadata,
+                                                       const std::string& name) {
+    for (const auto& partition : metadata.partitions) {
+        if (GetPartitionName(partition) == name) {
+            return &partition;
+        }
+    }
+    return nullptr;
+}
+
+bool LogicalPartitionExists(const std::string& name, const std::string& slot_suffix,
+                            bool* is_zero_length) {
+    auto path = FindPhysicalPartition(LP_METADATA_PARTITION_NAME);
+    if (!path) {
+        return false;
+    }
+
+    uint32_t slot_number = SlotNumberForSlotSuffix(slot_suffix);
+    std::unique_ptr<LpMetadata> metadata = ReadMetadata(path->c_str(), slot_number);
+    if (!metadata) {
+        return false;
+    }
+    const LpMetadataPartition* partition = FindLogicalPartition(*metadata.get(), name);
+    if (!partition) {
+        return false;
+    }
+    if (is_zero_length) {
+        *is_zero_length = (partition->num_extents == 0);
+    }
+    return true;
+}
+
 bool GetSlotNumber(const std::string& slot, Slot* number) {
     if (slot.size() != 1) {
         return false;
diff --git a/fastboot/device/utility.h b/fastboot/device/utility.h
index 867d693..0931fc3 100644
--- a/fastboot/device/utility.h
+++ b/fastboot/device/utility.h
@@ -15,8 +15,46 @@
  */
 #pragma once
 
+#include <optional>
 #include <string>
 
+#include <android-base/unique_fd.h>
 #include <android/hardware/boot/1.0/IBootControl.h>
 
+// Logical partitions are only mapped to a block device as needed, and
+// immediately unmapped when no longer needed. In order to enforce this we
+// require accessing partitions through a Handle abstraction, which may perform
+// additional operations after closing its file descriptor.
+class PartitionHandle {
+  public:
+    PartitionHandle() {}
+    explicit PartitionHandle(const std::string& path) : path_(path) {}
+    PartitionHandle(const std::string& path, std::function<void()>&& closer)
+        : path_(path), closer_(std::move(closer)) {}
+    PartitionHandle(PartitionHandle&& other) = default;
+    PartitionHandle& operator=(PartitionHandle&& other) = default;
+    ~PartitionHandle() {
+        if (closer_) {
+            // Make sure the device is closed first.
+            fd_ = {};
+            closer_();
+        }
+    }
+    const std::string& path() const { return path_; }
+    int fd() const { return fd_.get(); }
+    void set_fd(android::base::unique_fd&& fd) { fd_ = std::move(fd); }
+
+  private:
+    std::string path_;
+    android::base::unique_fd fd_;
+    std::function<void()> closer_;
+};
+
+class FastbootDevice;
+
+std::optional<std::string> FindPhysicalPartition(const std::string& name);
+bool LogicalPartitionExists(const std::string& name, const std::string& slot_suffix,
+                            bool* is_zero_length = nullptr);
+bool OpenPartition(FastbootDevice* device, const std::string& name, PartitionHandle* handle);
+
 bool GetSlotNumber(const std::string& slot, android::hardware::boot::V1_0::Slot* number);
diff --git a/fastboot/device/variables.cpp b/fastboot/device/variables.cpp
index 153ab92..b51b985 100644
--- a/fastboot/device/variables.cpp
+++ b/fastboot/device/variables.cpp
@@ -16,6 +16,8 @@
 
 #include "variables.h"
 
+#include <inttypes.h>
+
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/properties.h>
@@ -24,6 +26,7 @@
 #include <ext4_utils/ext4_utils.h>
 
 #include "fastboot_device.h"
+#include "flashing.h"
 #include "utility.h"
 
 using ::android::hardware::boot::V1_0::BoolResult;
@@ -32,91 +35,116 @@
 constexpr int kMaxDownloadSizeDefault = 0x20000000;
 constexpr char kFastbootProtocolVersion[] = "0.4";
 
-std::string GetVersion(FastbootDevice* /* device */, const std::vector<std::string>& /* args */) {
-    return kFastbootProtocolVersion;
+bool GetVersion(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(kFastbootProtocolVersion);
 }
 
-std::string GetBootloaderVersion(FastbootDevice* /* device */,
-                                 const std::vector<std::string>& /* args */) {
-    return android::base::GetProperty("ro.bootloader", "");
+bool GetBootloaderVersion(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(android::base::GetProperty("ro.bootloader", ""));
 }
 
-std::string GetBasebandVersion(FastbootDevice* /* device */,
-                               const std::vector<std::string>& /* args */) {
-    return android::base::GetProperty("ro.build.expect.baseband", "");
+bool GetBasebandVersion(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(android::base::GetProperty("ro.build.expect.baseband", ""));
 }
 
-std::string GetProduct(FastbootDevice* /* device */, const std::vector<std::string>& /* args */) {
-    return android::base::GetProperty("ro.product.device", "");
+bool GetProduct(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(android::base::GetProperty("ro.product.device", ""));
 }
 
-std::string GetSerial(FastbootDevice* /* device */, const std::vector<std::string>& /* args */) {
-    return android::base::GetProperty("ro.serialno", "");
+bool GetSerial(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(android::base::GetProperty("ro.serialno", ""));
 }
 
-std::string GetSecure(FastbootDevice* /* device */, const std::vector<std::string>& /* args */) {
-    return android::base::GetBoolProperty("ro.secure", "") ? "yes" : "no";
+bool GetSecure(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(android::base::GetBoolProperty("ro.secure", "") ? "yes" : "no");
 }
 
-std::string GetCurrentSlot(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+bool GetCurrentSlot(FastbootDevice* device, const std::vector<std::string>& /* args */) {
     std::string suffix = device->GetCurrentSlot();
-    return suffix.size() == 2 ? suffix.substr(1) : suffix;
+    std::string slot = suffix.size() == 2 ? suffix.substr(1) : suffix;
+    return device->WriteOkay(slot);
 }
 
-std::string GetSlotCount(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+bool GetSlotCount(FastbootDevice* device, const std::vector<std::string>& /* args */) {
     auto boot_control_hal = device->boot_control_hal();
     if (!boot_control_hal) {
         return "0";
     }
-    return std::to_string(boot_control_hal->getNumberSlots());
+    return device->WriteOkay(std::to_string(boot_control_hal->getNumberSlots()));
 }
 
-std::string GetSlotSuccessful(FastbootDevice* device, const std::vector<std::string>& args) {
+bool GetSlotSuccessful(FastbootDevice* device, const std::vector<std::string>& args) {
     if (args.empty()) {
-        return "no";
+        return device->WriteFail("Missing argument");
     }
     Slot slot;
     if (!GetSlotNumber(args[0], &slot)) {
-        return "no";
+        return device->WriteFail("Invalid slot");
     }
     auto boot_control_hal = device->boot_control_hal();
     if (!boot_control_hal) {
-        return "no";
+        return device->WriteFail("Device has no slots");
     }
-    return boot_control_hal->isSlotMarkedSuccessful(slot) == BoolResult::TRUE ? "yes" : "no";
+    if (boot_control_hal->isSlotMarkedSuccessful(slot) != BoolResult::TRUE) {
+        return device->WriteOkay("no");
+    }
+    return device->WriteOkay("yes");
 }
 
-std::string GetSlotUnbootable(FastbootDevice* device, const std::vector<std::string>& args) {
+bool GetSlotUnbootable(FastbootDevice* device, const std::vector<std::string>& args) {
     if (args.empty()) {
-        return "no";
+        return device->WriteFail("Missing argument");
     }
     Slot slot;
     if (!GetSlotNumber(args[0], &slot)) {
-        return "no";
+        return device->WriteFail("Invalid slot");
     }
     auto boot_control_hal = device->boot_control_hal();
     if (!boot_control_hal) {
-        return "no";
+        return device->WriteFail("Device has no slots");
     }
-    return boot_control_hal->isSlotBootable(slot) == BoolResult::TRUE ? "no" : "yes";
+    if (boot_control_hal->isSlotBootable(slot) != BoolResult::TRUE) {
+        return device->WriteOkay("yes");
+    }
+    return device->WriteOkay("no");
 }
 
-std::string GetMaxDownloadSize(FastbootDevice* /* device */,
-                               const std::vector<std::string>& /* args */) {
-    return std::to_string(kMaxDownloadSizeDefault);
+bool GetMaxDownloadSize(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay(std::to_string(kMaxDownloadSizeDefault));
 }
 
-std::string GetUnlocked(FastbootDevice* /* device */, const std::vector<std::string>& /* args */) {
-    return "yes";
+bool GetUnlocked(FastbootDevice* device, const std::vector<std::string>& /* args */) {
+    return device->WriteOkay("yes");
 }
 
-std::string GetHasSlot(FastbootDevice* device, const std::vector<std::string>& args) {
+bool GetHasSlot(FastbootDevice* device, const std::vector<std::string>& args) {
     if (args.empty()) {
-        return "no";
+        return device->WriteFail("Missing argument");
     }
     std::string slot_suffix = device->GetCurrentSlot();
     if (slot_suffix.empty()) {
-        return "no";
+        return device->WriteFail("Invalid slot");
     }
-    return args[0] == "userdata" ? "no" : "yes";
+    std::string result = (args[0] == "userdata" ? "no" : "yes");
+    return device->WriteOkay(result);
+}
+
+bool GetPartitionSize(FastbootDevice* device, const std::vector<std::string>& args) {
+    if (args.size() < 1) {
+        return device->WriteFail("Missing argument");
+    }
+    // Zero-length partitions cannot be created through device-mapper, so we
+    // special case them here.
+    bool is_zero_length;
+    if (LogicalPartitionExists(args[0], device->GetCurrentSlot(), &is_zero_length) &&
+        is_zero_length) {
+        return device->WriteOkay("0");
+    }
+    // Otherwise, open the partition as normal.
+    PartitionHandle handle;
+    if (!OpenPartition(device, args[0], &handle)) {
+        return device->WriteFail("Could not open partition");
+    }
+    uint64_t size = get_block_device_size(handle.fd());
+    return device->WriteOkay(android::base::StringPrintf("%" PRIX64, size));
 }
diff --git a/fastboot/device/variables.h b/fastboot/device/variables.h
index 09ef8ec..88947e0 100644
--- a/fastboot/device/variables.h
+++ b/fastboot/device/variables.h
@@ -21,16 +21,17 @@
 
 class FastbootDevice;
 
-std::string GetVersion(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetBootloaderVersion(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetBasebandVersion(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetProduct(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetSerial(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetSecure(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetCurrentSlot(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetSlotCount(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetSlotSuccessful(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetSlotUnbootable(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetMaxDownloadSize(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetUnlocked(FastbootDevice* device, const std::vector<std::string>& args);
-std::string GetHasSlot(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetVersion(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetBootloaderVersion(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetBasebandVersion(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetProduct(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetSerial(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetSecure(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetCurrentSlot(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetSlotCount(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetSlotSuccessful(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetSlotUnbootable(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetMaxDownloadSize(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetUnlocked(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetHasSlot(FastbootDevice* device, const std::vector<std::string>& args);
+bool GetPartitionSize(FastbootDevice* device, const std::vector<std::string>& args);
diff --git a/init/init_first_stage.cpp b/init/init_first_stage.cpp
index b367f2a..466cde3 100644
--- a/init/init_first_stage.cpp
+++ b/init/init_first_stage.cpp
@@ -138,9 +138,10 @@
     SelinuxSetupKernelLogging();
     SelinuxInitialize();
 
-    // Unneeded?  It's an ext4 file system so shouldn't it have the right domain already?
-    // We're in the kernel domain, so re-exec init to transition to the init domain now
-    // that the SELinux policy has been loaded.
+    // We're in the kernel domain and want to transition to the init domain when we exec second
+    // stage init.  File systems that store SELabels in their xattrs, such as ext4 do not need an
+    // explicit restorecon here, but other file systems do.  In particular, this is needed for
+    // ramdisks such as the recovery image for A/B devices.
     if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
         PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
     }
diff --git a/libbacktrace/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
index a9cfce4..c564271 100644
--- a/libbacktrace/include/backtrace/BacktraceMap.h
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -31,6 +31,7 @@
 
 #include <deque>
 #include <iterator>
+#include <memory>
 #include <string>
 #include <vector>
 
diff --git a/libutils/CallStack.cpp b/libutils/CallStack.cpp
index bd6015e..fe6f33d 100644
--- a/libutils/CallStack.cpp
+++ b/libutils/CallStack.cpp
@@ -16,16 +16,15 @@
 
 #define LOG_TAG "CallStack"
 
-#include <utils/CallStack.h>
-
-#include <memory>
-
 #include <utils/Printer.h>
 #include <utils/Errors.h>
 #include <utils/Log.h>
 
 #include <backtrace/Backtrace.h>
 
+#define CALLSTACK_WEAK  // Don't generate weak definitions.
+#include <utils/CallStack.h>
+
 namespace android {
 
 CallStack::CallStack() {
@@ -76,4 +75,30 @@
     }
 }
 
+// The following four functions may be used via weak symbol references from libutils.
+// Clients assume that if any of these symbols are available, then deleteStack() is.
+
+#ifdef WEAKS_AVAILABLE
+
+CallStack::CallStackUPtr CallStack::getCurrentInternal(int ignoreDepth) {
+    CallStack::CallStackUPtr stack(new CallStack());
+    stack->update(ignoreDepth + 1);
+    return stack;
+}
+
+void CallStack::logStackInternal(const char* logtag, const CallStack* stack,
+                                 android_LogPriority priority) {
+    stack->log(logtag, priority);
+}
+
+String8 CallStack::stackToStringInternal(const char* prefix, const CallStack* stack) {
+    return stack->toString(prefix);
+}
+
+void CallStack::deleteStack(CallStack* stack) {
+    delete stack;
+}
+
+#endif // WEAKS_AVAILABLE
+
 }; // namespace android
diff --git a/libutils/RefBase.cpp b/libutils/RefBase.cpp
index 9074850..3f1e79a 100644
--- a/libutils/RefBase.cpp
+++ b/libutils/RefBase.cpp
@@ -17,30 +17,41 @@
 #define LOG_TAG "RefBase"
 // #define LOG_NDEBUG 0
 
+#include <memory>
+
 #include <utils/RefBase.h>
 
 #include <utils/CallStack.h>
 
+#include <utils/Mutex.h>
+
 #ifndef __unused
 #define __unused __attribute__((__unused__))
 #endif
 
-// compile with refcounting debugging enabled
-#define DEBUG_REFS                      0
+// Compile with refcounting debugging enabled.
+#define DEBUG_REFS 0
+
+// The following three are ignored unless DEBUG_REFS is set.
 
 // whether ref-tracking is enabled by default, if not, trackMe(true, false)
 // needs to be called explicitly
-#define DEBUG_REFS_ENABLED_BY_DEFAULT   0
+#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
 
 // whether callstack are collected (significantly slows things down)
-#define DEBUG_REFS_CALLSTACK_ENABLED    1
+#define DEBUG_REFS_CALLSTACK_ENABLED 1
 
 // folder where stack traces are saved when DEBUG_REFS is enabled
 // this folder needs to exist and be writable
-#define DEBUG_REFS_CALLSTACK_PATH       "/data/debug"
+#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
 
 // log all reference counting operations
-#define PRINT_REFS                      0
+#define PRINT_REFS 0
+
+// Continue after logging a stack trace if ~RefBase discovers that reference
+// count has never been incremented. Normally we conspicuously crash in that
+// case.
+#define DEBUG_REFBASE_DESTRUCTION 1
 
 // ---------------------------------------------------------------------------
 
@@ -184,7 +195,7 @@
                 char inc = refs->ref >= 0 ? '+' : '-';
                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
 #if DEBUG_REFS_CALLSTACK_ENABLED
-                refs->stack.log(LOG_TAG);
+                CallStack::logStack(LOG_TAG, refs->stack.get());
 #endif
                 refs = refs->next;
             }
@@ -198,14 +209,14 @@
                 char inc = refs->ref >= 0 ? '+' : '-';
                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
 #if DEBUG_REFS_CALLSTACK_ENABLED
-                refs->stack.log(LOG_TAG);
+                CallStack::logStack(LOG_TAG, refs->stack.get());
 #endif
                 refs = refs->next;
             }
         }
         if (dumpStack) {
             ALOGE("above errors at:");
-            CallStack stack(LOG_TAG);
+            CallStack::logStack(LOG_TAG);
         }
     }
 
@@ -279,7 +290,7 @@
                      this);
             int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
             if (rc >= 0) {
-                write(rc, text.string(), text.length());
+                (void)write(rc, text.string(), text.length());
                 close(rc);
                 ALOGD("STACK TRACE for %p saved in %s", this, name);
             }
@@ -294,7 +305,7 @@
         ref_entry* next;
         const void* id;
 #if DEBUG_REFS_CALLSTACK_ENABLED
-        CallStack stack;
+        CallStack::CallStackUPtr stack;
 #endif
         int32_t ref;
     };
@@ -311,7 +322,7 @@
             ref->ref = mRef;
             ref->id = id;
 #if DEBUG_REFS_CALLSTACK_ENABLED
-            ref->stack.update(2);
+            ref->stack = CallStack::getCurrent(2);
 #endif
             ref->next = *refs;
             *refs = ref;
@@ -346,7 +357,7 @@
                 ref = ref->next;
             }
 
-            CallStack stack(LOG_TAG);
+            CallStack::logStack(LOG_TAG);
         }
     }
 
@@ -373,7 +384,7 @@
                      inc, refs->id, refs->ref);
             out->append(buf);
 #if DEBUG_REFS_CALLSTACK_ENABLED
-            out->append(refs->stack.toString("\t\t"));
+            out->append(CallStack::stackToString("\t\t", refs->stack.get()));
 #else
             out->append("\t\t(call stacks disabled)");
 #endif
@@ -700,16 +711,16 @@
         if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
             delete mRefs;
         }
-    } else if (mRefs->mStrong.load(std::memory_order_relaxed)
-            == INITIAL_STRONG_VALUE) {
+    } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
         // We never acquired a strong reference on this object.
-        LOG_ALWAYS_FATAL_IF(mRefs->mWeak.load() != 0,
-                "RefBase: Explicit destruction with non-zero weak "
-                "reference count");
-        // TODO: Always report if we get here. Currently MediaMetadataRetriever
-        // C++ objects are inconsistently managed and sometimes get here.
-        // There may be other cases, but we believe they should all be fixed.
-        delete mRefs;
+#if DEBUG_REFBASE_DESTRUCTION
+        // Treating this as fatal is prone to causing boot loops. For debugging, it's
+        // better to treat as non-fatal.
+        ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);
+        CallStack::logStack(LOG_TAG);
+#else
+        LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
+#endif
     }
     // For debugging purposes, clear mRefs.  Ineffective against outstanding wp's.
     const_cast<weakref_impl*&>(mRefs) = nullptr;
diff --git a/libutils/include/utils/CallStack.h b/libutils/include/utils/CallStack.h
index 0c1b875..56004fe 100644
--- a/libutils/include/utils/CallStack.h
+++ b/libutils/include/utils/CallStack.h
@@ -17,6 +17,8 @@
 #ifndef ANDROID_CALLSTACK_H
 #define ANDROID_CALLSTACK_H
 
+#include <memory>
+
 #include <android/log.h>
 #include <backtrace/backtrace_constants.h>
 #include <utils/String8.h>
@@ -25,6 +27,19 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#if !defined(__APPLE__) && !defined(_WIN32)
+# define WEAKS_AVAILABLE 1
+#endif
+#ifndef CALLSTACK_WEAK
+# ifdef WEAKS_AVAILABLE
+#   define CALLSTACK_WEAK __attribute__((weak))
+# else // !WEAKS_AVAILABLE
+#   define CALLSTACK_WEAK
+# endif // !WEAKS_AVAILABLE
+#endif // CALLSTACK_WEAK predefined
+
+#define ALWAYS_INLINE __attribute__((always_inline))
+
 namespace android {
 
 class Printer;
@@ -36,7 +51,7 @@
     CallStack();
     // Create a callstack with the current thread's stack trace.
     // Immediately dump it to logcat using the given logtag.
-    CallStack(const char* logtag, int32_t ignoreDepth=1);
+    CallStack(const char* logtag, int32_t ignoreDepth = 1);
     ~CallStack();
 
     // Reset the stack frames (same as creating an empty call stack).
@@ -44,7 +59,7 @@
 
     // Immediately collect the stack traces for the specified thread.
     // The default is to dump the stack of the current call.
-    void update(int32_t ignoreDepth=1, pid_t tid=BACKTRACE_CURRENT_THREAD);
+    void update(int32_t ignoreDepth = 1, pid_t tid = BACKTRACE_CURRENT_THREAD);
 
     // Dump a stack trace to the log using the supplied logtag.
     void log(const char* logtag,
@@ -63,7 +78,88 @@
     // Get the count of stack frames that are in this call stack.
     size_t size() const { return mFrameLines.size(); }
 
-private:
+    // DO NOT USE ANYTHING BELOW HERE. The following public members are expected
+    // to disappear again shortly, once a better replacement facility exists.
+    // The replacement facility will be incompatible!
+
+    // Debugging accesses to some basic functionality. These use weak symbols to
+    // avoid introducing a dependency on libutilscallstack. Such a dependency from
+    // libutils results in a cyclic build dependency. These routines can be called
+    // from within libutils. But if the actual library is unavailable, they do
+    // nothing.
+    //
+    // DO NOT USE THESE. They will disappear.
+    struct StackDeleter {
+#ifdef WEAKS_AVAILABLE
+        void operator()(CallStack* stack) {
+            deleteStack(stack);
+        }
+#else
+        void operator()(CallStack*) {}
+#endif
+    };
+
+    typedef std::unique_ptr<CallStack, StackDeleter> CallStackUPtr;
+
+    // Return current call stack if possible, nullptr otherwise.
+#ifdef WEAKS_AVAILABLE
+    static CallStackUPtr ALWAYS_INLINE getCurrent(int32_t ignoreDepth = 1) {
+        if (reinterpret_cast<uintptr_t>(getCurrentInternal) == 0) {
+            ALOGW("CallStack::getCurrentInternal not linked, returning null");
+            return CallStackUPtr(nullptr);
+        } else {
+            return getCurrentInternal(ignoreDepth);
+        }
+    }
+#else // !WEAKS_AVAILABLE
+    static CallStackUPtr ALWAYS_INLINE getCurrent(int32_t = 1) {
+        return CallStackUPtr(nullptr);
+    }
+#endif // !WEAKS_AVAILABLE
+
+#ifdef WEAKS_AVAILABLE
+    static void ALWAYS_INLINE logStack(const char* logtag, CallStack* stack = getCurrent().get(),
+                                       android_LogPriority priority = ANDROID_LOG_DEBUG) {
+        if (reinterpret_cast<uintptr_t>(logStackInternal) != 0 && stack != nullptr) {
+            logStackInternal(logtag, stack, priority);
+        } else {
+            ALOGW("CallStack::logStackInternal not linked");
+        }
+    }
+
+#else
+    static void ALWAYS_INLINE logStack(const char*, CallStack* = getCurrent().get(),
+                                       android_LogPriority = ANDROID_LOG_DEBUG) {
+    }
+#endif // !WEAKS_AVAILABLE
+
+#ifdef WEAKS_AVAILABLE
+    static String8 ALWAYS_INLINE stackToString(const char* prefix = nullptr,
+                                               const CallStack* stack = getCurrent().get()) {
+        if (reinterpret_cast<uintptr_t>(stackToStringInternal) != 0 && stack != nullptr) {
+            return stackToStringInternal(prefix, stack);
+        } else {
+            return String8("<CallStack package not linked>");
+        }
+    }
+#else // !WEAKS_AVAILABLE
+    static String8 ALWAYS_INLINE stackToString(const char* = nullptr,
+                                               const CallStack* = getCurrent().get()) {
+        return String8("<CallStack package not linked>");
+    }
+#endif // !WEAKS_AVAILABLE
+
+  private:
+#ifdef WEAKS_AVAILABLE
+    static CallStackUPtr CALLSTACK_WEAK getCurrentInternal(int32_t ignoreDepth);
+    static void CALLSTACK_WEAK logStackInternal(const char* logtag, const CallStack* stack,
+                                                android_LogPriority priority);
+    static String8 CALLSTACK_WEAK stackToStringInternal(const char* prefix, const CallStack* stack);
+    // The deleter is only invoked on non-null pointers. Hence it will never be
+    // invoked if CallStack is not linked.
+    static void CALLSTACK_WEAK deleteStack(CallStack* stack);
+#endif // WEAKS_AVAILABLE
+
     Vector<String8> mFrameLines;
 };