Merge "Added Mock function call tests"
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index a00a202..39d7fff 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -20,6 +20,7 @@
 #include <fcntl.h>
 #include <linux/prctl.h>
 #include <malloc.h>
+#include <pthread.h>
 #include <stdlib.h>
 #include <sys/capability.h>
 #include <sys/mman.h>
@@ -2703,3 +2704,58 @@
   }
   ASSERT_TRUE(found_valid_elf) << "Did not find any elf files with valid BuildIDs to check.";
 }
+
+const char kLogMessage[] = "Should not see this log message.";
+
+// Verify that the logd process does not read the log.
+TEST_F(CrasherTest, logd_skips_reading_logs) {
+  StartProcess([]() {
+    pthread_setname_np(pthread_self(), "logd");
+    LOG(INFO) << kLogMessage;
+    abort();
+  });
+
+  unique_fd output_fd;
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  int intercept_result;
+  FinishIntercept(&intercept_result);
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  // logd should not contain our log message.
+  ASSERT_NOT_MATCH(result, kLogMessage);
+}
+
+// Verify that the logd process does not read the log when the non-main
+// thread crashes.
+TEST_F(CrasherTest, logd_skips_reading_logs_not_main_thread) {
+  StartProcess([]() {
+    pthread_setname_np(pthread_self(), "logd");
+    LOG(INFO) << kLogMessage;
+
+    std::thread thread([]() {
+      pthread_setname_np(pthread_self(), "not_logd_thread");
+      // Raise the signal on the side thread.
+      raise_debugger_signal(kDebuggerdTombstone);
+    });
+    thread.join();
+    _exit(0);
+  });
+
+  unique_fd output_fd;
+  StartIntercept(&output_fd, kDebuggerdTombstone);
+  FinishCrasher();
+  AssertDeath(0);
+
+  int intercept_result;
+  FinishIntercept(&intercept_result);
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
+  ASSERT_NOT_MATCH(result, kLogMessage);
+}
diff --git a/debuggerd/libdebuggerd/tombstone_proto.cpp b/debuggerd/libdebuggerd/tombstone_proto.cpp
index 9a565de..acd814e 100644
--- a/debuggerd/libdebuggerd/tombstone_proto.cpp
+++ b/debuggerd/libdebuggerd/tombstone_proto.cpp
@@ -690,7 +690,14 @@
 
   // Only dump logs on debuggable devices.
   if (android::base::GetBoolProperty("ro.debuggable", false)) {
-    dump_logcat(&result, main_thread.pid);
+    // Get the thread that corresponds to the main pid of the process.
+    const ThreadInfo& thread = threads.at(main_thread.pid);
+
+    // Do not attempt to dump logs of the logd process because the gathering
+    // of logs can hang until a timeout occurs.
+    if (thread.thread_name != "logd") {
+      dump_logcat(&result, main_thread.pid);
+    }
   }
 
   dump_open_fds(&result, open_files);
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index 460d49d..f472bab 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -196,6 +196,17 @@
         return true;
     }
 
+    bool ShouldSkipLegacyMerging() {
+        if (!GetLegacyCompressionEnabledProperty() || !snapuserd_required_) {
+            return false;
+        }
+        int api_level = android::base::GetIntProperty("ro.board.api_level", -1);
+        if (api_level == -1) {
+            api_level = android::base::GetIntProperty("ro.product.first_api_level", -1);
+        }
+        return api_level != __ANDROID_API_S__;
+    }
+
     void InitializeState() {
         ASSERT_TRUE(sm->EnsureImageManager());
         image_manager_ = sm->image_manager();
@@ -654,6 +665,10 @@
 
     test_device->set_slot_suffix("_b");
     ASSERT_TRUE(sm->CreateLogicalAndSnapshotPartitions("super", snapshot_timeout_));
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(sm->InitiateMerge());
 
     // The device should have been switched to a snapshot-merge target.
@@ -761,6 +776,10 @@
     ASSERT_NE(init, nullptr);
     ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
     ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", snapshot_timeout_));
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
 
     // Now, reflash super. Note that we haven't called ProcessUpdateState, so the
@@ -1344,6 +1363,10 @@
     }
 
     // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(init->IsSnapuserdRequired(), snapuserd_required_);
     {
@@ -1407,6 +1430,10 @@
     ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", snapshot_timeout_));
 
     // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(UpdateState::MergeCompleted, init->ProcessUpdateState());
 }
