Merge "Tag libstatspull and libstatssocket tests as MTS" into rvc-dev
diff --git a/adb/Android.bp b/adb/Android.bp
index 0af82e1..0394bf6 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -425,6 +425,15 @@
             ],
         }
     },
+
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.adbd",
+    ],
+    visibility: [
+        "//bootable/recovery/minadbd",
+        "//system/core/adb",
+    ],
 }
 
 cc_library {
@@ -492,12 +501,22 @@
             ],
         },
     },
+
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.adbd",
+    ],
+    visibility: [
+        "//system/core/adb",
+    ],
+
 }
 
 cc_library {
     name: "libadbd",
     defaults: ["adbd_defaults", "host_adbd_supported"],
     recovery_available: true,
+    apex_available: ["com.android.adbd"],
 
     // avoid getting duplicate symbol of android::build::getbuildnumber().
     use_version_lib: false,
@@ -550,6 +569,7 @@
     defaults: ["adbd_defaults", "host_adbd_supported", "libadbd_binary_dependencies"],
     stl: "libc++_static",
     recovery_available: true,
+    apex_available: ["com.android.adbd"],
 
     srcs: [
         "daemon/main.cpp",
@@ -656,6 +676,7 @@
         "daemon/shell_service_test.cpp",
         "shell_service_protocol.cpp",
         "shell_service_protocol_test.cpp",
+        "mdns_test.cpp",
     ],
 
     shared_libs: [
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 44e5dac..c3e9731 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -149,7 +149,7 @@
     case A_WRTE: tag = "WRTE"; break;
     case A_AUTH: tag = "AUTH"; break;
     case A_STLS:
-        tag = "ATLS";
+        tag = "STLS";
         break;
     default: tag = "????"; break;
     }
diff --git a/adb/adb_mdns.h b/adb/adb_mdns.h
index 6b37355..3111248 100644
--- a/adb/adb_mdns.h
+++ b/adb/adb_mdns.h
@@ -19,9 +19,14 @@
 
 #include <android-base/macros.h>
 
-const char* kADBServiceType = "_adb._tcp";
-const char* kADBSecurePairingServiceType = "_adb_secure_pairing._tcp";
-const char* kADBSecureConnectServiceType = "_adb_secure_connect._tcp";
+// The rules for Service Names [RFC6335] state that they may be no more
+// than fifteen characters long (not counting the mandatory underscore),
+// consisting of only letters, digits, and hyphens, must begin and end
+// with a letter or digit, must not contain consecutive hyphens, and
+// must contain at least one letter.
+#define ADB_MDNS_SERVICE_TYPE "adb"
+#define ADB_MDNS_TLS_PAIRING_TYPE "adb-tls-pairing"
+#define ADB_MDNS_TLS_CONNECT_TYPE "adb-tls-connect"
 
 const int kADBTransportServiceRefIndex = 0;
 const int kADBSecurePairingServiceRefIndex = 1;
@@ -71,11 +76,10 @@
 const char* kADBSecureConnectServiceTxtRecord =
         ADB_SECURE_SERVICE_VERSION_TXT_RECORD(ADB_SECURE_SERVICE_VERSION);
 
-const char* kADBDNSServices[] = {
-        kADBServiceType,
-        kADBSecurePairingServiceType,
-        kADBSecureConnectServiceType,
-};
+#define ADB_FULL_MDNS_SERVICE_TYPE(atype) ("_" atype "._tcp")
+const char* kADBDNSServices[] = {ADB_FULL_MDNS_SERVICE_TYPE(ADB_MDNS_SERVICE_TYPE),
+                                 ADB_FULL_MDNS_SERVICE_TYPE(ADB_MDNS_TLS_PAIRING_TYPE),
+                                 ADB_FULL_MDNS_SERVICE_TYPE(ADB_MDNS_TLS_CONNECT_TYPE)};
 
 const char* kADBDNSServiceTxtRecords[] = {
         nullptr,
diff --git a/adb/client/auth.cpp b/adb/client/auth.cpp
index 8738ce7..35264c7 100644
--- a/adb/client/auth.cpp
+++ b/adb/client/auth.cpp
@@ -502,6 +502,12 @@
     }).detach();
 }
 
+// Callback given to SSL_set_cert_cb to select a certificate when server requests
+// for a certificate. This is where the server will give us a CA-issuer list, and
+// figure out if the server knows any of our public keys. We currently always return
+// 1 here to indicate success, since we always try a key here (in the case of no auth).
+// See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
+// for more details.
 int adb_tls_set_certificate(SSL* ssl) {
     LOG(INFO) << __func__;
 
diff --git a/adb/client/file_sync_client.cpp b/adb/client/file_sync_client.cpp
index 190c235..e686973 100644
--- a/adb/client/file_sync_client.cpp
+++ b/adb/client/file_sync_client.cpp
@@ -617,7 +617,7 @@
         }
 
         std::string path_and_mode = android::base::StringPrintf("%s,%d", path.c_str(), mode);
