Merge "Revert "snapuserd: Handle real time signal 36""
diff --git a/fs_mgr/OWNERS b/fs_mgr/OWNERS
index cf353a1..c6f9054 100644
--- a/fs_mgr/OWNERS
+++ b/fs_mgr/OWNERS
@@ -1,2 +1,4 @@
+# Bug component: 30545
 bowgotsai@google.com
 dvander@google.com
+elsk@google.com
diff --git a/fs_mgr/libsnapshot/cow_reader.cpp b/fs_mgr/libsnapshot/cow_reader.cpp
index e8f0153..5306b28 100644
--- a/fs_mgr/libsnapshot/cow_reader.cpp
+++ b/fs_mgr/libsnapshot/cow_reader.cpp
@@ -231,7 +231,7 @@
                 memcpy(&footer_->op, &current_op, sizeof(footer->op));
                 off_t offs = lseek(fd_.get(), pos, SEEK_SET);
                 if (offs < 0 || pos != static_cast<uint64_t>(offs)) {
-                    PLOG(ERROR) << "lseek next op failed";
+                    PLOG(ERROR) << "lseek next op failed " << offs;
                     return false;
                 }
                 if (!android::base::ReadFully(fd_, &footer->data, sizeof(footer->data))) {
@@ -251,7 +251,7 @@
         // Position for next cluster read
         off_t offs = lseek(fd_.get(), pos, SEEK_SET);
         if (offs < 0 || pos != static_cast<uint64_t>(offs)) {
-            PLOG(ERROR) << "lseek next op failed";
+            PLOG(ERROR) << "lseek next op failed " << offs;
             return false;
         }
         ops_buffer->resize(current_op_num);
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/mock_snapshot_writer.h b/fs_mgr/libsnapshot/include/libsnapshot/mock_snapshot_writer.h
index 3655c01..b0be5a5 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/mock_snapshot_writer.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/mock_snapshot_writer.h
@@ -44,6 +44,7 @@
 
     // Open the writer in write mode (no append).
     MOCK_METHOD(bool, Initialize, (), (override));
+    MOCK_METHOD(bool, VerifyMergeOps, (), (override, const, noexcept));
 
     // Open the writer in append mode, with the last label to resume
     // from. See CowWriter::InitializeAppend.
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot_writer.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot_writer.h
index b09e1ae..545f117 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot_writer.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot_writer.h
@@ -47,6 +47,7 @@
     virtual bool InitializeAppend(uint64_t label) = 0;
 
     virtual std::unique_ptr<FileDescriptor> OpenReader() = 0;
+    virtual bool VerifyMergeOps() const noexcept = 0;
 
   protected:
     android::base::borrowed_fd GetSourceFd();
@@ -58,7 +59,7 @@
 };
 
 // Send writes to a COW or a raw device directly, based on a threshold.