@@ -1476,6 +1503,10 @@
     }
 
     // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(init->IsSnapuserdRequired(), snapuserd_required_);
     {
@@ -1584,6 +1615,10 @@
             });
 
     // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(init->IsSnapuserdRequired(), snapuserd_required_);
     {
@@ -1786,6 +1821,10 @@
 
     // Initiate the merge and wait for it to be completed.
     auto new_sm = SnapshotManager::New(new TestDeviceInfo(fake_super, "_b"));
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(new_sm->InitiateMerge());
     ASSERT_EQ(UpdateState::MergeCompleted, new_sm->ProcessUpdateState());
 
@@ -1924,6 +1963,10 @@
     ASSERT_GE(fd, 0);
 
     // COW cannot be removed due to open fd, so expect a soft failure.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(UpdateState::MergeNeedsReboot, init->ProcessUpdateState());
 
@@ -2027,6 +2070,10 @@
 
     // Initiate the merge and then immediately stop it to simulate a reboot.
     auto new_sm = SnapshotManager::New(new TestDeviceInfo(fake_super, "_b"));
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(new_sm->InitiateMerge());
     ASSERT_TRUE(UnmapAll());
 
@@ -2059,6 +2106,10 @@
 
     // Initiate the merge and then immediately stop it to simulate a reboot.
     auto new_sm = SnapshotManager::New(new TestDeviceInfo(fake_super, "_b"));
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(new_sm->InitiateMerge());
     ASSERT_TRUE(UnmapAll());
 
@@ -2136,6 +2187,10 @@
 
 // Test update package that requests data wipe.
 TEST_F(SnapshotUpdateTest, DataWipeRequiredInPackage) {
+    if (ShouldSkipLegacyMerging()) {
+        GTEST_SKIP() << "Skipping legacy merge in test";
+    }
+
     AddOperationForPartitions();
     // Execute the update.
     ASSERT_TRUE(sm->BeginUpdate());
@@ -2175,6 +2230,10 @@
 
 // Test update package that requests data wipe.
 TEST_F(SnapshotUpdateTest, DataWipeWithStaleSnapshots) {
+    if (ShouldSkipLegacyMerging()) {
+        GTEST_SKIP() << "Skipping legacy merge in test";
+    }
+
     AddOperationForPartitions();
 
     // Execute the update.
@@ -2397,6 +2456,10 @@
     }
 
     // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
     ASSERT_TRUE(init->InitiateMerge());
     ASSERT_EQ(UpdateState::MergeCompleted, init->ProcessUpdateState());
 
diff --git a/gatekeeperd/Android.bp b/gatekeeperd/Android.bp
index 838f734..534fc1a 100644
--- a/gatekeeperd/Android.bp
+++ b/gatekeeperd/Android.bp
@@ -18,8 +18,8 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-cc_binary {
-    name: "gatekeeperd",
+cc_defaults {
+    name: "gatekeeperd_defaults",
     cflags: [
         "-Wall",
         "-Wextra",
@@ -52,6 +52,16 @@
 
     static_libs: ["libscrypt_static"],
     include_dirs: ["external/scrypt/lib/crypto"],
+}
+
+cc_binary {
+    name: "gatekeeperd",
+    defaults: [
+        "gatekeeperd_defaults",
+    ],
+    srcs: [
+        "main.cpp",
+    ],
     init_rc: ["gatekeeperd.rc"],
 }
 
@@ -88,3 +98,20 @@
         "libbinder",
     ],
 }
+
+cc_fuzz {
+    name: "gatekeeperd_service_fuzzer",
+    defaults: [
+        "gatekeeperd_defaults",
+        "service_fuzzer_defaults"
+    ],
+    srcs: [
+        "fuzzer/GateKeeperServiceFuzzer.cpp",
+    ],
+    fuzz_config: {
+        cc: [
+            "subrahmanyaman@google.com",
+            "swillden@google.com",
+        ],
+    },
+}
\ No newline at end of file
diff --git a/gatekeeperd/fuzzer/GateKeeperServiceFuzzer.cpp b/gatekeeperd/fuzzer/GateKeeperServiceFuzzer.cpp
new file mode 100644
index 0000000..bc0d5fe
--- /dev/null
+++ b/gatekeeperd/fuzzer/GateKeeperServiceFuzzer.cpp
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2023 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 <fuzzbinder/libbinder_driver.h>
+
+#include "gatekeeperd.h"
+
+using android::fuzzService;
+using android::GateKeeperProxy;
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    auto gatekeeperService = new GateKeeperProxy();
+    fuzzService(gatekeeperService, FuzzedDataProvider(data, size));
+    return 0;
+}
\ No newline at end of file
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index eb43a33..e5241b5 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -13,11 +13,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 #define LOG_TAG "gatekeeperd"
 
-#include <android/service/gatekeeper/BnGateKeeperService.h>
-#include <gatekeeper/GateKeeperResponse.h>
+#include "gatekeeperd.h"
 
 #include <endian.h>
 #include <errno.h>
@@ -39,25 +37,18 @@
 #include <log/log.h>
 #include <utils/String16.h>
 
-#include <aidl/android/hardware/gatekeeper/IGatekeeper.h>
 #include <aidl/android/hardware/security/keymint/HardwareAuthToken.h>
 #include <aidl/android/security/authorization/IKeystoreAuthorization.h>
-#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
 #include <hidl/HidlSupport.h>
 
 using android::sp;
 using android::hardware::Return;
 using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
 using android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
-using android::hardware::gatekeeper::V1_0::IGatekeeper;
 
 using AidlGatekeeperEnrollResp = aidl::android::hardware::gatekeeper::GatekeeperEnrollResponse;
 using AidlGatekeeperVerifyResp = aidl::android::hardware::gatekeeper::GatekeeperVerifyResponse;
-using AidlIGatekeeper = aidl::android::hardware::gatekeeper::IGatekeeper;
 
-using ::android::binder::Status;
-using ::android::service::gatekeeper::BnGateKeeperService;
-using GKResponse = ::android::service::gatekeeper::GateKeeperResponse;
 using GKResponseCode = ::android::service::gatekeeper::ResponseCode;
 using ::aidl::android::hardware::security::keymint::HardwareAuthenticatorType;
 using ::aidl::android::hardware::security::keymint::HardwareAuthToken;
@@ -70,172 +61,167 @@
 static const String16 DUMP_PERMISSION("android.permission.DUMP");
 constexpr const char gatekeeperServiceName[] = "android.hardware.gatekeeper.IGatekeeper/default";
 
-class GateKeeperProxy : public BnGateKeeperService {
-  public:
-    GateKeeperProxy() {
-        clear_state_if_needed_done = false;
-        hw_device = IGatekeeper::getService();
-        ::ndk::SpAIBinder ks2Binder(AServiceManager_getService(gatekeeperServiceName));
-        aidl_hw_device = AidlIGatekeeper::fromBinder(ks2Binder);
-        is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
+GateKeeperProxy::GateKeeperProxy() {
+    clear_state_if_needed_done = false;
+    hw_device = IGatekeeper::getService();
+    ::ndk::SpAIBinder ks2Binder(AServiceManager_getService(gatekeeperServiceName));
+    aidl_hw_device = AidlIGatekeeper::fromBinder(ks2Binder);
+    is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
 
-        if (!aidl_hw_device && !hw_device) {
-            LOG(ERROR) << "Could not find Gatekeeper device, which makes me very sad.";
+    if (!aidl_hw_device && !hw_device) {
+        LOG(ERROR) << "Could not find Gatekeeper device, which makes me very sad.";
+    }
+}
+
+void GateKeeperProxy::store_sid(uint32_t userId, uint64_t sid) {
+    char filename[21];
+    snprintf(filename, sizeof(filename), "%u", userId);
+    int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
+    if (fd < 0) {
+        ALOGE("could not open file: %s: %s", filename, strerror(errno));
+        return;
+    }
+    write(fd, &sid, sizeof(sid));
+    close(fd);
+}
+
+void GateKeeperProxy::clear_state_if_needed() {
+    if (clear_state_if_needed_done) {
+        return;
+    }
+
+    if (mark_cold_boot() && !is_running_gsi) {
+        ALOGI("cold boot: clearing state");
+        if (aidl_hw_device) {
+            aidl_hw_device->deleteAllUsers();
+        } else if (hw_device) {
+            hw_device->deleteAllUsers([](const GatekeeperResponse&) {});
         }
     }
 
-    virtual ~GateKeeperProxy() {}
+    clear_state_if_needed_done = true;
+}
 
-    void store_sid(uint32_t userId, uint64_t sid) {
-        char filename[21];
-        snprintf(filename, sizeof(filename), "%u", userId);
+bool GateKeeperProxy::mark_cold_boot() {
+    const char* filename = ".coldboot";
+    if (access(filename, F_OK) == -1) {
         int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
         if (fd < 0) {
-            ALOGE("could not open file: %s: %s", filename, strerror(errno));
-            return;
+            ALOGE("could not open file: %s : %s", filename, strerror(errno));
+            return false;
         }
-        write(fd, &sid, sizeof(sid));
         close(fd);
+        return true;
     }
+    return false;
+}
 
-    void clear_state_if_needed() {
-        if (clear_state_if_needed_done) {
-            return;
-        }
-
-        if (mark_cold_boot() && !is_running_gsi) {
-            ALOGI("cold boot: clearing state");
-            if (aidl_hw_device) {
-                aidl_hw_device->deleteAllUsers();
-            } else if (hw_device) {
-                hw_device->deleteAllUsers([](const GatekeeperResponse&) {});
-            }
-        }
-
-        clear_state_if_needed_done = true;
+void GateKeeperProxy::maybe_store_sid(uint32_t userId, uint64_t sid) {
+    char filename[21];
+    snprintf(filename, sizeof(filename), "%u", userId);
+    if (access(filename, F_OK) == -1) {
+        store_sid(userId, sid);
     }
+}
 
-    bool mark_cold_boot() {
-        const char* filename = ".coldboot";
-        if (access(filename, F_OK) == -1) {
-            int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
-            if (fd < 0) {
-                ALOGE("could not open file: %s : %s", filename, strerror(errno));
-                return false;
-            }
-            close(fd);
-            return true;
-        }
-        return false;
-    }
+uint64_t GateKeeperProxy::read_sid(uint32_t userId) {
+    char filename[21];
+    uint64_t sid;
+    snprintf(filename, sizeof(filename), "%u", userId);
+    int fd = open(filename, O_RDONLY);
+    if (fd < 0) return 0;
+    read(fd, &sid, sizeof(sid));
+    close(fd);
+    return sid;
+}
 
-    void maybe_store_sid(uint32_t userId, uint64_t sid) {
-        char filename[21];
-        snprintf(filename, sizeof(filename), "%u", userId);
-        if (access(filename, F_OK) == -1) {
-            store_sid(userId, sid);
-        }
+void GateKeeperProxy::clear_sid(uint32_t userId) {
+    char filename[21];
+    snprintf(filename, sizeof(filename), "%u", userId);
+    if (remove(filename) < 0 && errno != ENOENT) {
+        ALOGE("%s: could not remove file [%s], attempting 0 write", __func__, strerror(errno));
+        store_sid(userId, 0);
     }
+}
 
-    uint64_t read_sid(uint32_t userId) {
-        char filename[21];
-        uint64_t sid;
-        snprintf(filename, sizeof(filename), "%u", userId);
-        int fd = open(filename, O_RDONLY);
-        if (fd < 0) return 0;
-        read(fd, &sid, sizeof(sid));
-        close(fd);
-        return sid;
+uint32_t GateKeeperProxy::adjust_userId(uint32_t userId) {
+    static constexpr uint32_t kGsiOffset = 1000000;
+    CHECK(userId < kGsiOffset);
+    CHECK((aidl_hw_device != nullptr) || (hw_device != nullptr));
+    if (is_running_gsi) {
+        return userId + kGsiOffset;
     }
-
-    void clear_sid(uint32_t userId) {
-        char filename[21];
-        snprintf(filename, sizeof(filename), "%u", userId);
-        if (remove(filename) < 0 && errno != ENOENT) {
-            ALOGE("%s: could not remove file [%s], attempting 0 write", __func__, strerror(errno));
-            store_sid(userId, 0);
-        }
-    }
-
-    // This should only be called on userIds being passed to the GateKeeper HAL. It ensures that
-    // secure storage shared across a GSI image and a host image will not overlap.
-    uint32_t adjust_userId(uint32_t userId) {
-        static constexpr uint32_t kGsiOffset = 1000000;
-        CHECK(userId < kGsiOffset);
-        CHECK((aidl_hw_device != nullptr) || (hw_device != nullptr));
-        if (is_running_gsi) {
-            return userId + kGsiOffset;
-        }
-        return userId;
-    }
+    return userId;
+}
 
 #define GK_ERROR *gkResponse = GKResponse::error(), Status::ok()
 
-    Status enroll(int32_t userId, const std::optional<std::vector<uint8_t>>& currentPasswordHandle,
-                  const std::optional<std::vector<uint8_t>>& currentPassword,
-                  const std::vector<uint8_t>& desiredPassword, GKResponse* gkResponse) override {
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int calling_pid = ipc->getCallingPid();
-        const int calling_uid = ipc->getCallingUid();
-        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
-            return GK_ERROR;
-        }
+Status GateKeeperProxy::enroll(int32_t userId,
+                               const std::optional<std::vector<uint8_t>>& currentPasswordHandle,
+                               const std::optional<std::vector<uint8_t>>& currentPassword,
+                               const std::vector<uint8_t>& desiredPassword,
+                               GKResponse* gkResponse) {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int calling_pid = ipc->getCallingPid();
+    const int calling_uid = ipc->getCallingUid();
+    if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
+        return GK_ERROR;
+    }
 
-        // Make sure to clear any state from before factory reset as soon as a credential is
-        // enrolled (which may happen during device setup).
-        clear_state_if_needed();
+    // Make sure to clear any state from before factory reset as soon as a credential is
+    // enrolled (which may happen during device setup).
+    clear_state_if_needed();
 
-        // need a desired password to enroll
-        if (desiredPassword.size() == 0) return GK_ERROR;
+    // need a desired password to enroll
+    if (desiredPassword.size() == 0) return GK_ERROR;
 
-        if (!aidl_hw_device && !hw_device) {
-            LOG(ERROR) << "has no HAL to talk to";
-            return GK_ERROR;
-        }
+    if (!aidl_hw_device && !hw_device) {
+        LOG(ERROR) << "has no HAL to talk to";
+        return GK_ERROR;
+    }
 
-        android::hardware::hidl_vec<uint8_t> curPwdHandle;
-        android::hardware::hidl_vec<uint8_t> curPwd;
+    android::hardware::hidl_vec<uint8_t> curPwdHandle;
+    android::hardware::hidl_vec<uint8_t> curPwd;
 
-        if (currentPasswordHandle && currentPassword) {
-            if (hw_device) {
-                // Hidl Implementations expects passwordHandle to be in
-                // gatekeeper::password_handle_t format.
-                if (currentPasswordHandle->size() != sizeof(gatekeeper::password_handle_t)) {
-                    LOG(INFO) << "Password handle has wrong length";
-                    return GK_ERROR;
-                }
-            }
-            curPwdHandle.setToExternal(const_cast<uint8_t*>(currentPasswordHandle->data()),
-                                       currentPasswordHandle->size());
-            curPwd.setToExternal(const_cast<uint8_t*>(currentPassword->data()),
-                                 currentPassword->size());
-        }
-
-        android::hardware::hidl_vec<uint8_t> newPwd;
-        newPwd.setToExternal(const_cast<uint8_t*>(desiredPassword.data()), desiredPassword.size());
-
-        uint32_t hw_userId = adjust_userId(userId);
-        uint64_t secureUserId = 0;
-        if (aidl_hw_device) {
-            // AIDL gatekeeper service
-            AidlGatekeeperEnrollResp rsp;
-            auto result = aidl_hw_device->enroll(hw_userId, curPwdHandle, curPwd, newPwd, &rsp);
-            if (!result.isOk()) {
-                LOG(ERROR) << "enroll transaction failed";
+    if (currentPasswordHandle && currentPassword) {
+        if (hw_device) {
+            // Hidl Implementations expects passwordHandle to be in
+            // gatekeeper::password_handle_t format.
+            if (currentPasswordHandle->size() != sizeof(gatekeeper::password_handle_t)) {
+                LOG(INFO) << "Password handle has wrong length";
                 return GK_ERROR;
             }
-            if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
-                *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
-                secureUserId = static_cast<uint64_t>(rsp.secureUserId);
-            } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT &&
-                       rsp.timeoutMs > 0) {
-                *gkResponse = GKResponse::retry(rsp.timeoutMs);
-            } else {
-                *gkResponse = GKResponse::error();
-            }
-        } else if (hw_device) {
-            // HIDL gatekeeper service
-            Return<void> hwRes = hw_device->enroll(
+        }
+        curPwdHandle.setToExternal(const_cast<uint8_t*>(currentPasswordHandle->data()),
+                                   currentPasswordHandle->size());
+        curPwd.setToExternal(const_cast<uint8_t*>(currentPassword->data()),
+                             currentPassword->size());
+    }
+
+    android::hardware::hidl_vec<uint8_t> newPwd;
+    newPwd.setToExternal(const_cast<uint8_t*>(desiredPassword.data()), desiredPassword.size());
+
+    uint32_t hw_userId = adjust_userId(userId);
+    uint64_t secureUserId = 0;
+    if (aidl_hw_device) {
+        // AIDL gatekeeper service
+        AidlGatekeeperEnrollResp rsp;
+        auto result = aidl_hw_device->enroll(hw_userId, curPwdHandle, curPwd, newPwd, &rsp);
+        if (!result.isOk()) {
+            LOG(ERROR) << "enroll transaction failed";
+            return GK_ERROR;
+        }
+        if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
+            *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
+            secureUserId = static_cast<uint64_t>(rsp.secureUserId);
+        } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT && rsp.timeoutMs > 0) {
+            *gkResponse = GKResponse::retry(rsp.timeoutMs);
+        } else {
+            *gkResponse = GKResponse::error();
+        }
+    } else if (hw_device) {
+        // HIDL gatekeeper service
+        Return<void> hwRes = hw_device->enroll(
                 hw_userId, curPwdHandle, curPwd, newPwd,
                 [&gkResponse](const GatekeeperResponse& rsp) {
                     if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
@@ -247,110 +233,110 @@
                         *gkResponse = GKResponse::error();
                     }
                 });
-            if (!hwRes.isOk()) {
-                LOG(ERROR) << "enroll transaction failed";
+        if (!hwRes.isOk()) {
+            LOG(ERROR) << "enroll transaction failed";
+            return GK_ERROR;
+        }
+        if (gkResponse->response_code() == GKResponseCode::OK) {
+            if (gkResponse->payload().size() != sizeof(gatekeeper::password_handle_t)) {
+                LOG(ERROR) << "HAL returned password handle of invalid length "
+                           << gkResponse->payload().size();
                 return GK_ERROR;
             }
-            if (gkResponse->response_code() == GKResponseCode::OK) {
-                if (gkResponse->payload().size() != sizeof(gatekeeper::password_handle_t)) {
-                    LOG(ERROR) << "HAL returned password handle of invalid length "
-                               << gkResponse->payload().size();
-                    return GK_ERROR;
-                }
 
-                const gatekeeper::password_handle_t* handle =
+            const gatekeeper::password_handle_t* handle =
                     reinterpret_cast<const gatekeeper::password_handle_t*>(
-                        gkResponse->payload().data());
-                secureUserId = handle->user_id;
-            }
+                            gkResponse->payload().data());
+            secureUserId = handle->user_id;
         }
-
-        if (gkResponse->response_code() == GKResponseCode::OK && !gkResponse->should_reenroll()) {
-            store_sid(userId, secureUserId);
-
-            GKResponse verifyResponse;
-            // immediately verify this password so we don't ask the user to enter it again
-            // if they just created it.
-            auto status = verify(userId, gkResponse->payload(), desiredPassword, &verifyResponse);
-            if (!status.isOk() || verifyResponse.response_code() != GKResponseCode::OK) {
-                LOG(ERROR) << "Failed to verify password after enrolling";
-            }
-        }
-
-        return Status::ok();
     }
 
-    Status verify(int32_t userId, const ::std::vector<uint8_t>& enrolledPasswordHandle,
-                  const ::std::vector<uint8_t>& providedPassword, GKResponse* gkResponse) override {
-        return verifyChallenge(userId, 0 /* challenge */, enrolledPasswordHandle, providedPassword,
-                               gkResponse);
+    if (gkResponse->response_code() == GKResponseCode::OK && !gkResponse->should_reenroll()) {
+        store_sid(userId, secureUserId);
+
+        GKResponse verifyResponse;
+        // immediately verify this password so we don't ask the user to enter it again
+        // if they just created it.
+        auto status = verify(userId, gkResponse->payload(), desiredPassword, &verifyResponse);
+        if (!status.isOk() || verifyResponse.response_code() != GKResponseCode::OK) {
+            LOG(ERROR) << "Failed to verify password after enrolling";
+        }
     }
 
-    Status verifyChallenge(int32_t userId, int64_t challenge,
-                           const std::vector<uint8_t>& enrolledPasswordHandle,
-                           const std::vector<uint8_t>& providedPassword,
-                           GKResponse* gkResponse) override {
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int calling_pid = ipc->getCallingPid();
-        const int calling_uid = ipc->getCallingUid();
-        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
+    return Status::ok();
+}
+
+Status GateKeeperProxy::verify(int32_t userId, const ::std::vector<uint8_t>& enrolledPasswordHandle,
+                               const ::std::vector<uint8_t>& providedPassword,
+                               GKResponse* gkResponse) {
+    return verifyChallenge(userId, 0 /* challenge */, enrolledPasswordHandle, providedPassword,
+                           gkResponse);
+}
+
+Status GateKeeperProxy::verifyChallenge(int32_t userId, int64_t challenge,
+                                        const std::vector<uint8_t>& enrolledPasswordHandle,
+                                        const std::vector<uint8_t>& providedPassword,
+                                        GKResponse* gkResponse) {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int calling_pid = ipc->getCallingPid();
+    const int calling_uid = ipc->getCallingUid();
+    if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
+        return GK_ERROR;
+    }
+
+    // can't verify if we're missing either param
+    if (enrolledPasswordHandle.size() == 0 || providedPassword.size() == 0) return GK_ERROR;
+
+    if (!aidl_hw_device && !hw_device) {
+        LOG(ERROR) << "has no HAL to talk to";
+        return GK_ERROR;
+    }
+
+    if (hw_device) {
+        // Hidl Implementations expects passwordHandle to be in gatekeeper::password_handle_t
+        if (enrolledPasswordHandle.size() != sizeof(gatekeeper::password_handle_t)) {
+            LOG(INFO) << "Password handle has wrong length";
             return GK_ERROR;
         }
+    }
 
-        // can't verify if we're missing either param
-        if (enrolledPasswordHandle.size() == 0 || providedPassword.size() == 0) return GK_ERROR;
+    uint32_t hw_userId = adjust_userId(userId);
+    android::hardware::hidl_vec<uint8_t> curPwdHandle;
+    curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolledPasswordHandle.data()),
+                               enrolledPasswordHandle.size());
+    android::hardware::hidl_vec<uint8_t> enteredPwd;
+    enteredPwd.setToExternal(const_cast<uint8_t*>(providedPassword.data()),
+                             providedPassword.size());
 
-        if (!aidl_hw_device && !hw_device) {
-            LOG(ERROR) << "has no HAL to talk to";
+    uint64_t secureUserId = 0;
+    if (aidl_hw_device) {
+        // AIDL gatekeeper service
+        AidlGatekeeperVerifyResp rsp;
+        auto result = aidl_hw_device->verify(hw_userId, challenge, curPwdHandle, enteredPwd, &rsp);
+        if (!result.isOk()) {
+            LOG(ERROR) << "verify transaction failed";
             return GK_ERROR;
         }
-
-        if (hw_device) {
-            // Hidl Implementations expects passwordHandle to be in gatekeeper::password_handle_t
-            if (enrolledPasswordHandle.size() != sizeof(gatekeeper::password_handle_t)) {
-                LOG(INFO) << "Password handle has wrong length";
-                return GK_ERROR;
-            }
+        if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
+            secureUserId = rsp.hardwareAuthToken.userId;
+            // Serialize HardwareAuthToken to a vector as hw_auth_token_t.
+            *gkResponse = GKResponse::ok(
+                    authToken2AidlVec(rsp.hardwareAuthToken),
+                    rsp.statusCode == AidlIGatekeeper::STATUS_REENROLL /* reenroll */);
+        } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT) {
+            *gkResponse = GKResponse::retry(rsp.timeoutMs);
+        } else {
+            *gkResponse = GKResponse::error();
         }
-
-        uint32_t hw_userId = adjust_userId(userId);
-        android::hardware::hidl_vec<uint8_t> curPwdHandle;
-        curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolledPasswordHandle.data()),
-                                   enrolledPasswordHandle.size());
-        android::hardware::hidl_vec<uint8_t> enteredPwd;
-        enteredPwd.setToExternal(const_cast<uint8_t*>(providedPassword.data()),
-                                 providedPassword.size());
-
-        uint64_t secureUserId = 0;
-        if (aidl_hw_device) {
-            // AIDL gatekeeper service
-            AidlGatekeeperVerifyResp rsp;
-            auto result =
-                aidl_hw_device->verify(hw_userId, challenge, curPwdHandle, enteredPwd, &rsp);
-            if (!result.isOk()) {
-                LOG(ERROR) << "verify transaction failed";
-                return GK_ERROR;
-            }
-            if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
-                secureUserId = rsp.hardwareAuthToken.userId;
-                // Serialize HardwareAuthToken to a vector as hw_auth_token_t.
-                *gkResponse = GKResponse::ok(authToken2AidlVec(rsp.hardwareAuthToken),
-                                             rsp.statusCode ==
-                                                 AidlIGatekeeper::STATUS_REENROLL /* reenroll */);
-            } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT) {
-                *gkResponse = GKResponse::retry(rsp.timeoutMs);
-            } else {
-                *gkResponse = GKResponse::error();
-            }
-        } else if (hw_device) {
-            // HIDL gatekeeper service
-            Return<void> hwRes = hw_device->verify(
+    } else if (hw_device) {
+        // HIDL gatekeeper service
+        Return<void> hwRes = hw_device->verify(
                 hw_userId, challenge, curPwdHandle, enteredPwd,
                 [&gkResponse](const GatekeeperResponse& rsp) {
                     if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
                         *gkResponse = GKResponse::ok(
-                            {rsp.data.begin(), rsp.data.end()},
-                            rsp.code == GatekeeperStatusCode::STATUS_REENROLL /* reenroll */);
+                                {rsp.data.begin(), rsp.data.end()},
+                                rsp.code == GatekeeperStatusCode::STATUS_REENROLL /* reenroll */);
                     } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) {
                         *gkResponse = GKResponse::retry(rsp.timeout);
                     } else {
@@ -358,149 +344,110 @@
                     }
                 });
 
-            if (!hwRes.isOk()) {
-                LOG(ERROR) << "verify transaction failed";
-                return GK_ERROR;
-            }
-            const gatekeeper::password_handle_t* handle =
-                reinterpret_cast<const gatekeeper::password_handle_t*>(
-                    enrolledPasswordHandle.data());
-            secureUserId = handle->user_id;
+        if (!hwRes.isOk()) {
+            LOG(ERROR) << "verify transaction failed";
+            return GK_ERROR;
         }
+        const gatekeeper::password_handle_t* handle =
+                reinterpret_cast<const gatekeeper::password_handle_t*>(
+                        enrolledPasswordHandle.data());
+        secureUserId = handle->user_id;
+    }
 