-        if (!SendRequest(ID_SEND_V1, path_and_mode.c_str())) {
+        if (!SendRequest(ID_SEND_V1, path_and_mode)) {
             Error("failed to send ID_SEND_V1 message '%s': %s", path_and_mode.c_str(),
                   strerror(errno));
             return false;
diff --git a/adb/libs/adbconnection/Android.bp b/adb/libs/adbconnection/Android.bp
index f6b0a42..ce2ab51 100644
--- a/adb/libs/adbconnection/Android.bp
+++ b/adb/libs/adbconnection/Android.bp
@@ -18,6 +18,11 @@
     use_version_lib: false,
 
     recovery_available: true,
+    apex_available: [
+        "com.android.adbd",
+        // TODO(b/151398197) remove the below
+        "//apex_available:platform",
+    ],
     compile_multilib: "both",
 }
 
diff --git a/adb/mdns_test.cpp b/adb/mdns_test.cpp
new file mode 100644
index 0000000..1f662c1
--- /dev/null
+++ b/adb/mdns_test.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2020 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 <gtest/gtest.h>
+
+#include "adb_mdns.h"
+
+static bool isValidMdnsServiceName(std::string_view name) {
+    // The rules for Service Names [RFC6335] state that they may be no more
+    // than fifteen characters long (not counting the mandatory underscore),
+    // consisting of only letters, digits, and hyphens, must begin and end
+    // with a letter or digit, must not contain consecutive hyphens, and
+    // must contain at least one letter.
+
+    // No more than 15 characters long
+    if (name.empty() || name.size() > 15) {
+        return false;
+    }
+
+    bool hasAtLeastOneLetter = false;
+    bool sawHyphen = false;
+    for (size_t i = 0; i < name.size(); ++i) {
+        // Must contain at least one letter
+        // Only contains letters, digits and hyphens
+        if (name[i] == '-') {
+            // Cannot be at beginning or end
+            if (i == 0 || i == name.size() - 1) {
+                return false;
+            }
+            if (sawHyphen) {
+                // Consecutive hyphen found
+                return false;
+            }
+            sawHyphen = true;
+            continue;
+        }
+
+        sawHyphen = false;
+        if ((name[i] >= 'a' && name[i] <= 'z') || (name[i] >= 'A' && name[i] <= 'Z')) {
+            hasAtLeastOneLetter = true;
+            continue;
+        }
+
+        if (name[i] >= '0' && name[i] <= '9') {
+            continue;
+        }
+
+        // Invalid character
+        return false;
+    }
+
+    return hasAtLeastOneLetter;
+}
+
+TEST(mdns, test_isValidMdnsServiceName) {
+    // Longer than 15 characters
+    EXPECT_FALSE(isValidMdnsServiceName("abcd1234abcd1234"));
+
+    // Contains invalid characters
+    EXPECT_FALSE(isValidMdnsServiceName("a*a"));
+    EXPECT_FALSE(isValidMdnsServiceName("a_a"));
+    EXPECT_FALSE(isValidMdnsServiceName("_a"));
+
+    // Does not begin or end with letter or digit
+    EXPECT_FALSE(isValidMdnsServiceName(""));
+    EXPECT_FALSE(isValidMdnsServiceName("-"));
+    EXPECT_FALSE(isValidMdnsServiceName("-a"));
+    EXPECT_FALSE(isValidMdnsServiceName("-1"));
+    EXPECT_FALSE(isValidMdnsServiceName("a-"));
+    EXPECT_FALSE(isValidMdnsServiceName("1-"));
+
+    // Contains consecutive hyphens
+    EXPECT_FALSE(isValidMdnsServiceName("a--a"));
+
+    // Does not contain at least one letter
+    EXPECT_FALSE(isValidMdnsServiceName("1"));
+    EXPECT_FALSE(isValidMdnsServiceName("12"));
+    EXPECT_FALSE(isValidMdnsServiceName("1-2"));
+
+    // Some valid names
+    EXPECT_TRUE(isValidMdnsServiceName("a"));
+    EXPECT_TRUE(isValidMdnsServiceName("a1"));
+    EXPECT_TRUE(isValidMdnsServiceName("1A"));
+    EXPECT_TRUE(isValidMdnsServiceName("aZ"));
+    EXPECT_TRUE(isValidMdnsServiceName("a-Z"));
+    EXPECT_TRUE(isValidMdnsServiceName("a-b-Z"));
+    EXPECT_TRUE(isValidMdnsServiceName("abc-def-123-456"));
+}
+
+TEST(mdns, ServiceName_RFC6335) {
+    EXPECT_TRUE(isValidMdnsServiceName(ADB_MDNS_SERVICE_TYPE));
+    EXPECT_TRUE(isValidMdnsServiceName(ADB_MDNS_TLS_PAIRING_TYPE));
+    EXPECT_TRUE(isValidMdnsServiceName(ADB_MDNS_TLS_CONNECT_TYPE));
+}
diff --git a/adb/transport.cpp b/adb/transport.cpp
index 61467cb..fe286de 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -506,11 +506,10 @@
 #endif
 
 #if ADB_HOST
-    tls_ = TlsConnection::Create(TlsConnection::Role::Client,
+    tls_ = TlsConnection::Create(TlsConnection::Role::Client, x509_str, evp_str, osh);
 #else
-    tls_ = TlsConnection::Create(TlsConnection::Role::Server,
+    tls_ = TlsConnection::Create(TlsConnection::Role::Server, x509_str, evp_str, osh);
 #endif
-                                 x509_str, evp_str, osh);
     CHECK(tls_);
 #if ADB_HOST
     // TLS 1.3 gives the client no message if the server rejected the
diff --git a/base/Android.bp b/base/Android.bp
index 3702b43..5b91078 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -47,6 +47,10 @@
             enabled: true,
         },
     },
