Merge "[Metrics] Add helper data structures to parse metrics messages" into main
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index 439218d..235fdfd 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -371,6 +371,11 @@
         },
     },
 
+    sanitize: {
+        memtag_heap: true,
+        memtag_stack: true,
+    },
+
     shared_libs: [
         "libbase",
         "libcutils",
diff --git a/debuggerd/TEST_MAPPING b/debuggerd/TEST_MAPPING
index 8633cb8..61d7155 100644
--- a/debuggerd/TEST_MAPPING
+++ b/debuggerd/TEST_MAPPING
@@ -14,5 +14,10 @@
     {
       "name": "debuggerd_test"
     }
+  ],
+  "postsubmit": [
+    {
+      "name": "CtsCrashDetailHostTestCases"
+    }
   ]
 }
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index f396b1d..3135d9e 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -21,6 +21,7 @@
 #include <linux/prctl.h>
 #include <malloc.h>
 #include <pthread.h>
+#include <setjmp.h>
 #include <stdlib.h>
 #include <sys/capability.h>
 #include <sys/mman.h>
@@ -601,6 +602,55 @@
 #endif
 }
 
+__attribute__((noinline)) void mte_illegal_setjmp_helper(jmp_buf& jump_buf) {
+  // Because the detection of illegal setjmp is done relative to the SP in setjmp,
+  // we need to make sure this stack frame is bigger than the one of setjmp.
+  // TODO(fmayer): fix that bug and remove the workaround.
+  volatile char buf[1024];
+  buf[0] = '1';
+  setjmp(jump_buf);
+}
+
+TEST_F(CrasherTest, mte_illegal_setjmp) {
+  // This setjmp is illegal because it jumps back into a function that already returned.
+  // Quoting man 3 setjmp:
+  //     If the function which called setjmp() returns before longjmp() is
+  //     called, the behavior is undefined.  Some kind of subtle or
+  //     unsubtle chaos is sure to result.
+  // https://man7.org/linux/man-pages/man3/longjmp.3.html
+#if defined(__aarch64__)
+  if (!mte_supported()) {
+    GTEST_SKIP() << "Requires MTE";
+  }
+
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([&]() {
+    SetTagCheckingLevelSync();
+    jmp_buf jump_buf;
+    mte_illegal_setjmp_helper(jump_buf);
+    longjmp(jump_buf, 1);
+  });
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+
+  // In our test-case, we have a NEGATIVE stack adjustment, which is being
+  // interpreted as unsigned integer, and thus is "too large".
+  // TODO(fmayer): fix the error message for this
+  ASSERT_MATCH(result, R"(memtag_handle_longjmp: stack adjustment too large)");
+#else
+  GTEST_SKIP() << "Requires aarch64";
+#endif
+}
+
 TEST_F(CrasherTest, mte_async) {
 #if defined(__aarch64__)
   if (!mte_supported()) {
@@ -2647,7 +2697,7 @@
   match_str += format_full_pointer(crash_uptr);
   ASSERT_MATCH(result, match_str);
 
-  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
+  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->\)\n)");
 
   // Verifies that the fault address error message is at the end of the
   // maps section. To do this, the check below looks for the start of the
@@ -2699,7 +2749,7 @@
   match_str += format_full_pointer(reinterpret_cast<uintptr_t>(middle_ptr));
   ASSERT_MATCH(result, match_str);
 
-  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
+  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->\)\n)");
 
   match_str = android::base::StringPrintf(
       R"(    %s.*\n--->Fault address falls at %s between mapped regions\n    %s)",
@@ -2737,7 +2787,7 @@
   match_str += format_full_pointer(reinterpret_cast<uintptr_t>(ptr));
   ASSERT_MATCH(result, match_str);
 
-  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
+  ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->\)\n)");
 
   match_str = android::base::StringPrintf(R"(\n--->%s.*\n)", format_pointer(ptr).c_str());
   ASSERT_MATCH(result, match_str);
diff --git a/fs_mgr/libdm/dm_target.cpp b/fs_mgr/libdm/dm_target.cpp
index 90d91a0..1f6bd1a 100644
--- a/fs_mgr/libdm/dm_target.cpp
+++ b/fs_mgr/libdm/dm_target.cpp
@@ -61,6 +61,10 @@
     return block_device_ + " " + std::to_string(physical_sector_);
 }
 