-        if (gkResponse->response_code() == GKResponseCode::OK) {
-            if (gkResponse->payload().size() != 0) {
-                // try to connect to IKeystoreAuthorization AIDL service first.
-                AIBinder* authzAIBinder =
-                        AServiceManager_getService("android.security.authorization");
-                ::ndk::SpAIBinder authzBinder(authzAIBinder);
-                auto authzService = IKeystoreAuthorization::fromBinder(authzBinder);
-                if (authzService) {
-                    if (gkResponse->payload().size() != sizeof(hw_auth_token_t)) {
-                        LOG(ERROR) << "Incorrect size of AuthToken payload.";
-                        return GK_ERROR;
-                    }
-
-                    const hw_auth_token_t* hwAuthToken =
-                            reinterpret_cast<const hw_auth_token_t*>(gkResponse->payload().data());
-                    HardwareAuthToken authToken;
-
-                    authToken.timestamp.milliSeconds = betoh64(hwAuthToken->timestamp);
-                    authToken.challenge = hwAuthToken->challenge;
-                    authToken.userId = hwAuthToken->user_id;
-                    authToken.authenticatorId = hwAuthToken->authenticator_id;
-                    authToken.authenticatorType = static_cast<HardwareAuthenticatorType>(
-                            betoh32(hwAuthToken->authenticator_type));
-                    authToken.mac.assign(&hwAuthToken->hmac[0], &hwAuthToken->hmac[32]);
-                    auto result = authzService->addAuthToken(authToken);
-                    if (!result.isOk()) {
-                        LOG(ERROR) << "Failure in sending AuthToken to AuthorizationService.";
-                        return GK_ERROR;
-                    }
-                } else {
-                    LOG(ERROR) << "Cannot deliver auth token. Unable to communicate with "
-                                  "Keystore.";
+    if (gkResponse->response_code() == GKResponseCode::OK) {
+        if (gkResponse->payload().size() != 0) {
+            // try to connect to IKeystoreAuthorization AIDL service first.
+            AIBinder* authzAIBinder = AServiceManager_getService("android.security.authorization");
+            ::ndk::SpAIBinder authzBinder(authzAIBinder);
+            auto authzService = IKeystoreAuthorization::fromBinder(authzBinder);
+            if (authzService) {
+                if (gkResponse->payload().size() != sizeof(hw_auth_token_t)) {
+                    LOG(ERROR) << "Incorrect size of AuthToken payload.";
                     return GK_ERROR;
                 }
+
+                const hw_auth_token_t* hwAuthToken =
+                        reinterpret_cast<const hw_auth_token_t*>(gkResponse->payload().data());
+                HardwareAuthToken authToken;
+
+                authToken.timestamp.milliSeconds = betoh64(hwAuthToken->timestamp);
+                authToken.challenge = hwAuthToken->challenge;
+                authToken.userId = hwAuthToken->user_id;
+                authToken.authenticatorId = hwAuthToken->authenticator_id;
+                authToken.authenticatorType = static_cast<HardwareAuthenticatorType>(
+                        betoh32(hwAuthToken->authenticator_type));
+                authToken.mac.assign(&hwAuthToken->hmac[0], &hwAuthToken->hmac[32]);
+                auto result = authzService->addAuthToken(authToken);
+                if (!result.isOk()) {
+                    LOG(ERROR) << "Failure in sending AuthToken to AuthorizationService.";
+                    return GK_ERROR;
+                }
+            } else {
+                LOG(ERROR) << "Cannot deliver auth token. Unable to communicate with "
+                              "Keystore.";
+                return GK_ERROR;
             }
-
-            maybe_store_sid(userId, secureUserId);
         }
 
-        return Status::ok();
+        maybe_store_sid(userId, secureUserId);
     }
 
-    Status getSecureUserId(int32_t userId, int64_t* sid) override {
-        *sid = read_sid(userId);
-        return Status::ok();
-    }
-
-    Status clearSecureUserId(int32_t userId) override {
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int calling_pid = ipc->getCallingPid();
-        const int calling_uid = ipc->getCallingUid();
-        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
-            ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
-            return Status::ok();
-        }
-        clear_sid(userId);
-
-        uint32_t hw_userId = adjust_userId(userId);
-        if (aidl_hw_device) {
-            aidl_hw_device->deleteUser(hw_userId);
-        } else if (hw_device) {
-            hw_device->deleteUser(hw_userId, [](const GatekeeperResponse&) {});
-        }
-        return Status::ok();
-    }
-
-    Status reportDeviceSetupComplete() override {
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int calling_pid = ipc->getCallingPid();
-        const int calling_uid = ipc->getCallingUid();
-        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
-            ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
-            return Status::ok();
-        }
-
-        clear_state_if_needed();
-        return Status::ok();
-    }
-
-    status_t dump(int fd, const Vector<String16>&) override {
-        IPCThreadState* ipc = IPCThreadState::self();
-        const int pid = ipc->getCallingPid();
-        const int uid = ipc->getCallingUid();
-        if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
-            return PERMISSION_DENIED;
-        }
-
-        if (aidl_hw_device == nullptr && hw_device == nullptr) {
-            const char* result = "Device not available";
-            write(fd, result, strlen(result) + 1);
-        } else {
-            const char* result = "OK";
-            write(fd, result, strlen(result) + 1);
-        }
-
-        return OK;
-    }
-
-  private:
-    // AIDL gatekeeper service.
-    std::shared_ptr<AidlIGatekeeper> aidl_hw_device;
-    // HIDL gatekeeper service.
-    sp<IGatekeeper> hw_device;
-
-    bool clear_state_if_needed_done;
-    bool is_running_gsi;
-};
-}  // namespace android
-
-int main(int argc, char* argv[]) {
-    ALOGI("Starting gatekeeperd...");
-    if (argc < 2) {
-        ALOGE("A directory must be specified!");
-        return 1;
-    }
-    if (chdir(argv[1]) == -1) {
-        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
-        return 1;
-    }
-
-    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
-    android::sp<android::GateKeeperProxy> proxy = new android::GateKeeperProxy();
-    android::status_t ret =
-        sm->addService(android::String16("android.service.gatekeeper.IGateKeeperService"), proxy);
-    if (ret != android::OK) {
-        ALOGE("Couldn't register binder service!");
-        return -1;
-    }
-
-    /*
-     * We're the only thread in existence, so we're just going to process
-     * Binder transaction as a single-threaded program.
-     */
-    android::IPCThreadState::self()->joinThreadPool();
-    return 0;
+    return Status::ok();
 }