-class CompressedSnapshotWriter : public ISnapshotWriter {
+class CompressedSnapshotWriter final : public ISnapshotWriter {
   public:
     CompressedSnapshotWriter(const CowOptions& options);
 
@@ -70,6 +71,7 @@
     bool Finalize() override;
     uint64_t GetCowSize() override;
     std::unique_ptr<FileDescriptor> OpenReader() override;
+    bool VerifyMergeOps() const noexcept;
 
   protected:
     bool EmitCopy(uint64_t new_block, uint64_t old_block) override;
@@ -81,13 +83,14 @@
     bool EmitSequenceData(size_t num_ops, const uint32_t* data) override;
 
   private:
+    std::unique_ptr<CowReader> OpenCowReader() const;
     android::base::unique_fd cow_device_;
 
     std::unique_ptr<CowWriter> cow_;
 };
 
 // Write directly to a dm-snapshot device.
-class OnlineKernelSnapshotWriter : public ISnapshotWriter {
+class OnlineKernelSnapshotWriter final : public ISnapshotWriter {
   public:
     OnlineKernelSnapshotWriter(const CowOptions& options);
 
@@ -101,6 +104,10 @@
     uint64_t GetCowSize() override { return cow_size_; }
     std::unique_ptr<FileDescriptor> OpenReader() override;
 
+    // Online kernel snapshot writer doesn't care about merge sequences.
+    // So ignore.
+    bool VerifyMergeOps() const noexcept override { return true; }
+
   protected:
     bool EmitRawBlocks(uint64_t new_block_start, const void* data, size_t size) override;
     bool EmitZeroBlocks(uint64_t new_block_start, uint64_t num_blocks) override;
diff --git a/fs_mgr/libsnapshot/snapshot_fuzz_utils.cpp b/fs_mgr/libsnapshot/snapshot_fuzz_utils.cpp
index 0096f85..acee2f4 100644
--- a/fs_mgr/libsnapshot/snapshot_fuzz_utils.cpp
+++ b/fs_mgr/libsnapshot/snapshot_fuzz_utils.cpp
@@ -139,7 +139,7 @@
     auto& dm = DeviceMapper::Instance();
     std::vector<DeviceMapper::TargetInfo> table;
     if (!dm.GetTableInfo(dev_name, &table)) {
-        PCHECK(errno == ENODEV);
+        PCHECK(errno == ENODEV || errno == ENXIO);
         return {};
     }
     return table;
diff --git a/fs_mgr/libsnapshot/snapshot_writer.cpp b/fs_mgr/libsnapshot/snapshot_writer.cpp
index 3eda08e..48b7d80 100644
--- a/fs_mgr/libsnapshot/snapshot_writer.cpp
+++ b/fs_mgr/libsnapshot/snapshot_writer.cpp
@@ -67,7 +67,7 @@
     return cow_->GetCowSize();
 }
 
-std::unique_ptr<FileDescriptor> CompressedSnapshotWriter::OpenReader() {
+std::unique_ptr<CowReader> CompressedSnapshotWriter::OpenCowReader() const {
     unique_fd cow_fd(dup(cow_device_.get()));
     if (cow_fd < 0) {
         PLOG(ERROR) << "dup COW device";
@@ -79,6 +79,20 @@
         LOG(ERROR) << "Unable to read COW";
         return nullptr;
     }
+    return cow;
+}
+
+bool CompressedSnapshotWriter::VerifyMergeOps() const noexcept {
+    auto cow_reader = OpenCowReader();
+    if (cow_reader == nullptr) {
+        LOG(ERROR) << "Couldn't open CowReader";
+        return false;
+    }
+    return cow_reader->VerifyMergeOps();
+}
+
+std::unique_ptr<FileDescriptor> CompressedSnapshotWriter::OpenReader() {
+    auto cow = OpenCowReader();
 
     auto reader = std::make_unique<CompressedSnapshotReader>();
     if (!reader->SetCow(std::move(cow))) {
diff --git a/init/Android.bp b/init/Android.bp
index 1c303fc..9b02c38 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -455,6 +455,7 @@
         "persistent_properties_test.cpp",
         "property_service_test.cpp",
         "property_type_test.cpp",
+        "reboot_test.cpp",
         "rlimit_parser_test.cpp",
         "service_test.cpp",
         "subcontext_test.cpp",
diff --git a/init/mount_namespace.cpp b/init/mount_namespace.cpp
index 593e5ae..bce1cc3 100644
--- a/init/mount_namespace.cpp
+++ b/init/mount_namespace.cpp
@@ -82,11 +82,6 @@
     return updatable;
 }
 
-static bool IsMicrodroid() {
-    static bool is_microdroid = android::base::GetProperty("ro.hardware", "") == "microdroid";
-    return is_microdroid;
-}
-
 // In case we have two sets of APEXes (non-updatable, updatable), we need two separate mount
 // namespaces.
 static bool NeedsTwoMountNamespaces() {
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 1681627..6aa9912 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -550,8 +550,8 @@
 
 // Like StopServices, but also logs all the services that failed to stop after the provided timeout.
 // Returns number of violators.
-static int StopServicesAndLogViolations(const std::set<std::string>& services,
-                                        std::chrono::milliseconds timeout, bool terminate) {
+int StopServicesAndLogViolations(const std::set<std::string>& services,
+                                 std::chrono::milliseconds timeout, bool terminate) {
     StopServices(services, timeout, terminate);
     int still_running = 0;
     for (const auto& s : ServiceList::GetInstance()) {
diff --git a/init/reboot.h b/init/reboot.h
index 81c3edc..551a114 100644
--- a/init/reboot.h
+++ b/init/reboot.h
@@ -17,11 +17,17 @@
 #ifndef _INIT_REBOOT_H
 #define _INIT_REBOOT_H
 
+#include <chrono>
+#include <set>
 #include <string>
 
 namespace android {
 namespace init {
 
+// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
+// Returns number of violators.
+int StopServicesAndLogViolations(const std::set<std::string>& services,
+                                 std::chrono::milliseconds timeout, bool terminate);
 // Parses and handles a setprop sys.powerctl message.
 void HandlePowerctlMessage(const std::string& command);
 
diff --git a/init/reboot_test.cpp b/init/reboot_test.cpp
new file mode 100644
index 0000000..b3d038d
--- /dev/null
+++ b/init/reboot_test.cpp
@@ -0,0 +1,196 @@
+/*
+ * 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 "reboot.h"
+
+#include <errno.h>
+#include <unistd.h>
+
+#include <memory>
+#include <string_view>
+
+#include <android-base/file.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <gtest/gtest.h>
+#include <selinux/selinux.h>
+
+#include "builtin_arguments.h"
+#include "builtins.h"
+#include "parser.h"
+#include "service_list.h"
+#include "service_parser.h"
+#include "subcontext.h"
+#include "util.h"
+
+using namespace std::literals;
+
+using android::base::GetProperty;
+using android::base::Join;
+using android::base::SetProperty;
+using android::base::Split;
+using android::base::StringReplace;
+using android::base::WaitForProperty;
+using android::base::WriteStringToFd;
+
+namespace android {
+namespace init {
+
+class RebootTest : public ::testing::Test {
+  public:
+    RebootTest() {
+        std::vector<std::string> names = GetServiceNames();
+        if (!names.empty()) {
+            ADD_FAILURE() << "Expected empty ServiceList but found: [" << Join(names, ',') << "]";
+        }
+    }
+
+    ~RebootTest() {
+        std::vector<std::string> names = GetServiceNames();
+        for (const auto& name : names) {
+            auto s = ServiceList::GetInstance().FindService(name);
+            auto pid = s->pid();
+            ServiceList::GetInstance().RemoveService(*s);
+            if (pid > 0) {
+                kill(pid, SIGTERM);
+                kill(pid, SIGKILL);
+            }
+        }
+    }
+
+  private:
+    std::vector<std::string> GetServiceNames() const {
+        std::vector<std::string> names;
+        for (const auto& s : ServiceList::GetInstance()) {
+            names.push_back(s->name());
+        }
+        return names;
+    }
+};
+
+std::string GetSecurityContext() {
+    char* ctx;
+    if (getcon(&ctx) == -1) {
+        ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
+    }
+    std::string result = std::string(ctx);
+    freecon(ctx);
+    return result;
+}
+
+void AddTestService(const std::string& name) {
+    static constexpr std::string_view kScriptTemplate = R"init(
+service $name /system/bin/yes
+    user shell
+    group shell
+    seclabel $selabel
+)init";
+
+    std::string script = StringReplace(StringReplace(kScriptTemplate, "$name", name, false),
+                                       "$selabel", GetSecurityContext(), false);
+    ServiceList& service_list = ServiceList::GetInstance();
+    Parser parser;
+    parser.AddSectionParser("service",
+                            std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
+
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    ASSERT_TRUE(WriteStringToFd(script, tf.fd));
+    ASSERT_TRUE(parser.ParseConfig(tf.path));
+}
+
+TEST_F(RebootTest, StopServicesSIGTERM) {
+    if (getuid() != 0) {
+        GTEST_SKIP() << "Skipping test, must be run as root.";
+        return;
+    }
+
+    AddTestService("A");
+    AddTestService("B");
+
+    auto service_a = ServiceList::GetInstance().FindService("A");
+    ASSERT_NE(nullptr, service_a);
+    auto service_b = ServiceList::GetInstance().FindService("B");
+    ASSERT_NE(nullptr, service_b);
+
+    ASSERT_RESULT_OK(service_a->Start());
+    ASSERT_TRUE(service_a->IsRunning());
+    ASSERT_RESULT_OK(service_b->Start());
+    ASSERT_TRUE(service_b->IsRunning());
+
+    std::unique_ptr<Service> oneshot_service;
+    {
+        auto result = Service::MakeTemporaryOneshotService(
+                {"exec", GetSecurityContext(), "--", "/system/bin/yes"});
+        ASSERT_RESULT_OK(result);
+        oneshot_service = std::move(*result);
+    }
+    std::string oneshot_service_name = oneshot_service->name();
+    oneshot_service->Start();
+    ASSERT_TRUE(oneshot_service->IsRunning());
+    ServiceList::GetInstance().AddService(std::move(oneshot_service));
+
+    EXPECT_EQ(0, StopServicesAndLogViolations({"A", "B", oneshot_service_name}, 10s,
+                                              /* terminate= */ true));
+    EXPECT_FALSE(service_a->IsRunning());
+    EXPECT_FALSE(service_b->IsRunning());
+    // Oneshot services are deleted from the ServiceList after they are destroyed.
+    auto oneshot_service_after_stop = ServiceList::GetInstance().FindService(oneshot_service_name);
+    EXPECT_EQ(nullptr, oneshot_service_after_stop);
+}
+
+TEST_F(RebootTest, StopServicesSIGKILL) {
+    if (getuid() != 0) {
+        GTEST_SKIP() << "Skipping test, must be run as root.";
+        return;
+    }
+
+    AddTestService("A");
+    AddTestService("B");
+
+    auto service_a = ServiceList::GetInstance().FindService("A");
+    ASSERT_NE(nullptr, service_a);
+    auto service_b = ServiceList::GetInstance().FindService("B");
+    ASSERT_NE(nullptr, service_b);
+
+    ASSERT_RESULT_OK(service_a->Start());
+    ASSERT_TRUE(service_a->IsRunning());
+    ASSERT_RESULT_OK(service_b->Start());
+    ASSERT_TRUE(service_b->IsRunning());
+
+    std::unique_ptr<Service> oneshot_service;
+    {
+        auto result = Service::MakeTemporaryOneshotService(
+                {"exec", GetSecurityContext(), "--", "/system/bin/yes"});
+        ASSERT_RESULT_OK(result);
+        oneshot_service = std::move(*result);
+    }
+    std::string oneshot_service_name = oneshot_service->name();
+    oneshot_service->Start();
+    ASSERT_TRUE(oneshot_service->IsRunning());
+    ServiceList::GetInstance().AddService(std::move(oneshot_service));
+
+    EXPECT_EQ(0, StopServicesAndLogViolations({"A", "B", oneshot_service_name}, 10s,
+                                              /* terminate= */ false));
+    EXPECT_FALSE(service_a->IsRunning());
+    EXPECT_FALSE(service_b->IsRunning());
+    // Oneshot services are deleted from the ServiceList after they are destroyed.
+    auto oneshot_service_after_stop = ServiceList::GetInstance().FindService(oneshot_service_name);
+    EXPECT_EQ(nullptr, oneshot_service_after_stop);
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index f1fbffe..6eaa80f 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -44,6 +44,7 @@
 #endif
 
 using android::base::GetExecutablePath;
+using android::base::GetProperty;
 using android::base::Join;
 using android::base::Socketpair;
 using android::base::Split;
@@ -337,6 +338,11 @@
 }
 
 void InitializeSubcontext() {
+    if (IsMicrodroid()) {
+        LOG(INFO) << "Not using subcontext for microdroid";
+        return;
+    }
+
     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
         subcontext.reset(
                 new Subcontext(std::vector<std::string>{"/vendor", "/odm"}, kVendorContext));
@@ -351,6 +357,9 @@
 }
 
 bool SubcontextChildReap(pid_t pid) {
+    if (!subcontext) {
+        return false;
+    }
     if (subcontext->pid() == pid) {
         if (!subcontext_terminated_by_shutdown) {
             subcontext->Restart();
diff --git a/init/util.cpp b/init/util.cpp
index 9f7bfdb..d1e518b 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -757,5 +757,10 @@
     is_default_mount_namespace_ready = true;
 }
 
+bool IsMicrodroid() {
+    static bool is_microdroid = android::base::GetProperty("ro.hardware", "") == "microdroid";
+    return is_microdroid;
+}
+
 }  // namespace init
 }  // namespace android
diff --git a/init/util.h b/init/util.h
index daba852..bf53675 100644
--- a/init/util.h
+++ b/init/util.h
@@ -103,5 +103,7 @@
 
 bool IsDefaultMountNamespaceReady();
 void SetDefaultMountNamespaceReady();
+
+bool IsMicrodroid();
 }  // namespace init
 }  // namespace android
diff --git a/trusty/keymaster/Android.bp b/trusty/keymaster/Android.bp
index 155363c..7bd1d10 100644
--- a/trusty/keymaster/Android.bp
+++ b/trusty/keymaster/Android.bp
@@ -120,6 +120,7 @@
     ],
     required: [
         "android.hardware.hardware_keystore.xml",
+        "RemoteProvisioner",
     ],
 }