+std::string DmTargetStripe::GetParameterString() const {
+    return "2 " + std::to_string(chunksize) + " " + block_device0_ + " 0 " + block_device1_ + " 0";
+}
+
 DmTargetVerity::DmTargetVerity(uint64_t start, uint64_t length, uint32_t version,
                                const std::string& block_device, const std::string& hash_device,
                                uint32_t data_block_size, uint32_t hash_block_size,
diff --git a/fs_mgr/libdm/dm_test.cpp b/fs_mgr/libdm/dm_test.cpp
index a0129c2..d043be6 100644
--- a/fs_mgr/libdm/dm_test.cpp
+++ b/fs_mgr/libdm/dm_test.cpp
@@ -181,6 +181,13 @@
     ASSERT_EQ(dm.GetState(dev.name()), DmDeviceState::ACTIVE);
 }
 
+TEST_F(DmTest, StripeArgs) {
+    DmTargetStripe target(0, 4096, 1024, "/dev/loop0", "/dev/loop1");
+    ASSERT_EQ(target.name(), "striped");
+    ASSERT_TRUE(target.Valid());
+    ASSERT_EQ(target.GetParameterString(), "2 1024 /dev/loop0 0 /dev/loop1 0");
+}
+
 TEST_F(DmTest, DmVerityArgsAvb2) {
     std::string device = "/dev/block/platform/soc/1da4000.ufshc/by-name/vendor_a";
     std::string algorithm = "sha1";
diff --git a/fs_mgr/libdm/include/libdm/dm_target.h b/fs_mgr/libdm/include/libdm/dm_target.h
index 09fe200..97f3c13 100644
--- a/fs_mgr/libdm/include/libdm/dm_target.h
+++ b/fs_mgr/libdm/include/libdm/dm_target.h
@@ -116,6 +116,24 @@
     uint64_t physical_sector_;
 };
 