+
+Status GateKeeperProxy::getSecureUserId(int32_t userId, int64_t* sid) {
+    *sid = read_sid(userId);
+    return Status::ok();
+}
+
+Status GateKeeperProxy::clearSecureUserId(int32_t userId) {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int calling_pid = ipc->getCallingPid();
+    const int calling_uid = ipc->getCallingUid();
+    if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
+        ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
+        return Status::ok();
+    }
+    clear_sid(userId);
+
+    uint32_t hw_userId = adjust_userId(userId);
+    if (aidl_hw_device) {
+        aidl_hw_device->deleteUser(hw_userId);
+    } else if (hw_device) {
+        hw_device->deleteUser(hw_userId, [](const GatekeeperResponse&) {});
+    }
+    return Status::ok();
+}
+
+Status GateKeeperProxy::reportDeviceSetupComplete() {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int calling_pid = ipc->getCallingPid();
+    const int calling_uid = ipc->getCallingUid();
+    if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
+        ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
+        return Status::ok();
+    }
+
+    clear_state_if_needed();
+    return Status::ok();
+}
+
+status_t GateKeeperProxy::dump(int fd, const Vector<String16>&) {
+    IPCThreadState* ipc = IPCThreadState::self();
+    const int pid = ipc->getCallingPid();
+    const int uid = ipc->getCallingUid();
+    if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
+        return PERMISSION_DENIED;
+    }
+
+    if (aidl_hw_device == nullptr && hw_device == nullptr) {
+        const char* result = "Device not available";
+        write(fd, result, strlen(result) + 1);
+    } else {
+        const char* result = "OK";
+        write(fd, result, strlen(result) + 1);
+    }
+
+    return OK;
+}
+}  // namespace android
diff --git a/gatekeeperd/gatekeeperd.h b/gatekeeperd/gatekeeperd.h
new file mode 100644
index 0000000..29873da
--- /dev/null
+++ b/gatekeeperd/gatekeeperd.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2023 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 <aidl/android/hardware/gatekeeper/IGatekeeper.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+#include <android/service/gatekeeper/BnGateKeeperService.h>
+#include <gatekeeper/GateKeeperResponse.h>
+
+using ::android::hardware::gatekeeper::V1_0::IGatekeeper;
+using AidlIGatekeeper = ::aidl::android::hardware::gatekeeper::IGatekeeper;
+using ::android::binder::Status;
+using ::android::service::gatekeeper::BnGateKeeperService;
+using GKResponse = ::android::service::gatekeeper::GateKeeperResponse;
+
+namespace android {
+
+class GateKeeperProxy : public BnGateKeeperService {
+  public:
+    GateKeeperProxy();
+
+    virtual ~GateKeeperProxy() {}
+
+    void store_sid(uint32_t userId, uint64_t sid);
+
+    void clear_state_if_needed();
+
+    bool mark_cold_boot();
+
+    void maybe_store_sid(uint32_t userId, uint64_t sid);
+
+    uint64_t read_sid(uint32_t userId);
+
+    void clear_sid(uint32_t userId);
+
+    // This should only be called on userIds being passed to the GateKeeper HAL. It ensures that
+    // secure storage shared across a GSI image and a host image will not overlap.
+    uint32_t adjust_userId(uint32_t userId);
+
+#define GK_ERROR *gkResponse = GKResponse::error(), Status::ok()
+
+    Status enroll(int32_t userId, const std::optional<std::vector<uint8_t>>& currentPasswordHandle,
+                  const std::optional<std::vector<uint8_t>>& currentPassword,
+                  const std::vector<uint8_t>& desiredPassword, GKResponse* gkResponse) override;
+
+    Status verify(int32_t userId, const ::std::vector<uint8_t>& enrolledPasswordHandle,
+                  const ::std::vector<uint8_t>& providedPassword, GKResponse* gkResponse) override;
+
+    Status verifyChallenge(int32_t userId, int64_t challenge,
+                           const std::vector<uint8_t>& enrolledPasswordHandle,
+                           const std::vector<uint8_t>& providedPassword,
+                           GKResponse* gkResponse) override;
+
+    Status getSecureUserId(int32_t userId, int64_t* sid) override;
+
+    Status clearSecureUserId(int32_t userId) override;
+
+    Status reportDeviceSetupComplete() override;
+
+    status_t dump(int fd, const Vector<String16>&) override;
+
+  private:
+    // AIDL gatekeeper service.
+    std::shared_ptr<AidlIGatekeeper> aidl_hw_device;
+    // HIDL gatekeeper service.
+    sp<IGatekeeper> hw_device;
+
+    bool clear_state_if_needed_done;
+    bool is_running_gsi;
+};
+}  // namespace android
diff --git a/gatekeeperd/main.cpp b/gatekeeperd/main.cpp
new file mode 100644
index 0000000..a05584a
--- /dev/null
+++ b/gatekeeperd/main.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2023 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 <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+
+#include <log/log.h>
+
+#include "gatekeeperd.h"
+
+int main(int argc, char* argv[]) {
+    ALOGI("Starting gatekeeperd...");
+    if (argc < 2) {
+        ALOGE("A directory must be specified!");
+        return 1;
+    }
+    if (chdir(argv[1]) == -1) {
+        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
+        return 1;
+    }
+
+    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
+    android::sp<android::GateKeeperProxy> proxy = new android::GateKeeperProxy();
+    android::status_t ret = sm->addService(
+            android::String16("android.service.gatekeeper.IGateKeeperService"), proxy);
+    if (ret != android::OK) {
+        ALOGE("Couldn't register binder service!");
+        return -1;
+    }
+
+    /*
+     * We're the only thread in existence, so we're just going to process
+     * Binder transaction as a single-threaded program.
+     */
+    android::IPCThreadState::self()->joinThreadPool();
+    return 0;
+}
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 66e1e63..f68d65a 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -242,6 +242,8 @@
         value = BatteryHealth::DEAD;
     else if (status == BatteryMonitor::BH_FAILED)
         value = BatteryHealth::UNSPECIFIED_FAILURE;
