Merge "Convert vts configs to Android.bp" into rvc-dev
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/base/include/android-base/expected.h b/base/include/android-base/expected.h
index 9603bb1..9470344 100644
--- a/base/include/android-base/expected.h
+++ b/base/include/android-base/expected.h
@@ -182,7 +182,7 @@
                 !std::is_same_v<unexpected<E>, std::remove_cv_t<std::remove_reference_t<U>>> &&
                 std::is_convertible_v<U&&, T> /* non-explicit */
                 )>
-  // NOLINTNEXTLINE(google-explicit-constructor)
+  // NOLINTNEXTLINE(google-explicit-constructor,bugprone-forwarding-reference-overload)
   constexpr expected(U&& v) : var_(std::in_place_index<0>, std::forward<U>(v)) {}
 
   template <class U = T _ENABLE_IF(
@@ -192,6 +192,7 @@
                 !std::is_same_v<unexpected<E>, std::remove_cv_t<std::remove_reference_t<U>>> &&
                 !std::is_convertible_v<U&&, T> /* explicit */
                 )>
+  // NOLINTNEXTLINE(bugprone-forwarding-reference-overload)
   constexpr explicit expected(U&& v) : var_(std::in_place_index<0>, T(std::forward<U>(v))) {}
 
   template<class G = E _ENABLE_IF(
@@ -387,13 +388,9 @@
 
 template<class T1, class E1, class T2, class E2>
 constexpr bool operator==(const expected<T1, E1>& x, const expected<T2, E2>& y) {
-  if (x.has_value() != y.has_value()) {
-    return false;
-  } else if (!x.has_value()) {
-    return x.error() == y.error();
-  } else {
-    return *x == *y;
-  }
+  if (x.has_value() != y.has_value()) return false;
+  if (!x.has_value()) return x.error() == y.error();
+  return *x == *y;
 }
 
 template<class T1, class E1, class T2, class E2>
@@ -581,35 +578,23 @@
 
 template<class E1, class E2>
 constexpr bool operator==(const expected<void, E1>& x, const expected<void, E2>& y) {
-  if (x.has_value() != y.has_value()) {
-    return false;
-  } else if (!x.has_value()) {
-    return x.error() == y.error();
-  } else {
-    return true;
-  }
+  if (x.has_value() != y.has_value()) return false;
+  if (!x.has_value()) return x.error() == y.error();
+  return true;
 }
 
 template<class T1, class E1, class E2>
 constexpr bool operator==(const expected<T1, E1>& x, const expected<void, E2>& y) {
-  if (x.has_value() != y.has_value()) {
-    return false;
-  } else if (!x.has_value()) {
-    return x.error() == y.error();
-  } else {
-    return false;
-  }
+  if (x.has_value() != y.has_value()) return false;
+  if (!x.has_value()) return x.error() == y.error();
+  return false;
 }
 
 template<class E1, class T2, class E2>
 constexpr bool operator==(const expected<void, E1>& x, const expected<T2, E2>& y) {
-  if (x.has_value() != y.has_value()) {
-    return false;
-  } else if (!x.has_value()) {
-    return x.error() == y.error();
-  } else {
-    return false;
-  }
+  if (x.has_value() != y.has_value()) return false;
+  if (!x.has_value()) return x.error() == y.error();
+  return false;
 }
 
 template<class E>
@@ -623,7 +608,7 @@
                 std::is_constructible_v<E, Err> &&
                 !std::is_same_v<std::remove_cv_t<std::remove_reference_t<E>>, std::in_place_t> &&
                 !std::is_same_v<std::remove_cv_t<std::remove_reference_t<E>>, unexpected>)>