+class DmTargetStripe final : public DmTarget {
+  public:
+    DmTargetStripe(uint64_t start, uint64_t length, uint64_t chunksize,
+                   const std::string& block_device0, const std::string& block_device1)
+        : DmTarget(start, length),
+          chunksize(chunksize),
+          block_device0_(block_device0),
+          block_device1_(block_device1) {}
+
+    std::string name() const override { return "striped"; }
+    std::string GetParameterString() const override;
+
+  private:
+    uint64_t chunksize;
+    std::string block_device0_;
+    std::string block_device1_;
+};
+
 class DmTargetVerity final : public DmTarget {
   public:
     DmTargetVerity(uint64_t start, uint64_t length, uint32_t version,
diff --git a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
index cf26a16..a4a2c1a 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
+++ b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
@@ -39,6 +39,7 @@
 namespace android {
 namespace snapshot {
 
+// @VsrTest = 3.7.6
 class PartitionCowCreatorTest : public ::testing::Test {
   public:
     void SetUp() override {
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index e538d50..47e6ce9 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -104,6 +104,7 @@
 
 void MountMetadata();
 
+// @VsrTest = 3.7.6
 class SnapshotTest : public ::testing::Test {
   public:
     SnapshotTest() : dm_(DeviceMapper::Instance()) {}
diff --git a/fs_mgr/libsnapshot/snapshotctl.cpp b/fs_mgr/libsnapshot/snapshotctl.cpp
index 0396a55..50e9f48 100644
--- a/fs_mgr/libsnapshot/snapshotctl.cpp
+++ b/fs_mgr/libsnapshot/snapshotctl.cpp
@@ -15,6 +15,7 @@
 //
 
 #include <sysexits.h>
+#include <unistd.h>
 
 #include <chrono>
 #include <filesystem>
@@ -46,9 +47,7 @@
 
 #include "partition_cow_creator.h"
 
-#ifdef SNAPSHOTCTL_USERDEBUG_OR_ENG
 #include <BootControlClient.h>
-#endif
 
 using namespace std::chrono_literals;
 using namespace std::string_literals;
@@ -79,7 +78,11 @@
                  "  revert-snapshots\n"
                  "    Prepares devices to boot without snapshots on next boot.\n"
                  "    This does not delete the snapshot. It only removes the indicators\n"
-                 "    so that first stage init will not mount from snapshots.\n";
+                 "    so that first stage init will not mount from snapshots.\n"
+                 "  apply-update\n"
+                 "    Apply the incremental OTA update wherein the snapshots are\n"
+                 "    directly written to COW block device. This will bypass update-engine\n"
+                 "    and the device will be ready to boot from the target build.\n";
     return EX_USAGE;
 }
 
@@ -96,14 +99,22 @@
     bool DeleteSnapshots();
     bool CleanupSnapshot() { return sm_->PrepareDeviceToBootWithoutSnapshot(); }
     bool BeginUpdate();
+    bool ApplyUpdate();
 
   private:
     std::optional<std::string> GetCowImagePath(std::string& name);
+    bool PrepareUpdate();
     bool WriteSnapshotPatch(std::string cow_device, std::string patch);
+    std::string GetGroupName(const android::fs_mgr::LpMetadata& pt,
+                             const std::string& partiton_name);
     std::unique_ptr<SnapshotManager::LockedFile> lock_;
     std::unique_ptr<SnapshotManager> sm_;
     std::vector<std::future<bool>> threads_;
     std::string snapshot_dir_path_;
+    std::unordered_map<std::string, chromeos_update_engine::DynamicPartitionGroup*> group_map_;
+
+    std::vector<std::string> patchfiles_;
+    chromeos_update_engine::DeltaArchiveManifest manifest_;
 };
 
 MapSnapshots::MapSnapshots(std::string path) {
@@ -115,6 +126,178 @@
     snapshot_dir_path_ = path + "/";
 }
 
+std::string MapSnapshots::GetGroupName(const android::fs_mgr::LpMetadata& pt,
+                                       const std::string& partition_name) {
+    std::string group_name;
+    for (const auto& partition : pt.partitions) {
+        std::string name = android::fs_mgr::GetPartitionName(partition);
+        auto suffix = android::fs_mgr::GetPartitionSlotSuffix(name);
+        std::string pname = name.substr(0, name.size() - suffix.size());
+        if (pname == partition_name) {
+            std::string group_name =
+                    android::fs_mgr::GetPartitionGroupName(pt.groups[partition.group_index]);
+            return group_name.substr(0, group_name.size() - suffix.size());
+        }
+    }
+    return "";
+}
+
+bool MapSnapshots::PrepareUpdate() {
+    auto source_slot = fs_mgr_get_slot_suffix();
+    auto source_slot_number = SlotNumberForSlotSuffix(source_slot);
+    auto super_source = fs_mgr_get_super_partition_name(source_slot_number);
+
+    // Get current partition information.
+    PartitionOpener opener;
+    auto source_metadata = ReadMetadata(opener, super_source, source_slot_number);
+    if (!source_metadata) {
+        LOG(ERROR) << "Could not read source partition metadata.\n";
+        return false;
+    }
+
+    auto dap = manifest_.mutable_dynamic_partition_metadata();
+    dap->set_snapshot_enabled(true);
+    dap->set_vabc_enabled(true);
+    dap->set_vabc_compression_param("lz4");
+    dap->set_cow_version(3);
+
+    for (const auto& entry : std::filesystem::directory_iterator(snapshot_dir_path_)) {
+        if (android::base::EndsWith(entry.path().generic_string(), ".patch")) {
+            patchfiles_.push_back(android::base::Basename(entry.path().generic_string()));
+        }
+    }
+
+    for (auto& patchfile : patchfiles_) {
+        std::string parsing_file = snapshot_dir_path_ + patchfile;
+        android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(parsing_file.c_str(), O_RDONLY)));
+        if (fd < 0) {
+            LOG(ERROR) << "Failed to open file: " << parsing_file;
+            return false;
+        }
+        uint64_t dev_sz = lseek(fd.get(), 0, SEEK_END);
+        if (!dev_sz) {
+            LOG(ERROR) << "Could not determine block device size: " << parsing_file;
+            return false;
+        }
+
+        const int block_sz = 4_KiB;
+        dev_sz += block_sz - 1;
+        dev_sz &= ~(block_sz - 1);
+
+        auto npos = patchfile.rfind(".patch");
+        auto partition_name = patchfile.substr(0, npos);
+
+        chromeos_update_engine::DynamicPartitionGroup* group = nullptr;
+        std::string group_name = GetGroupName(*source_metadata.get(), partition_name);
+        if (group_map_.find(group_name) != group_map_.end()) {
+            group = group_map_[group_name];
+        } else {
+            group = dap->add_groups();
+            group->set_name(group_name);
+            group_map_[group_name] = group;
+        }
+        group->add_partition_names(partition_name);
+
+        auto pu = manifest_.mutable_partitions()->Add();
+        pu->set_partition_name(partition_name);
+        pu->set_estimate_cow_size(dev_sz);
+
+        CowReader reader;
+        if (!reader.Parse(fd)) {
+            LOG(ERROR) << "COW reader parse failed";
+            return false;
+        }
+
+        uint64_t new_device_size = 0;
+        const auto& header = reader.GetHeader();
+        if (header.prefix.major_version == 2) {
+            size_t num_ops = reader.get_num_total_data_ops();
+            new_device_size = (num_ops * header.block_size);
+        } else {
+            const auto& v3_header = reader.header_v3();
+            new_device_size = v3_header.op_count_max * v3_header.block_size;
+        }
+
+        LOG(INFO) << "Partition: " << partition_name << " Group_name: " << group_name
+                  << " size: " << new_device_size << " COW-size: " << dev_sz;
+        pu->mutable_new_partition_info()->set_size(new_device_size);
+    }
+    return true;
+}
+
+bool MapSnapshots::ApplyUpdate() {
+    if (!PrepareUpdate()) {
+        LOG(ERROR) << "PrepareUpdate failed";
+        return false;
+    }
+    if (!sm_->BeginUpdate()) {
+        LOG(ERROR) << "BeginUpdate failed";
+        return false;
+    }
+    if (!sm_->CreateUpdateSnapshots(manifest_)) {
+        LOG(ERROR) << "Could not apply snapshots";
+        return false;
+    }
+
+    LOG(INFO) << "CreateUpdateSnapshots success";
+    if (!sm_->MapAllSnapshots(10s)) {
+        LOG(ERROR) << "MapAllSnapshots failed";
+        return false;
+    }
+
+    LOG(INFO) << "MapAllSnapshots success";
+
+    auto& dm = android::dm::DeviceMapper::Instance();
+    auto target_slot = fs_mgr_get_other_slot_suffix();
+    for (auto& patchfile : patchfiles_) {
+        auto npos = patchfile.rfind(".patch");
+        auto partition_name = patchfile.substr(0, npos) + target_slot;
+        auto cow_device = partition_name + "-cow";
+        std::string cow_path;
+        if (!dm.GetDmDevicePathByName(cow_device, &cow_path)) {
+            LOG(ERROR) << "Failed to cow path";
+            return false;
+        }
+        threads_.emplace_back(std::async(std::launch::async, &MapSnapshots::WriteSnapshotPatch,
+                                         this, cow_path, patchfile));
+    }
+
+    bool ret = true;
+    for (auto& t : threads_) {
+        ret = t.get() && ret;
+    }
+    if (!ret) {
+        LOG(ERROR) << "Snapshot writes failed";
+        return false;
+    }
+    if (!sm_->UnmapAllSnapshots()) {
+        LOG(ERROR) << "UnmapAllSnapshots failed";
+        return false;
+    }
+
+    LOG(INFO) << "Pre-created snapshots successfully copied";
+    // All snapshots have been written.
+    if (!sm_->FinishedSnapshotWrites(false /* wipe */)) {
+        LOG(ERROR) << "Could not finalize snapshot writes.\n";
+        return false;
+    }
+
+    auto hal = hal::BootControlClient::WaitForService();
+    if (!hal) {
+        LOG(ERROR) << "Could not find IBootControl HAL.\n";
+        return false;
+    }
+    auto target_slot_number = SlotNumberForSlotSuffix(target_slot);
+    auto cr = hal->SetActiveBootSlot(target_slot_number);
+    if (!cr.IsOk()) {
+        LOG(ERROR) << "Could not set active boot slot: " << cr.errMsg;
+        return false;
+    }
+
+    LOG(INFO) << "ApplyUpdate success";
+    return true;
+}
+
 bool MapSnapshots::BeginUpdate() {
     lock_ = sm_->LockExclusive();
     std::vector<std::string> snapshots;
@@ -227,11 +410,10 @@
         if (file_offset >= dev_sz) {
             break;
         }
-
-        if (fsync(cfd.get()) < 0) {
-            PLOG(ERROR) << "Fsync failed at offset: " << file_offset << " size: " << to_read;
-            return false;
-        }
+    }
+    if (fsync(cfd.get()) < 0) {
+        PLOG(ERROR) << "Fsync failed";
+        return false;
     }
     return true;
 }
@@ -367,6 +549,30 @@
     return snapshot.DeleteSnapshots();
 }
 
+bool ApplyUpdate(int argc, char** argv) {
+    android::base::InitLogging(argv, &android::base::KernelLogger);
+
+    // Make sure we are root.
+    if (::getuid() != 0) {
+        LOG(ERROR) << "Not running as root. Try \"adb root\" first.";
+        return EXIT_FAILURE;
+    }
+
+    if (argc < 3) {
+        std::cerr << " apply-update <directory location where snapshot patches are present>"
+                     "    Apply the snapshots to the COW block device\n";
+        return false;
+    }
+
+    std::string path = std::string(argv[2]);
+    MapSnapshots cow(path);
+    if (!cow.ApplyUpdate()) {
+        return false;
+    }
+    LOG(INFO) << "Apply update success. Please reboot the device";
+    return true;
+}
+
 bool MapPrecreatedSnapshots(int argc, char** argv) {
     android::base::InitLogging(argv, &android::base::KernelLogger);
 
@@ -554,6 +760,7 @@
         {"test-blank-ota", TestOtaHandler},
 #endif
         {"unmap", UnmapCmdHandler},
+        {"apply-update", ApplyUpdate},
         {"map-snapshots", MapPrecreatedSnapshots},
         {"unmap-snapshots", UnMapPrecreatedSnapshots},
         {"delete-snapshots", DeletePrecreatedSnapshots},
diff --git a/fs_mgr/libsnapshot/vts_ota_config_test.cpp b/fs_mgr/libsnapshot/vts_ota_config_test.cpp
index d387eb3..b5618c4 100755
--- a/fs_mgr/libsnapshot/vts_ota_config_test.cpp
+++ b/fs_mgr/libsnapshot/vts_ota_config_test.cpp
@@ -21,6 +21,7 @@
     return android::base::GetIntProperty("ro.vendor.api_level", -1);
 }
 
+// @VsrTest = 3.7.6
 TEST(VAB, Enabled) {
     if (!android::base::GetBoolProperty("ro.build.ab_update", false) && (GetVsrLevel() < __ANDROID_API_T__)) {
         GTEST_SKIP();
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index 7ac7a16..526c761 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -1081,7 +1081,9 @@
 LOG RUN "Testing adb disable-verity -R"
 
 T=$(adb_date)
-adb_su disable-verity -R >&2 ||
+adb_su disable-verity -R >&2
+err=${?}
+[[ ${err} -eq 0 || ${err} -eq 255 ]] ||
   die -t "${T}" "disable-verity -R failed"
 sleep 2
 adb_wait "${ADB_WAIT}" ||
@@ -1192,7 +1194,9 @@
 LOG RUN "Testing adb remount -R"
 
 T=$(adb_date)
-adb_su remount -R </dev/null >&2 ||
+adb_su remount -R </dev/null >&2
+err=${?}
+[[ ${err} -eq 0 || ${err} -eq 255 ]] ||
   die -t "${T}" "adb remount -R failed"
 sleep 2
 adb_wait "${ADB_WAIT}" ||
diff --git a/fs_mgr/tools/dmctl.cpp b/fs_mgr/tools/dmctl.cpp
index 7273087..9dc8c24 100644
--- a/fs_mgr/tools/dmctl.cpp
+++ b/fs_mgr/tools/dmctl.cpp
@@ -115,6 +115,21 @@
             std::string block_device = NextArg();
             return std::make_unique<DmTargetAndroidVerity>(start_sector, num_sectors, keyid,
                                                            block_device);
+        } else if (target_type == "striped") {
+            if (!HasArgs(3)) {
+                std::cerr << "Expected \"striped\" <block_device0> <block_device1> <chunksize>"
+                          << std::endl;
+                return nullptr;
+            }
+            std::string block_device0 = NextArg();
+            std::string block_device1 = NextArg();
+            uint64_t chunk_size;
+            if (!android::base::ParseUint(NextArg(), &chunk_size)) {
+                std::cerr << "Expected start sector, got: " << PreviousArg() << std::endl;
+                return nullptr;
+            }
+            return std::make_unique<DmTargetStripe>(start_sector, num_sectors, chunk_size,
+                                                    block_device0, block_device1);
         } else if (target_type == "bow") {
             if (!HasArgs(1)) {
                 std::cerr << "Expected \"bow\" <block_device>" << std::endl;
diff --git a/init/property_service.cpp b/init/property_service.cpp
index bc4ef42..58a0a7f 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -58,6 +58,7 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <fs_mgr.h>
+#include <private/android_filesystem_config.h>
 #include <property_info_parser/property_info_parser.h>
 #include <property_info_serializer/property_info_serializer.h>
 #include <selinux/android.h>
@@ -117,12 +118,13 @@
 
 static bool persistent_properties_loaded = false;
 
-static int property_set_fd = -1;
 static int from_init_socket = -1;
 static int init_socket = -1;
 static bool accept_messages = false;
 static std::mutex accept_messages_lock;
+static std::mutex selinux_check_access_lock;
 static std::thread property_service_thread;
+static std::thread property_service_for_system_thread;
 
 static std::unique_ptr<PersistWriteThread> persist_write_thread;
 
@@ -167,6 +169,7 @@
     ucred cr = {.pid = 0, .uid = 0, .gid = 0};
     audit_data.cr = &cr;
 
+    auto lock = std::lock_guard{selinux_check_access_lock};
     return selinux_check_access(source_context.c_str(), target_context, "file", "read",
                                 &audit_data) == 0;
 }
@@ -182,10 +185,9 @@
     audit_data.name = name.c_str();
     audit_data.cr = &cr;
 
-    bool has_access = (selinux_check_access(source_context, target_context, "property_service",
-                                            "set", &audit_data) == 0);
-
-    return has_access;
+    auto lock = std::lock_guard{selinux_check_access_lock};
+    return selinux_check_access(source_context, target_context, "property_service", "set",
+                                &audit_data) == 0;
 }
 
 void NotifyPropertyChange(const std::string& name, const std::string& value) {
@@ -400,30 +402,38 @@
         return {PROP_ERROR_INVALID_VALUE};
     }
 
-    prop_info* pi = (prop_info*)__system_property_find(name.c_str());
-    if (pi != nullptr) {
-        // ro.* properties are actually "write-once".
-        if (StartsWith(name, "ro.")) {
-            *error = "Read-only property was already set";
-            return {PROP_ERROR_READ_ONLY_PROPERTY};
-        }
-
-        __system_property_update(pi, value.c_str(), valuelen);
+    if (name == "sys.powerctl") {
+        // No action here - NotifyPropertyChange will trigger the appropriate action, and since this
+        // can come to the second thread, we mustn't call out to the __system_property_* functions
+        // which support multiple readers but only one mutator.
     } else {
-        int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
-        if (rc < 0) {
-            *error = "__system_property_add failed";
-            return {PROP_ERROR_SET_FAILED};
-        }
-    }
+        prop_info* pi = (prop_info*)__system_property_find(name.c_str());
+        if (pi != nullptr) {
+            // ro.* properties are actually "write-once".
+            if (StartsWith(name, "ro.")) {
+                *error = "Read-only property was already set";
+                return {PROP_ERROR_READ_ONLY_PROPERTY};
+            }
 
-    bool need_persist = StartsWith(name, "persist.") || StartsWith(name, "next_boot.");
-    if (socket && persistent_properties_loaded && need_persist) {
-        if (persist_write_thread) {
-            persist_write_thread->Write(name, value, std::move(*socket));
-            return {};
+            __system_property_update(pi, value.c_str(), valuelen);
+        } else {
+            int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
+            if (rc < 0) {
+                *error = "__system_property_add failed";
+                return {PROP_ERROR_SET_FAILED};
+            }
         }
-        WritePersistentProperty(name, value);
+
+        // Don't write properties to disk until after we have read all default
+        // properties to prevent them from being overwritten by default values.
+        bool need_persist = StartsWith(name, "persist.") || StartsWith(name, "next_boot.");
+        if (socket && persistent_properties_loaded && need_persist) {
+            if (persist_write_thread) {
+                persist_write_thread->Write(name, value, std::move(*socket));
+                return {};
+            }
+            WritePersistentProperty(name, value);
+        }
     }
 
     NotifyPropertyChange(name, value);
@@ -584,10 +594,10 @@
     return *ret;
 }
 
-static void handle_property_set_fd() {
+static void handle_property_set_fd(int fd) {
     static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
 
-    int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
+    int s = accept4(fd, nullptr, nullptr, SOCK_CLOEXEC);
     if (s == -1) {
         return;
     }
@@ -1090,6 +1100,12 @@
     // required to support.
     constexpr auto VENDOR_API_LEVEL_PROP = "ro.vendor.api_level";
 
+    if (__system_property_find(VENDOR_API_LEVEL_PROP) != nullptr) {
+        // The device already have ro.vendor.api_level in its vendor/build.prop.
+        // Skip initializing the ro.vendor.api_level property.
+        return;
+    }
+
     auto vendor_api_level = GetIntProperty("ro.board.first_api_level", __ANDROID_VENDOR_API_MAX__);
     if (vendor_api_level != __ANDROID_VENDOR_API_MAX__) {
         // Update the vendor_api_level with "ro.board.api_level" only if both "ro.board.api_level"
@@ -1295,7 +1311,7 @@
     mkdir(APPCOMPAT_OVERRIDE_PROP_FOLDERNAME, S_IRWXU | S_IXGRP | S_IXOTH);
     if (!WriteStringToFile(serialized_contexts, APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0444, 0, 0,
                            false)) {
-        PLOG(ERROR) << "Unable to write vendor overrides to file";
+        PLOG(ERROR) << "Unable to write appcompat override property infos to file";
     }
     selinux_android_restorecon(APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0);
 }
@@ -1432,19 +1448,21 @@
     }
 }
 
-static void PropertyServiceThread() {
+static void PropertyServiceThread(int fd, bool listen_init) {
     Epoll epoll;
     if (auto result = epoll.Open(); !result.ok()) {
         LOG(FATAL) << result.error();
     }
 
-    if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
+    if (auto result = epoll.RegisterHandler(fd, std::bind(handle_property_set_fd, fd));
         !result.ok()) {
         LOG(FATAL) << result.error();
     }
 
-    if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
-        LOG(FATAL) << result.error();
+    if (listen_init) {
+        if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
+            LOG(FATAL) << result.error();
+        }
     }
 
     while (true) {
@@ -1493,6 +1511,23 @@
     cv_.notify_all();
 }
 
+void StartThread(const char* name, int mode, int gid, std::thread& t, bool listen_init) {
+    int fd = -1;
+    if (auto result = CreateSocket(name, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
+                                   /*passcred=*/false, /*should_listen=*/false, mode, /*uid=*/0,
+                                   /*gid=*/gid, /*socketcon=*/{});
+        result.ok()) {
+        fd = *result;
+    } else {
+        LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
+    }
+
+    listen(fd, 8);
+
+    auto new_thread = std::thread(PropertyServiceThread, fd, listen_init);
+    t.swap(new_thread);
+}
+
 void StartPropertyService(int* epoll_socket) {
     InitPropertySet("ro.property_service.version", "2");
 
@@ -1504,19 +1539,9 @@
     init_socket = sockets[1];
     StartSendingMessages();
 
-    if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
-                                   /*passcred=*/false, /*should_listen=*/false, 0666, /*uid=*/0,
-                                   /*gid=*/0, /*socketcon=*/{});
-        result.ok()) {
-        property_set_fd = *result;
-    } else {
-        LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
-    }
-
-    listen(property_set_fd, 8);
-
-    auto new_thread = std::thread{PropertyServiceThread};
-    property_service_thread.swap(new_thread);
+    StartThread(PROP_SERVICE_FOR_SYSTEM_NAME, 0660, AID_SYSTEM, property_service_for_system_thread,
+                true);
+    StartThread(PROP_SERVICE_NAME, 0666, 0, property_service_thread, false);
 
     auto async_persist_writes =
             android::base::GetBoolProperty("ro.property_service.async_persist_writes", false);
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index 8ae7d9e..b7752d9 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -116,27 +116,6 @@
     },
 }
 
-cc_test {
-    name: "libcutils_sockets_test",
-    test_suites: ["device-tests"],
-    static_libs: ["libbase", "libcutils_sockets"],
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-    ],
-
-    srcs: ["sockets_test.cpp"],
-    target: {
-        android: {
-            srcs: [
-                "android_get_control_file_test.cpp",
-                "android_get_control_socket_test.cpp",
-            ],
-        },
-    },
-}
-
 // some files must not be compiled when building against Mingw
 // they correspond to features not used by our host development tools
 // which are also hard or even impossible to port to native Win32