+    apex_available: [
+        "//apex_available:anyapex",
+        "//apex_available:platform",
+    ],
 }
 
 cc_defaults {
diff --git a/base/logging.cpp b/base/logging.cpp
index cd460eb..3c73fea 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -195,7 +195,6 @@
   return logging_lock;
 }
 
-// Only used for Q fallback.
 static LogFunction& Logger() {
 #ifdef __ANDROID__
   static auto& logger = *new LogFunction(LogdLogger());
@@ -205,7 +204,6 @@
   return logger;
 }
 
-// Only used for Q fallback.
 static AbortFunction& Aborter() {
   static auto& aborter = *new AbortFunction(DefaultAborter);
   return aborter;
@@ -416,45 +414,27 @@
 }
 
 void SetLogger(LogFunction&& logger) {
+  Logger() = std::move(logger);
+
   static auto& liblog_functions = GetLibLogFunctions();
   if (liblog_functions) {
-    // We need to atomically swap the old and new pointers since other threads may be logging.
-    // We know all threads will be using the new logger after __android_log_set_logger() returns,
-    // so we can delete it then.
-    // This leaks one std::function<> per instance of libbase if multiple copies of libbase within a
-    // single process call SetLogger().  That is the same cost as having a static
-    // std::function<>, which is the not-thread-safe alternative.
-    static std::atomic<LogFunction*> logger_function(nullptr);
-    auto* old_logger_function = logger_function.exchange(new LogFunction(logger));
     liblog_functions->__android_log_set_logger([](const struct __android_log_message* log_message) {
       auto log_id = log_id_tToLogId(log_message->buffer_id);
       auto severity = PriorityToLogSeverity(log_message->priority);
 
-      auto& function = *logger_function.load(std::memory_order_acquire);
-      function(log_id, severity, log_message->tag, log_message->file, log_message->line,
+      Logger()(log_id, severity, log_message->tag, log_message->file, log_message->line,
                log_message->message);
     });
-    delete old_logger_function;
-  } else {
-    std::lock_guard<std::mutex> lock(LoggingLock());
-    Logger() = std::move(logger);
   }
 }
 
 void SetAborter(AbortFunction&& aborter) {
+  Aborter() = std::move(aborter);
+
   static auto& liblog_functions = GetLibLogFunctions();
   if (liblog_functions) {
-    // See the comment in SetLogger().
-    static std::atomic<AbortFunction*> abort_function(nullptr);
-    auto* old_abort_function = abort_function.exchange(new AbortFunction(aborter));
-    liblog_functions->__android_log_set_aborter([](const char* abort_message) {
-      auto& function = *abort_function.load(std::memory_order_acquire);
-      function(abort_message);
-    });
-    delete old_abort_function;
-  } else {
-    std::lock_guard<std::mutex> lock(LoggingLock());
-    Aborter() = std::move(aborter);
+    liblog_functions->__android_log_set_aborter(
+        [](const char* abort_message) { Aborter()(abort_message); });
   }
 }
 
diff --git a/diagnose_usb/Android.bp b/diagnose_usb/Android.bp
index 6bee28c..93d13bd 100644
--- a/diagnose_usb/Android.bp
+++ b/diagnose_usb/Android.bp
@@ -3,6 +3,11 @@
     cflags: ["-Wall", "-Wextra", "-Werror"],
     host_supported: true,
     recovery_available: true,
+    apex_available: [
+        "com.android.adbd",
+        // TODO(b/151398197) remove the below
+        "//apex_available:platform",
+    ],
     target: {
         windows: {
             enabled: true,
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index d418122..76e3955 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -62,6 +62,7 @@
 #include <fs_mgr_overlayfs.h>
 #include <fscrypt/fscrypt.h>
 #include <libdm/dm.h>
+#include <libdm/loop_control.h>
 #include <liblp/metadata_format.h>
 #include <linux/fs.h>
 #include <linux/loop.h>
@@ -105,6 +106,7 @@
 using android::dm::DeviceMapper;
 using android::dm::DmDeviceState;
 using android::dm::DmTargetLinear;
+using android::dm::LoopControl;
 
 // Realistically, this file should be part of the android::fs_mgr namespace;
 using namespace android::fs_mgr;
@@ -1927,19 +1929,6 @@
     constexpr const char* file_path = "/data/per_boot/zram_swap";
     if (size == 0) return true;
 
-    // Get free loopback
-    unique_fd loop_fd(TEMP_FAILURE_RETRY(open("/dev/loop-control", O_RDWR | O_CLOEXEC)));
-    if (loop_fd.get() == -1) {
-        PERROR << "Cannot open loop-control";
-        return false;
-    }
-
-    int num = ioctl(loop_fd.get(), LOOP_CTL_GET_FREE);
-    if (num == -1) {
-        PERROR << "Cannot get free loop slot";
-        return false;
-    }
-
     // Prepare target path
     unique_fd target_fd(TEMP_FAILURE_RETRY(open(file_path, O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
     if (target_fd.get() == -1) {
@@ -1951,25 +1940,21 @@
         return false;
     }
 
-    // Connect loopback (device_fd) to target path (target_fd)
-    std::string device = android::base::StringPrintf("/dev/block/loop%d", num);
-    unique_fd device_fd(TEMP_FAILURE_RETRY(open(device.c_str(), O_RDWR | O_CLOEXEC)));
-    if (device_fd.get() == -1) {
-        PERROR << "Cannot open /dev/block/loop" << num;
-        return false;
-    }
-
-    if (ioctl(device_fd.get(), LOOP_SET_FD, target_fd.get())) {
-        PERROR << "Cannot set loopback to target path";
+    // Allocate loop device and attach it to file_path.
+    LoopControl loop_control;
+    std::string device;
+    if (!loop_control.Attach(target_fd.get(), 5s, &device)) {
         return false;
     }
 
     // set block size & direct IO
-    if (ioctl(device_fd.get(), LOOP_SET_BLOCK_SIZE, 4096)) {
-        PWARNING << "Cannot set 4KB blocksize to /dev/block/loop" << num;
+    unique_fd device_fd(TEMP_FAILURE_RETRY(open(device.c_str(), O_RDWR | O_CLOEXEC)));
+    if (device_fd.get() == -1) {
+        PERROR << "Cannot open " << device;
+        return false;
     }
-    if (ioctl(device_fd.get(), LOOP_SET_DIRECT_IO, 1)) {
-        PWARNING << "Cannot set direct_io to /dev/block/loop" << num;
+    if (!LoopControl::EnableDirectIo(device_fd.get())) {
+        return false;
     }
 
     return InstallZramDevice(device);
diff --git a/fs_mgr/liblp/builder.cpp b/fs_mgr/liblp/builder.cpp
index d496466..2f516fa 100644
--- a/fs_mgr/liblp/builder.cpp
+++ b/fs_mgr/liblp/builder.cpp
@@ -40,6 +40,20 @@
     return true;
 }
 
+bool LinearExtent::OverlapsWith(const LinearExtent& other) const {
+    if (device_index_ != other.device_index()) {
+        return false;
+    }
+    return physical_sector() < other.end_sector() && other.physical_sector() < end_sector();
+}
+
+bool LinearExtent::OverlapsWith(const Interval& interval) const {
+    if (device_index_ != interval.device_index) {
+        return false;
+    }
+    return physical_sector() < interval.end && interval.start < end_sector();
+}
+
 Interval LinearExtent::AsInterval() const {
     return Interval(device_index(), physical_sector(), end_sector());
 }
@@ -774,8 +788,7 @@
 bool MetadataBuilder::IsAnyRegionCovered(const std::vector<Interval>& regions,
                                          const LinearExtent& candidate) const {
     for (const auto& region : regions) {
-        if (region.device_index == candidate.device_index() &&
-            (candidate.OwnsSector(region.start) || candidate.OwnsSector(region.end))) {
+        if (candidate.OverlapsWith(region)) {
             return true;
         }
     }
@@ -786,11 +799,10 @@
     for (const auto& partition : partitions_) {
         for (const auto& extent : partition->extents()) {
             LinearExtent* linear = extent->AsLinearExtent();
-            if (!linear || linear->device_index() != candidate.device_index()) {
+            if (!linear) {
                 continue;
             }
-            if (linear->OwnsSector(candidate.physical_sector()) ||
-                linear->OwnsSector(candidate.end_sector() - 1)) {
+            if (linear->OverlapsWith(candidate)) {
                 return true;
             }
         }
diff --git a/fs_mgr/liblp/builder_test.cpp b/fs_mgr/liblp/builder_test.cpp
index ca8df61..977ebe3 100644
--- a/fs_mgr/liblp/builder_test.cpp
+++ b/fs_mgr/liblp/builder_test.cpp
@@ -937,3 +937,85 @@
     EXPECT_EQ(exported->header.header_size, sizeof(LpMetadataHeaderV1_2));
     EXPECT_EQ(exported->header.flags, 0x5e5e5e5e);
 }
+
+static Interval ToInterval(const std::unique_ptr<Extent>& extent) {
+    if (LinearExtent* le = extent->AsLinearExtent()) {
+        return le->AsInterval();
+    }
+    return {0, 0, 0};
+}
+
+static void AddPartition(const std::unique_ptr<MetadataBuilder>& builder,
+                         const std::string& partition_name, uint64_t num_sectors,
+                         uint64_t start_sector, std::vector<Interval>* intervals) {
+    Partition* p = builder->AddPartition(partition_name, "group", 0);
+    ASSERT_NE(p, nullptr);
+    ASSERT_TRUE(builder->AddLinearExtent(p, "super", num_sectors, start_sector));
+    ASSERT_EQ(p->extents().size(), 1);
+
+    if (!intervals) {
+        return;
+    }
+
+    auto new_interval = ToInterval(p->extents().back());
+    std::vector<Interval> new_intervals = {new_interval};
+
+    auto overlap = Interval::Intersect(*intervals, new_intervals);
+    ASSERT_TRUE(overlap.empty());
+
+    intervals->push_back(new_interval);
+}
+
+TEST_F(BuilderTest, CollidedExtents) {
+    BlockDeviceInfo super("super", 8_GiB, 786432, 229376, 4096);
+    std::vector<BlockDeviceInfo> block_devices = {super};
+
+    unique_ptr<MetadataBuilder> builder = MetadataBuilder::New(block_devices, "super", 65536, 2);
+    ASSERT_NE(builder, nullptr);
+
+    ASSERT_TRUE(builder->AddGroup("group", 0));
+
+    std::vector<Interval> old_intervals;
+    AddPartition(builder, "system", 10229008, 2048, &old_intervals);
+    AddPartition(builder, "test_a", 648, 12709888, &old_intervals);
+    AddPartition(builder, "test_b", 625184, 12711936, &old_intervals);
+    AddPartition(builder, "test_c", 130912, 13338624, &old_intervals);
+    AddPartition(builder, "test_d", 888, 13469696, &old_intervals);
+    AddPartition(builder, "test_e", 888, 13471744, &old_intervals);
+    AddPartition(builder, "test_f", 888, 13475840, &old_intervals);
+    AddPartition(builder, "test_g", 888, 13477888, &old_intervals);
+
+    // Don't track the first vendor interval, since it will get extended.
+    AddPartition(builder, "vendor", 2477920, 10231808, nullptr);
+
+    std::vector<Interval> new_intervals;
+
+    Partition* p = builder->FindPartition("vendor");
+    ASSERT_NE(p, nullptr);
+    ASSERT_TRUE(builder->ResizePartition(p, 1282031616));
+    ASSERT_GE(p->extents().size(), 1);
+    for (const auto& extent : p->extents()) {
+        new_intervals.push_back(ToInterval(extent));
+    }
+
+    std::vector<Interval> overlap = Interval::Intersect(old_intervals, new_intervals);
+    ASSERT_TRUE(overlap.empty());
+}
+
+TEST_F(BuilderTest, LinearExtentOverlap) {
+    LinearExtent extent(20, 0, 10);
+
+    EXPECT_TRUE(extent.OverlapsWith(LinearExtent{20, 0, 10}));
+    EXPECT_TRUE(extent.OverlapsWith(LinearExtent{50, 0, 10}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{20, 0, 30}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{10, 0, 0}));
+    EXPECT_TRUE(extent.OverlapsWith(LinearExtent{20, 0, 0}));
+    EXPECT_TRUE(extent.OverlapsWith(LinearExtent{40, 0, 0}));
+    EXPECT_TRUE(extent.OverlapsWith(LinearExtent{20, 0, 15}));
+
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{20, 1, 0}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{50, 1, 10}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{40, 1, 0}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{20, 1, 15}));
+    EXPECT_FALSE(extent.OverlapsWith(LinearExtent{20, 1, 10}));
+}
diff --git a/fs_mgr/liblp/device_test.cpp b/fs_mgr/liblp/device_test.cpp
index 382d53d..99bff6e 100644
--- a/fs_mgr/liblp/device_test.cpp
+++ b/fs_mgr/liblp/device_test.cpp
@@ -56,6 +56,10 @@
 
     // Having an alignment offset > alignment doesn't really make sense.
     EXPECT_LT(device_info.alignment_offset, device_info.alignment);
+
+    if (IPropertyFetcher::GetInstance()->GetBoolProperty("ro.virtual_ab.enabled", false)) {
+        EXPECT_EQ(device_info.alignment_offset, 0);
+    }
 }
 
 TEST_F(DeviceTest, ReadSuperPartitionCurrentSlot) {
diff --git a/fs_mgr/liblp/include/liblp/builder.h b/fs_mgr/liblp/include/liblp/builder.h
index f7738fb..bd39150 100644
--- a/fs_mgr/liblp/include/liblp/builder.h
+++ b/fs_mgr/liblp/include/liblp/builder.h
@@ -71,9 +71,8 @@
     uint64_t end_sector() const { return physical_sector_ + num_sectors_; }
     uint32_t device_index() const { return device_index_; }
 
-    bool OwnsSector(uint64_t sector) const {
-        return sector >= physical_sector_ && sector < end_sector();
-    }
+    bool OverlapsWith(const LinearExtent& other) const;
+    bool OverlapsWith(const Interval& interval) const;
 
     Interval AsInterval() const;
 
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index a209ea6..e290cdc 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -26,7 +26,6 @@
         "libbase",
         "libcutils",
         "liblog",
-        "liblp",
     ],
     static_libs: [
         "libdm",
diff --git a/init/mount_namespace.cpp b/init/mount_namespace.cpp
index 0749fe3..f3b584c 100644
--- a/init/mount_namespace.cpp
+++ b/init/mount_namespace.cpp
@@ -240,14 +240,20 @@
     // slave to the /mnt/user mount, and at the same time /mnt/installer in the
     // bootstrap namespace shares a peer group with /mnt/installer in the
     // default namespace.
+    // /mnt/androidwritable is similar to /mnt/installer but serves for
+    // MOUNT_EXTERNAL_ANDROID_WRITABLE apps.
     if (!mkdir_recursive("/mnt/user", 0755)) return false;
     if (!mkdir_recursive("/mnt/installer", 0755)) return false;
+    if (!mkdir_recursive("/mnt/androidwritable", 0755)) return false;
     if (!(BindMount("/mnt/user", "/mnt/installer", true))) return false;
-    // First, make /mnt/installer a slave bind mount
+    if (!(BindMount("/mnt/user", "/mnt/androidwritable", true))) return false;
+    // First, make /mnt/installer and /mnt/androidwritable a slave bind mount
     if (!(MakeSlave("/mnt/installer"))) return false;
+    if (!(MakeSlave("/mnt/androidwritable"))) return false;
     // Then, make it shared again - effectively creating a new peer group, that
     // will be inherited by new mount namespaces.
     if (!(MakeShared("/mnt/installer"))) return false;
+    if (!(MakeShared("/mnt/androidwritable"))) return false;
 
     bootstrap_ns_fd.reset(OpenMountNamespace());
     bootstrap_ns_id = GetMountNamespaceId();
diff --git a/libasyncio/Android.bp b/libasyncio/Android.bp
index 4ab439d..44e7933 100644
--- a/libasyncio/Android.bp
+++ b/libasyncio/Android.bp
@@ -28,6 +28,10 @@
     defaults: ["libasyncio_defaults"],
     vendor_available: true,
     recovery_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.adbd",
+    ],
     host_supported: true,
     srcs: [
         "AsyncIO.cpp",
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index aa18c42..dc989a0 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -44,6 +44,10 @@
     recovery_available: true,
     native_bridge_supported: true,
     export_include_dirs: ["include"],
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
 }
 
 cc_defaults {
@@ -92,6 +96,10 @@
     name: "libbacktrace",
     vendor_available: false,
     recovery_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
     vndk: {
         enabled: true,
         support_system_process: true,
diff --git a/libcrypto_utils/Android.bp b/libcrypto_utils/Android.bp
index e47560f..d7175e0 100644
--- a/libcrypto_utils/Android.bp
+++ b/libcrypto_utils/Android.bp
@@ -38,4 +38,8 @@
             enabled: true,
         },
     },
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.adbd",
+    ],
 }
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index c9eebfe..9ed7927 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -29,6 +29,10 @@
     vendor_available: true,
     recovery_available: true,
     host_supported: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
     native_bridge_supported: true,
     export_include_dirs: ["include"],
     target: {
@@ -134,6 +138,10 @@
     },
     recovery_available: true,
     host_supported: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
     native_bridge_supported: true,
     srcs: [
         "config_utils.cpp",
diff --git a/liblog/Android.bp b/liblog/Android.bp
index 8410370..0b98e1a 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -38,6 +38,10 @@
     vendor_available: true,
     ramdisk_available: true,
     recovery_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
     native_bridge_supported: true,
     export_include_dirs: ["include"],
     system_shared_libs: [],
diff --git a/liblog/logger_write.cpp b/liblog/logger_write.cpp
index 7c78ea1..b1bed80 100644
--- a/liblog/logger_write.cpp
+++ b/liblog/logger_write.cpp
@@ -28,7 +28,6 @@
 #endif
 
 #include <atomic>
-#include <shared_mutex>
 
 #include <android-base/errno_restorer.h>
 #include <android-base/macros.h>
@@ -38,7 +37,6 @@
 #include "android/log.h"
 #include "log/log_read.h"
 #include "logger.h"
-#include "rwlock.h"
 #include "uio.h"
 
 #ifdef __ANDROID__
@@ -142,10 +140,8 @@
   static std::string default_tag = getprogname();
   return default_tag;
 }
-RwLock default_tag_lock;
 
 void __android_log_set_default_tag(const char* tag) {
-  auto lock = std::unique_lock{default_tag_lock};
   GetDefaultTag().assign(tag, 0, LOGGER_ENTRY_MAX_PAYLOAD);
 }
 
@@ -163,10 +159,8 @@
 #else
 static __android_logger_function logger_function = __android_log_stderr_logger;
 #endif
-static RwLock logger_function_lock;
 
 void __android_log_set_logger(__android_logger_function logger) {
-  auto lock = std::unique_lock{logger_function_lock};
   logger_function = logger;
 }
 
@@ -180,15 +174,12 @@
 }
 
 static __android_aborter_function aborter_function = __android_log_default_aborter;
-static RwLock aborter_function_lock;
 
 void __android_log_set_aborter(__android_aborter_function aborter) {
-  auto lock = std::unique_lock{aborter_function_lock};
   aborter_function = aborter;
 }
 
 void __android_log_call_aborter(const char* abort_message) {
-  auto lock = std::shared_lock{aborter_function_lock};
   aborter_function(abort_message);
 }
 
@@ -310,9 +301,7 @@
     return;
   }
 
-  auto tag_lock = std::shared_lock{default_tag_lock, std::defer_lock};
   if (log_message->tag == nullptr) {
-    tag_lock.lock();
     log_message->tag = GetDefaultTag().c_str();
   }
 
@@ -322,7 +311,6 @@
   }
 #endif
 
-  auto lock = std::shared_lock{logger_function_lock};
   logger_function(log_message);
 }
 
@@ -330,7 +318,7 @@
   ErrnoRestorer errno_restorer;
 
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
-    return 0;
+    return -EPERM;
   }
 
   __android_log_message log_message = {
@@ -343,7 +331,7 @@
   ErrnoRestorer errno_restorer;
 
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
-    return 0;
+    return -EPERM;
   }
 
   char buf[LOG_BUF_SIZE];
@@ -360,7 +348,7 @@
   ErrnoRestorer errno_restorer;
 
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
-    return 0;
+    return -EPERM;
   }
 
   va_list ap;
@@ -380,7 +368,7 @@
   ErrnoRestorer errno_restorer;
 
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
-    return 0;
+    return -EPERM;
   }
 
   va_list ap;