+    else if (status == BatteryMonitor::BH_NOT_AVAILABLE)
+        value = BatteryHealth::NOT_AVAILABLE;
     else
         value = BatteryHealth::UNKNOWN;
 
diff --git a/healthd/include/healthd/BatteryMonitor.h b/healthd/include/healthd/BatteryMonitor.h
index 7b4f46c..a4c013b 100644
--- a/healthd/include/healthd/BatteryMonitor.h
+++ b/healthd/include/healthd/BatteryMonitor.h
@@ -62,6 +62,7 @@
         BH_MARGINAL,
         BH_NEEDS_REPLACEMENT,
         BH_FAILED,
+        BH_NOT_AVAILABLE,
     };
 
     BatteryMonitor();
diff --git a/init/service.cpp b/init/service.cpp
index 35beaad..c152081 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -140,9 +140,10 @@
 
 Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
                  const std::string& filename, const std::vector<std::string>& args)
-    : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, filename, args) {}
+    : Service(name, 0, std::nullopt, 0, {}, 0, "", subcontext_for_restart_commands, filename,
+              args) {}
 
-Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
+Service::Service(const std::string& name, unsigned flags, std::optional<uid_t> uid, gid_t gid,
                  const std::vector<gid_t>& supp_gids, int namespace_flags,
                  const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
                  const std::string& filename, const std::vector<std::string>& args)