@@ -347,7 +326,10 @@
 
 cc_test {
     name: "KernelLibcutilsTest",
-    test_suites: ["general-tests", "vts"],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
     defaults: ["libcutils_test_static_defaults"],
     test_config: "KernelLibcutilsTest.xml",
 }
diff --git a/libcutils/ashmem-dev.cpp b/libcutils/ashmem-dev.cpp
index 410dbfd..46b8ef2 100644
--- a/libcutils/ashmem-dev.cpp
+++ b/libcutils/ashmem-dev.cpp
@@ -301,6 +301,12 @@
         return -1;
     }
 
+    // forbid size changes to match ashmem behaviour
+    if (fcntl(fd, F_ADD_SEALS, F_SEAL_GROW | F_SEAL_SHRINK) == -1) {
+        ALOGE("memfd_create(%s, %zd) F_ADD_SEALS failed: %m", name, size);
+        return -1;
+    }
+
     if (debug_log) {
         ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
     }
@@ -352,14 +358,29 @@
 }
 
 static int memfd_set_prot_region(int fd, int prot) {
-    /* Only proceed if an fd needs to be write-protected */
+    int seals = fcntl(fd, F_GET_SEALS);
+    if (seals == -1) {
+        ALOGE("memfd_set_prot_region(%d, %d): F_GET_SEALS failed: %s\n", fd, prot, strerror(errno));
+        return -1;
+    }
+
     if (prot & PROT_WRITE) {
+        /* Now we want the buffer to be read-write, let's check if the buffer
+         * has been previously marked as read-only before, if so return error
+         */
+        if (seals & F_SEAL_FUTURE_WRITE) {
+            ALOGE("memfd_set_prot_region(%d, %d): region is write protected\n", fd, prot);
+            errno = EINVAL;  // inline with ashmem error code, if already in
+                             // read-only mode
+            return -1;
+        }
         return 0;
     }
 
-    if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
-        ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
-              strerror(errno));
+    /* We would only allow read-only for any future file operations */
+    if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE | F_SEAL_SEAL) == -1) {
+        ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE | F_SEAL_SEAL seal failed: %s\n",
+              fd, prot, strerror(errno));
         return -1;
     }
 