diff --git a/liblog/logger_write.h b/liblog/logger_write.h
index 065fd55..eee2778 100644
--- a/liblog/logger_write.h
+++ b/liblog/logger_write.h
@@ -18,7 +18,4 @@
 
 #include <string>
 
-#include "rwlock.h"
-
-std::string& GetDefaultTag();  // Must read lock default_tag_lock
-extern RwLock default_tag_lock;
\ No newline at end of file
+std::string& GetDefaultTag();
diff --git a/liblog/properties.cpp b/liblog/properties.cpp
index abd48fc..37670ec 100644
--- a/liblog/properties.cpp
+++ b/liblog/properties.cpp
@@ -23,7 +23,6 @@
 #include <unistd.h>
 
 #include <algorithm>
-#include <shared_mutex>
 
 #include <private/android_logger.h>
 
@@ -99,9 +98,7 @@
   static const char log_namespace[] = "persist.log.tag.";
   static const size_t base_offset = 8; /* skip "persist." */
 
-  auto tag_lock = std::shared_lock{default_tag_lock, std::defer_lock};
   if (tag == nullptr || len == 0) {
-    tag_lock.lock();
     auto& tag_string = GetDefaultTag();
     tag = tag_string.c_str();
     len = tag_string.size();
diff --git a/libprocessgroup/Android.bp b/libprocessgroup/Android.bp
index 618a5c5..2c1b255 100644
--- a/libprocessgroup/Android.bp
+++ b/libprocessgroup/Android.bp
@@ -13,6 +13,10 @@
             enabled: true,
         },
     },
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
 }
 
 cc_library {
@@ -52,4 +56,8 @@
         "-Werror",
         "-Wexit-time-destructors",
     ],
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
 }