@@ -153,7 +154,7 @@
       crash_count_(0),
       proc_attr_{.ioprio_class = IoSchedClass_NONE,
                  .ioprio_pri = 0,
-                 .uid = uid,
+                 .parsed_uid = uid,
                  .gid = gid,
                  .supp_gids = supp_gids,
                  .priority = 0},
@@ -205,9 +206,9 @@
         int max_processes = 0;
         int r;
         if (signal == SIGTERM) {
-            r = killProcessGroupOnce(proc_attr_.uid, pid_, signal, &max_processes);
+            r = killProcessGroupOnce(uid(), pid_, signal, &max_processes);
         } else {
-            r = killProcessGroup(proc_attr_.uid, pid_, signal, &max_processes);
+            r = killProcessGroup(uid(), pid_, signal, &max_processes);
         }
 
         if (report_oneshot && max_processes > 0) {
@@ -228,7 +229,7 @@
 
 void Service::SetProcessAttributesAndCaps(InterprocessFifo setsid_finished) {
     // Keep capabilites on uid change.
-    if (capabilities_ && proc_attr_.uid) {
+    if (capabilities_ && uid()) {
         // If Android is running in a container, some securebits might already
         // be locked, so don't change those.
         unsigned long securebits = prctl(PR_GET_SECUREBITS);
@@ -255,7 +256,7 @@
         if (!SetCapsForExec(*capabilities_)) {
             LOG(FATAL) << "cannot set capabilities for " << name_;
         }
-    } else if (proc_attr_.uid) {
+    } else if (uid()) {
         // Inheritable caps can be non-zero when running in a container.
         if (!DropInheritableCaps()) {
             LOG(FATAL) << "cannot drop inheritable caps for " << name_;
@@ -434,8 +435,8 @@
     flags_ |= SVC_EXEC;
     is_exec_service_running_ = true;
 
-    LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
-              << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
+    LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid() << " gid "
+              << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
               << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
 
     reboot_on_failure.Disable();
@@ -475,13 +476,13 @@
 // Configures the memory cgroup properties for the service.
 void Service::ConfigureMemcg() {
     if (swappiness_ != -1) {
-        if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
+        if (!setProcessGroupSwappiness(uid(), pid_, swappiness_)) {
             PLOG(ERROR) << "setProcessGroupSwappiness failed";
         }
     }
 
     if (soft_limit_in_bytes_ != -1) {
-        if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
+        if (!setProcessGroupSoftLimit(uid(), pid_, soft_limit_in_bytes_)) {
             PLOG(ERROR) << "setProcessGroupSoftLimit failed";
         }
     }
@@ -508,7 +509,7 @@
     }
 
     if (computed_limit_in_bytes != size_t(-1)) {
-        if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
+        if (!setProcessGroupLimit(uid(), pid_, computed_limit_in_bytes)) {
             PLOG(ERROR) << "setProcessGroupLimit failed";
         }
     }
@@ -705,21 +706,20 @@
     if (CgroupsAvailable()) {
         bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
                          limit_percent_ != -1 || !limit_property_.empty();
-        errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
+        errno = -createProcessGroup(uid(), pid_, use_memcg);
         if (errno != 0) {
             Result<void> result = cgroups_activated.Write(kActivatingCgroupsFailed);
             if (!result.ok()) {
                 return Error() << "Sending notification failed: " << result.error();
             }
-            return Error() << "createProcessGroup(" << proc_attr_.uid << ", " << pid_ << ", "
-                           << use_memcg << ") failed for service '" << name_
-                           << "': " << strerror(errno);
+            return Error() << "createProcessGroup(" << uid() << ", " << pid_ << ", " << use_memcg
+                           << ") failed for service '" << name_ << "': " << strerror(errno);
         }
 
         // When the blkio controller is mounted in the v1 hierarchy, NormalIoPriority is
         // the default (/dev/blkio). When the blkio controller is mounted in the v2 hierarchy, the
         // NormalIoPriority profile has to be applied explicitly.
-        SetProcessProfiles(proc_attr_.uid, pid_, {"NormalIoPriority"});
+        SetProcessProfiles(uid(), pid_, {"NormalIoPriority"});
 
         if (use_memcg) {
             ConfigureMemcg();
@@ -727,7 +727,7 @@
     }
 
     if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
-        LmkdRegister(name_, proc_attr_.uid, pid_, oom_score_adjust_);
+        LmkdRegister(name_, uid(), pid_, oom_score_adjust_);
     }
 
     if (Result<void> result = cgroups_activated.Write(kCgroupsActivated); !result.ok()) {
diff --git a/init/service.h b/init/service.h
index 3ef8902..ce7c0da 100644
--- a/init/service.h
+++ b/init/service.h
@@ -71,7 +71,7 @@
     Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
             const std::string& filename, const std::vector<std::string>& args);
 
-    Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
+    Service(const std::string& name, unsigned flags, std::optional<uid_t> uid, gid_t gid,
             const std::vector<gid_t>& supp_gids, int namespace_flags, const std::string& seclabel,
             Subcontext* subcontext_for_restart_commands, const std::string& filename,
             const std::vector<std::string>& args);
@@ -115,7 +115,7 @@
     pid_t pid() const { return pid_; }
     android::base::boot_clock::time_point time_started() const { return time_started_; }
     int crash_count() const { return crash_count_; }
-    uid_t uid() const { return proc_attr_.uid; }
+    uid_t uid() const { return proc_attr_.uid(); }
     gid_t gid() const { return proc_attr_.gid; }
     int namespace_flags() const { return namespaces_.flags; }
     const std::vector<gid_t>& supp_gids() const { return proc_attr_.supp_gids; }
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index 3563084..d89664c 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -534,7 +534,7 @@
     if (!uid.ok()) {
         return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
     }
-    service_->proc_attr_.uid = *uid;
+    service_->proc_attr_.parsed_uid = *uid;
     return {};
 }
 
@@ -677,6 +677,11 @@
         return {};
     }
 
+    if (service_->proc_attr_.parsed_uid == std::nullopt) {
+        LOG(WARNING) << "No user specified for service '" << service_->name()
+                     << "'. Defaults to root.";
+    }
+
     if (interface_inheritance_hierarchy_) {
         if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
                     service_->interfaces(), *interface_inheritance_hierarchy_);
diff --git a/init/service_utils.cpp b/init/service_utils.cpp
index 7004d8d..0e19bcc 100644
--- a/init/service_utils.cpp
+++ b/init/service_utils.cpp
@@ -271,8 +271,8 @@
     if (setgroups(attr.supp_gids.size(), const_cast<gid_t*>(&attr.supp_gids[0])) != 0) {
         return ErrnoError() << "setgroups failed";
     }
-    if (attr.uid) {
-        if (setuid(attr.uid) != 0) {
+    if (attr.uid()) {
+        if (setuid(attr.uid()) != 0) {
             return ErrnoError() << "setuid failed";
         }
     }
diff --git a/init/service_utils.h b/init/service_utils.h
index d4143aa..27ec450 100644
--- a/init/service_utils.h
+++ b/init/service_utils.h
@@ -91,11 +91,13 @@
     IoSchedClass ioprio_class;
     int ioprio_pri;
     std::vector<std::pair<int, rlimit>> rlimits;
-    uid_t uid;
+    std::optional<uid_t> parsed_uid;
     gid_t gid;
     std::vector<gid_t> supp_gids;
     int priority;
     bool stdio_to_kmsg;
+
+    uid_t uid() const { return parsed_uid.value_or(0); }
 };
 
 inline bool RequiresConsole(const ProcessAttributes& attr) {
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index a021594..e294260 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -216,7 +216,6 @@
 static int RemoveProcessGroup(const char* cgroup, uid_t uid, int pid, unsigned int retries) {
     int ret = 0;
     auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
-    auto uid_path = ConvertUidToPath(cgroup, uid);
 
     while (retries--) {
         ret = rmdir(uid_pid_path.c_str());
diff --git a/storaged/Android.bp b/storaged/Android.bp
index c3447d2..04f5d79 100644
--- a/storaged/Android.bp
+++ b/storaged/Android.bp
@@ -136,3 +136,27 @@
     ],
     path: "binder",
 }
+
+cc_fuzz {
+    name: "storaged_service_fuzzer",
+    defaults: [
+        "storaged_defaults",
+        "service_fuzzer_defaults",
+    ],
+    srcs: ["tests/fuzzers/storaged_service_fuzzer.cpp"],
+    static_libs: [
+        "libstoraged",
+    ],
+}
+
+cc_fuzz {
+    name: "storaged_private_service_fuzzer",
+    defaults: [
+        "storaged_defaults",
+        "service_fuzzer_defaults",
+    ],
+    srcs: ["tests/fuzzers/storaged_private_service_fuzzer.cpp"],
+    static_libs: [
+        "libstoraged",
+    ],
+}
\ No newline at end of file
diff --git a/storaged/include/storaged_service.h b/storaged/include/storaged_service.h
index 7ec6864..bf7af80 100644
--- a/storaged/include/storaged_service.h
+++ b/storaged/include/storaged_service.h
@@ -28,6 +28,7 @@
 using namespace android::os;
 using namespace android::os::storaged;
 
+namespace android {
 class StoragedService : public BinderService<StoragedService>, public BnStoraged {
 private:
     void dumpUidRecordsDebug(int fd, const vector<struct uid_record>& entries);
@@ -53,4 +54,5 @@
 
 sp<IStoragedPrivate> get_storaged_pri_service();
 
+}  // namespace android
 #endif /* _STORAGED_SERVICE_H_ */
\ No newline at end of file
diff --git a/storaged/storaged_service.cpp b/storaged/storaged_service.cpp
index 45f1d4d..00d36d7 100644
--- a/storaged/storaged_service.cpp
+++ b/storaged/storaged_service.cpp
@@ -38,6 +38,7 @@
 
 extern sp<storaged_t> storaged_sp;
 
+namespace android {
 status_t StoragedService::start() {
     return BinderService<StoragedService>::publish();
 }
@@ -218,3 +219,4 @@
 
     return interface_cast<IStoragedPrivate>(binder);
 }
+}  // namespace android
\ No newline at end of file
diff --git a/storaged/tests/fuzzers/storaged_private_service_fuzzer.cpp b/storaged/tests/fuzzers/storaged_private_service_fuzzer.cpp
new file mode 100644
index 0000000..82eb796
--- /dev/null
+++ b/storaged/tests/fuzzers/storaged_private_service_fuzzer.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 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 <fuzzbinder/libbinder_driver.h>
+
+#include <storaged.h>
+#include <storaged_service.h>
+
+sp<storaged_t> storaged_sp;
+
+extern "C" int LLVMFuzzerInitialize(int /**argc*/, char /****argv*/) {
+    storaged_sp = new storaged_t();
+    storaged_sp->init();
+    return 0;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    auto storagedPrivateService = new StoragedPrivateService();
+    fuzzService(storagedPrivateService, FuzzedDataProvider(data, size));
+    return 0;
+}
\ No newline at end of file
diff --git a/storaged/tests/fuzzers/storaged_service_fuzzer.cpp b/storaged/tests/fuzzers/storaged_service_fuzzer.cpp
new file mode 100644
index 0000000..d11ecc3
--- /dev/null
+++ b/storaged/tests/fuzzers/storaged_service_fuzzer.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 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 <fuzzbinder/libbinder_driver.h>
+
+#include <storaged.h>
+#include <storaged_service.h>
+
+sp<storaged_t> storaged_sp;
+
+extern "C" int LLVMFuzzerInitialize(int /**argc*/, char /****argv*/) {
+    storaged_sp = new storaged_t();
+    storaged_sp->init();
+    return 0;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    auto storagedService = new StoragedService();
+    fuzzService(storagedService, FuzzedDataProvider(data, size));
+    return 0;
+}
\ No newline at end of file