diff --git a/libvendorsupport/include_llndk/android/llndk-versioning.h b/libvendorsupport/include_llndk/android/llndk-versioning.h
index 7c408c9..b375a2f 100644
--- a/libvendorsupport/include_llndk/android/llndk-versioning.h
+++ b/libvendorsupport/include_llndk/android/llndk-versioning.h
@@ -40,8 +40,10 @@
 #else  // __ANDROID_VENDOR__
 
 // For non-vendor libraries, __INTRODUCED_IN_LLNDK must be ignored because it must not change
-// symbols of NDK or the system side of the treble boundary.
-#define __INTRODUCED_IN_LLNDK(vendor_api_level)
+// symbols of NDK or the system side of the treble boundary. It leaves a no-op annotation for ABI
+// analysis.
+#define __INTRODUCED_IN_LLNDK(vendor_api_level) \
+    __attribute__((annotate("introduced_in_llndk=" #vendor_api_level)))
 
 #endif  // __ANDROID_VENDOR__
 
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 3c367f9..1e0fa9a 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -303,6 +303,9 @@
     mkdir /mnt/runtime/full 0755 root root
     mkdir /mnt/runtime/full/self 0755 root root
 
+    # For Pre-reboot Dexopt
+    mkdir /mnt/pre_reboot_dexopt 0755 artd artd
+
     # Symlink to keep legacy apps working in multi-user world
     symlink /storage/self/primary /mnt/sdcard
     symlink /mnt/user/0/primary /mnt/runtime/default/self/primary
@@ -641,9 +644,9 @@
 
     mkdir /metadata/staged-install 0770 root system
 
-    mkdir /metadata/aconfig 0750 root system
-    mkdir /metadata/aconfig/flags 0750 root system
-    mkdir /metadata/aconfig/boot 0754 root system
+    mkdir /metadata/aconfig 0775 root system
+    mkdir /metadata/aconfig/flags 0770 root system
+    mkdir /metadata/aconfig/boot 0775 root system
 
 on late-fs
     # Ensure that tracefs has the correct permissions.