diff --git a/libstats/push_compat/Android.bp b/libstats/push_compat/Android.bp
index f0fcff6..2f7212f 100644
--- a/libstats/push_compat/Android.bp
+++ b/libstats/push_compat/Android.bp
@@ -49,6 +49,7 @@
         "libstatssocket_headers",
     ],
     static_libs: ["libgtest_prod"],
+    apex_available: ["com.android.resolv"],
 }
 
 cc_test {
diff --git a/libstats/socket/Android.bp b/libstats/socket/Android.bp
index a316432..3f42088 100644
--- a/libstats/socket/Android.bp
+++ b/libstats/socket/Android.bp
@@ -85,6 +85,7 @@
     name: "libstatssocket_headers",
     export_include_dirs: ["include"],
     host_supported: true,
+    apex_available: ["com.android.resolv"],
 }
 
 cc_benchmark {
diff --git a/libsystem/Android.bp b/libsystem/Android.bp
index b265b61..ff886fd 100644
--- a/libsystem/Android.bp
+++ b/libsystem/Android.bp
@@ -4,6 +4,10 @@
     recovery_available: true,
     host_supported: true,
     native_bridge_supported: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
     export_include_dirs: ["include"],
 
     target: {
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 3311793..7405c96 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -18,6 +18,10 @@
     recovery_available: true,
     host_supported: true,
     native_bridge_supported: true,
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
 
     header_libs: [
         "liblog_headers",
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 76a970f..b8c143d 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -122,6 +122,18 @@
     return fd;
 }
 
+static void closeLogFile(const char* pathname) {
+    int fd = open(pathname, O_WRONLY | O_CLOEXEC);
+    if (fd == -1) {
+        return;
+    }
+
+    // no need to check errors
+    __u32 set = 0;
+    ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
+    close(fd);
+}
+
 void Logcat::RotateLogs() {
     // Can't rotate logs if we're not outputting to a file
     if (!output_file_name_) return;
@@ -152,6 +164,8 @@
             break;
         }
 
+        closeLogFile(file0.c_str());
+
         int err = rename(file0.c_str(), file1.c_str());
 
         if (err < 0 && errno != ENOENT) {
diff --git a/qemu_pipe/Android.bp b/qemu_pipe/Android.bp
index c6bda4a..ad86a4e 100644
--- a/qemu_pipe/Android.bp
+++ b/qemu_pipe/Android.bp
@@ -4,6 +4,11 @@
     name: "libqemu_pipe",
     vendor_available: true,
     recovery_available: true,
+    apex_available: [
+        "com.android.adbd",
+        // TODO(b/151398197) remove the below
+        "//apex_available:platform",
+    ],
     sanitize: {
         misc_undefined: ["integer"],
     },
diff --git a/rootdir/init.rc b/rootdir/init.rc
index c571c26..8a66b0a 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -743,7 +743,7 @@
     mkdir /data/misc/train-info/ 0770 statsd system
 
     # Wait for apexd to finish activating APEXes before starting more processes.
-    wait_for_prop apexd.status ready
+    wait_for_prop apexd.status activated
     perform_apex_config
 
     # Special-case /data/media/obb per b/64566063
@@ -758,7 +758,7 @@
     # Allow apexd to snapshot and restore device encrypted apex data in the case
     # of a rollback. This should be done immediately after DE_user data keys
     # are loaded. APEXes should not access this data until this has been
-    # completed.
+    # completed and apexd.status becomes "ready".
     exec_start apexd-snapshotde
 
     # Set SELinux security contexts on upgrade or policy update.