-  // NOLINTNEXTLINE(google-explicit-constructor)
+  // NOLINTNEXTLINE(google-explicit-constructor,bugprone-forwarding-reference-overload)
   constexpr unexpected(Err&& e) : val_(std::forward<Err>(e)) {}
 
   template<class U, class... Args _ENABLE_IF(
diff --git a/base/include/android-base/result.h b/base/include/android-base/result.h
index 5e65876..56a4f3e 100644
--- a/base/include/android-base/result.h
+++ b/base/include/android-base/result.h
@@ -130,6 +130,7 @@
 
   template <typename T>
   Error& operator<<(T&& t) {
+    // NOLINTNEXTLINE(bugprone-suspicious-semicolon)
     if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) {
       errno_ = t.code();
       return (*this) << t.message();
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/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/liblog/logger_write.cpp b/liblog/logger_write.cpp
index 74b0ab9..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);
 }
 
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/libstats/pull/Android.bp b/libstats/pull/Android.bp
index ef1c5c5..2658639 100644
--- a/libstats/pull/Android.bp
+++ b/libstats/pull/Android.bp
@@ -84,7 +84,15 @@
         "libstatspull",
         "libstatssocket",
     ],
-    test_suites: ["general-tests"],
+    test_suites: ["general-tests", "mts"],
+    //TODO(b/153588990): Remove when the build system properly separates 
+    //32bit and 64bit architectures.
+    compile_multilib: "both",
+    multilib: {
+        lib64: {
+            suffix: "64",
+        }
+    },
     cflags: [
         "-Wall",
         "-Werror",
@@ -93,4 +101,5 @@
         "-Wno-unused-function",
         "-Wno-unused-parameter",
     ],
+    require_root: true,
 }
diff --git a/libstats/socket/Android.bp b/libstats/socket/Android.bp
index 8c12fe0..f386243 100644
--- a/libstats/socket/Android.bp
+++ b/libstats/socket/Android.bp
@@ -122,5 +122,14 @@
         "libcutils",
         "libutils",
     ],
-    test_suites: ["device-tests"],
+    test_suites: ["device-tests", "mts"],
+    //TODO(b/153588990): Remove when the build system properly separates 
+    //32bit and 64bit architectures.
+    compile_multilib: "both",
+    multilib: {
+        lib64: {
+            suffix: "64",
+        }
+    },
+    require_root: true,
 }
diff --git a/libstats/socket/tests/stats_event_test.cpp b/libstats/socket/tests/stats_event_test.cpp
index 6e47e3d..80ef145 100644
--- a/libstats/socket/tests/stats_event_test.cpp
+++ b/libstats/socket/tests/stats_event_test.cpp
@@ -53,7 +53,12 @@
 // Side-effect: this function moves the start of the buffer past the read value
 template <class T>
 T readNext(uint8_t** buffer) {
-    T value = *(T*)(*buffer);
+    T value;
+    if ((reinterpret_cast<uintptr_t>(*buffer) % alignof(T)) == 0) {
+        value = *(T*)(*buffer);
+    } else {
+        memcpy(&value, *buffer, sizeof(T));
+    }
     *buffer += sizeof(T);
     return value;
 }
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/rootdir/init.rc b/rootdir/init.rc
index 8a66b0a..e80756e 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -544,8 +544,8 @@
     enter_default_mount_ns
 
     # /data/apex is now available. Start apexd to scan and activate APEXes.
-    mkdir /data/apex 0750 root system encryption=None
-    mkdir /data/apex/active 0750 root system
+    mkdir /data/apex 0755 root system encryption=None
+    mkdir /data/apex/active 0755 root system
     mkdir /data/apex/backup 0700 root system
     mkdir /data/apex/hashtree 0700 root system
     mkdir /data/apex/sessions 0700 root system
diff --git a/toolbox/start.cpp b/toolbox/start.cpp
index 4b1a54d..cffb89c 100644
--- a/toolbox/start.cpp
+++ b/toolbox/start.cpp
@@ -36,7 +36,13 @@
 }
 
 static void ControlDefaultServices(bool start) {
-    std::vector<std::string> services = {"iorapd", "netd", "surfaceflinger", "zygote"};
+    std::vector<std::string> services = {
+        "iorapd",
+        "netd",
+        "surfaceflinger",
+        "audioserver",
+        "zygote",
+    };
 
     // Only start zygote_secondary if not single arch.
     std::string zygote_configuration = GetProperty("ro.zygote", "");