Convert gsid to use the dynamic AIDL service infrastructure

Replace the original on demand start mechanism with the new dynamic
AIDL service infrastructure to resolve a possible race condition.

Bug: 149130673
Test: gsi_tool status

Change-Id: I141475b56191eb82efe222bf7522350fc66a7dac
diff --git a/Android.bp b/Android.bp
index f96ec25..174567b 100644
--- a/Android.bp
+++ b/Android.bp
@@ -125,7 +125,6 @@
     srcs: [
         "aidl/android/gsi/AvbPublicKey.aidl",
         "aidl/android/gsi/GsiProgress.aidl",
-        "aidl/android/gsi/IGsid.aidl",
         "aidl/android/gsi/IGsiService.aidl",
         "aidl/android/gsi/IGsiServiceCallback.aidl",
         "aidl/android/gsi/IImageService.aidl",
diff --git a/aidl/android/gsi/IGsid.aidl b/aidl/android/gsi/IGsid.aidl
deleted file mode 100644
index 0c1a7b2..0000000
--- a/aidl/android/gsi/IGsid.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-package android.gsi;
-
-import android.gsi.IGsiService;
-
-/** {@hide} */
-interface IGsid {
-    // Acquire an IGsiService client. gsid automatically shuts down when the
-    // last client is dropped. To start the daemon:
-    //
-    //  1. Check if the "init.svc.gsid" property is "running". If not, continue.
-    //  2. Set the "ctl.start" property to "gsid".
-    //  3. Wait for "init.svc.gsid" to be "running".
-    IGsiService getClient();
-}
diff --git a/daemon.cpp b/daemon.cpp
index 782d2ed..ba05eb6 100644
--- a/daemon.cpp
+++ b/daemon.cpp
@@ -62,7 +62,7 @@
         }
     }
 
-    android::gsi::Gsid::Register();
+    android::gsi::GsiService::Register();
     {
         sp<ProcessState> ps(ProcessState::self());
         ps->startThreadPool();
diff --git a/gsi_service.cpp b/gsi_service.cpp
index 77db54b..ab2339b 100644
--- a/gsi_service.cpp
+++ b/gsi_service.cpp
@@ -38,6 +38,7 @@
 #include <android-base/strings.h>
 #include <android/gsi/BnImageService.h>
 #include <android/gsi/IGsiService.h>
+#include <binder/LazyServiceRegistrar.h>
 #include <ext4_utils/ext4_utils.h>
 #include <fs_mgr.h>
 #include <libavb/libavb.h>
@@ -63,53 +64,30 @@
 using android::base::unique_fd;
 using android::base::WriteStringToFd;
 using android::base::WriteStringToFile;
+using android::binder::LazyServiceRegistrar;
 using android::dm::DeviceMapper;
 
 static std::mutex sInstanceLock;
 
-android::wp<GsiService> GsiService::sInstance;
-
 // Default userdata image size.
 static constexpr int64_t kDefaultUserdataSize = int64_t(2) * 1024 * 1024 * 1024;
 
 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst);
 
-void Gsid::Register() {
-    auto ret = android::BinderService<Gsid>::publish();
-    if (ret != android::OK) {
-        LOG(FATAL) << "Could not register gsi service: " << ret;
-    }
-}
-
-binder::Status Gsid::getClient(android::sp<IGsiService>* _aidl_return) {
-    *_aidl_return = GsiService::Get(this);
-    return binder::Status::ok();
-}
-
-GsiService::GsiService(Gsid* parent) : parent_(parent) {
+GsiService::GsiService() {
     progress_ = {};
 }
 
-GsiService::~GsiService() {
-    std::lock_guard<std::mutex> guard(sInstanceLock);
+void GsiService::Register() {
+    auto lazyRegistrar = LazyServiceRegistrar::getInstance();
+    android::sp<GsiService> service = new GsiService();
+    auto ret = lazyRegistrar.registerService(service, kGsiServiceName);
 
-    if (sInstance == this) {
-        // No more consumers, gracefully shut down gsid.
-        exit(0);
+    if (ret != android::OK) {
+        LOG(FATAL) << "Could not register gsi service: " << ret;
     }
 }
 
-android::sp<IGsiService> GsiService::Get(Gsid* parent) {
-    std::lock_guard<std::mutex> guard(sInstanceLock);
-
-    android::sp<GsiService> service = sInstance.promote();
-    if (!service) {
-        service = new GsiService(parent);
-        sInstance = service.get();
-    }
-    return service.get();
-}
-
 #define ENFORCE_SYSTEM                      \
     do {                                    \
         binder::Status status = CheckUid(); \
@@ -143,7 +121,7 @@
 
 binder::Status GsiService::openInstall(const std::string& install_dir, int* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
     if (IsGsiRunning()) {
         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
         return binder::Status::ok();
@@ -165,7 +143,7 @@
 
 binder::Status GsiService::closeInstall(int* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
     auto dsu_slot = GetDsuSlot(install_dir_);
     std::string file = GetCompleteIndication(dsu_slot);
     if (!WriteStringToFile("OK", file)) {
@@ -179,7 +157,7 @@
 binder::Status GsiService::createPartition(const ::std::string& name, int64_t size, bool readOnly,
                                            int32_t* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (install_dir_.empty()) {
         PLOG(ERROR) << "open is required for createPartition";
@@ -215,7 +193,7 @@
 binder::Status GsiService::commitGsiChunkFromStream(const android::os::ParcelFileDescriptor& stream,
                                                     int64_t bytes, bool* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (!installer_) {
         *_aidl_return = false;
@@ -259,7 +237,7 @@
 
 binder::Status GsiService::commitGsiChunkFromAshmem(int64_t bytes, bool* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (!installer_) {
         *_aidl_return = false;
@@ -293,7 +271,7 @@
 }
 
 binder::Status GsiService::enableGsi(bool one_shot, const std::string& dsuSlot, int* _aidl_return) {
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (!WriteStringToFile(dsuSlot, kDsuActiveFile)) {
         PLOG(ERROR) << "write failed: " << GetDsuSlot(install_dir_);
@@ -321,7 +299,7 @@
 
 binder::Status GsiService::isGsiEnabled(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
     std::string boot_key;
     if (!GetInstallStatus(&boot_key)) {
         *_aidl_return = false;
@@ -344,7 +322,7 @@
 
 binder::Status GsiService::removeGsi(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     std::string install_dir = GetActiveInstalledImageDir();
     if (IsGsiRunning()) {
@@ -359,7 +337,7 @@
 
 binder::Status GsiService::disableGsi(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = DisableGsiInstall();
     return binder::Status::ok();
@@ -367,7 +345,7 @@
 
 binder::Status GsiService::isGsiRunning(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = IsGsiRunning();
     return binder::Status::ok();
@@ -375,7 +353,7 @@
 
 binder::Status GsiService::isGsiInstalled(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = IsGsiInstalled();
     return binder::Status::ok();
@@ -383,7 +361,7 @@
 
 binder::Status GsiService::isGsiInstallInProgress(bool* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = !!installer_;
     return binder::Status::ok();
@@ -392,7 +370,7 @@
 binder::Status GsiService::cancelGsiInstall(bool* _aidl_return) {
     ENFORCE_SYSTEM;
     should_abort_ = true;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     should_abort_ = false;
     installer_ = nullptr;
@@ -403,7 +381,7 @@
 
 binder::Status GsiService::getInstalledGsiImageDir(std::string* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = GetActiveInstalledImageDir();
     return binder::Status::ok();
@@ -411,7 +389,7 @@
 
 binder::Status GsiService::getActiveDsuSlot(std::string* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     *_aidl_return = GetActiveDsuSlot();
     return binder::Status::ok();
@@ -419,14 +397,14 @@
 
 binder::Status GsiService::getInstalledDsuSlots(std::vector<std::string>* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
     *_aidl_return = GetInstalledDsuSlots();
     return binder::Status::ok();
 }
 
 binder::Status GsiService::zeroPartition(const std::string& name, int* _aidl_return) {
     ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (IsGsiRunning() || !IsGsiInstalled()) {
         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
@@ -478,7 +456,7 @@
 
 binder::Status GsiService::getAvbPublicKey(AvbPublicKey* dst, int32_t* _aidl_return) {
     ENFORCE_SYSTEM;
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(lock_);
 
     if (!installer_) {
         *_aidl_return = INSTALL_ERROR_GENERIC;
@@ -548,13 +526,12 @@
     bool CheckUid();
 
     android::sp<GsiService> service_;
-    android::sp<Gsid> parent_;
     std::unique_ptr<ImageManager> impl_;
     uid_t uid_;
 };
 
 ImageService::ImageService(GsiService* service, std::unique_ptr<ImageManager>&& impl, uid_t uid)
-    : service_(service), parent_(service->parent()), impl_(std::move(impl)), uid_(uid) {}
+    : service_(service), impl_(std::move(impl)), uid_(uid) {}
 
 binder::Status ImageService::getAllBackingImages(std::vector<std::string>* _aidl_return) {
     *_aidl_return = impl_->GetAllBackingImages();
@@ -565,7 +542,7 @@
                                                 const sp<IProgressCallback>& on_progress) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     std::function<bool(uint64_t, uint64_t)> callback;
     if (on_progress) {
@@ -590,7 +567,7 @@
 binder::Status ImageService::deleteBackingImage(const std::string& name) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     if (!impl_->DeleteBackingImage(name)) {
         return BinderError("Failed to delete");
@@ -602,7 +579,7 @@
                                             MappedImage* mapping) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     if (!impl_->MapImageDevice(name, std::chrono::milliseconds(timeout_ms), &mapping->path)) {
         return BinderError("Failed to map");
@@ -613,7 +590,7 @@
 binder::Status ImageService::unmapImageDevice(const std::string& name) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     if (!impl_->UnmapImageDevice(name)) {
         return BinderError("Failed to unmap");
@@ -624,7 +601,7 @@
 binder::Status ImageService::backingImageExists(const std::string& name, bool* _aidl_return) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     *_aidl_return = impl_->BackingImageExists(name);
     return binder::Status::ok();
@@ -633,7 +610,7 @@
 binder::Status ImageService::isImageMapped(const std::string& name, bool* _aidl_return) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     *_aidl_return = impl_->IsImageMapped(name);
     return binder::Status::ok();
@@ -643,7 +620,7 @@
                                              int32_t* _aidl_return) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     std::string device_path;
     std::unique_ptr<MappedDevice> mapped_device;
@@ -682,7 +659,7 @@
 binder::Status ImageService::zeroFillNewImage(const std::string& name, int64_t bytes) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
 
     if (bytes < 0) {
         return BinderError("Cannot use negative values");
@@ -697,7 +674,7 @@
 binder::Status ImageService::removeAllImages() {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
     if (!impl_->RemoveAllImages()) {
         return BinderError("Failed to remove all images");
     }
@@ -707,7 +684,7 @@
 binder::Status ImageService::removeDisabledImages() {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
     if (!impl_->RemoveDisabledImages()) {
         return BinderError("Failed to remove disabled images");
     }
@@ -717,7 +694,7 @@
 binder::Status ImageService::getMappedImageDevice(const std::string& name, std::string* device) {
     if (!CheckUid()) return UidSecurityError();
 
-    std::lock_guard<std::mutex> guard(parent_->lock());
+    std::lock_guard<std::mutex> guard(service_->lock());
     if (!impl_->GetMappedImageDevice(name, device)) {
         *device = "";
     }
diff --git a/gsi_service.h b/gsi_service.h
index 0f9880c..229db36 100644
--- a/gsi_service.h
+++ b/gsi_service.h
@@ -24,7 +24,6 @@
 
 #include <android-base/unique_fd.h>
 #include <android/gsi/BnGsiService.h>
-#include <android/gsi/BnGsid.h>
 #include <binder/BinderService.h>
 #include <libfiemap/split_fiemap_writer.h>
 #include <liblp/builder.h>
@@ -35,27 +34,9 @@
 namespace android {
 namespace gsi {
 
-class Gsid : public BinderService<Gsid>, public BnGsid {
-  public:
-    static void Register();
-    static char const* getServiceName() { return kGsiServiceName; }
-
-    binder::Status getClient(android::sp<IGsiService>* _aidl_return) override;
-
-  private:
-    friend class GsiService;
-    friend class ImageService;
-
-    std::mutex& lock() { return lock_; }
-
-    std::mutex lock_;
-};
-
 class GsiService : public BinderService<GsiService>, public BnGsiService {
   public:
-    ~GsiService() override;
-
-    static android::sp<IGsiService> Get(Gsid* parent);
+    static void Register();
 
     binder::Status openInstall(const std::string& install_dir, int* _aidl_return) override;
     binder::Status closeInstall(int32_t* _aidl_return) override;
@@ -95,7 +76,6 @@
     // Helper methods for GsiInstaller.
     static bool RemoveGsiFiles(const std::string& install_dir);
     bool should_abort() const { return should_abort_; }
-    Gsid* parent() const { return parent_.get(); }
 
     static void RunStartupTasks();
     static std::string GetInstalledImageDir();
@@ -105,7 +85,9 @@
     static std::vector<std::string> GetInstalledDsuSlots();
 
   private:
-    GsiService(Gsid* parent);
+    friend class ImageService;
+
+    GsiService();
     static int ValidateInstallParams(std::string& install_dir);
     bool DisableGsiInstall();
     int ReenableGsi(bool one_shot);
@@ -122,9 +104,9 @@
     static android::wp<GsiService> sInstance;
 
     std::string install_dir_ = {};
-    android::sp<Gsid> parent_;
     std::unique_ptr<PartitionInstaller> installer_;
-
+    std::mutex lock_;
+    std::mutex& lock() { return lock_; }
     // These are initialized or set in StartInstall().
     std::atomic<bool> should_abort_ = false;
 
diff --git a/gsi_tool.cpp b/gsi_tool.cpp
index b059947..4c246cc 100644
--- a/gsi_tool.cpp
+++ b/gsi_tool.cpp
@@ -35,7 +35,6 @@
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <android/gsi/IGsiService.h>
-#include <android/gsi/IGsid.h>
 #include <binder/IServiceManager.h>
 #include <cutils/android_reboot.h>
 #include <libgsi/libgsi.h>
diff --git a/gsid.rc b/gsid.rc
index 1640a73..6b9663f 100644
--- a/gsid.rc
+++ b/gsid.rc
@@ -1,4 +1,5 @@
 service gsid /system/bin/gsid
+    interface aidl gsiservice
     oneshot
     disabled
     user root
diff --git a/libgsid.cpp b/libgsid.cpp
index cfddb60..b42833c 100644
--- a/libgsid.cpp
+++ b/libgsid.cpp
@@ -17,54 +17,23 @@
 #include <android-base/logging.h>
 #include <android-base/properties.h>
 #include <android/gsi/IGsiService.h>
-#include <android/gsi/IGsid.h>
 #include <binder/IServiceManager.h>
 #include <libgsi/libgsi.h>
 
 namespace android {
 namespace gsi {
 
-using namespace std::chrono_literals;
 using android::sp;
 
-static sp<IGsid> GetGsid() {
-    if (android::base::GetProperty("init.svc.gsid", "") != "running") {
-        if (!android::base::SetProperty("ctl.start", "gsid") ||
-            !android::base::WaitForProperty("init.svc.gsid", "running", 5s)) {
-            LOG(ERROR) << "Unable to start gsid";
-            return nullptr;
-        }
-    }
-
-    static const int kSleepTimeMs = 50;
-    static const int kTotalWaitTimeMs = 3000;
-    for (int i = 0; i < kTotalWaitTimeMs / kSleepTimeMs; i++) {
-        auto sm = android::defaultServiceManager();
-        auto name = android::String16(kGsiServiceName);
-        android::sp<android::IBinder> res = sm->checkService(name);
-        if (res) {
-            return android::interface_cast<IGsid>(res);
-        }
-        usleep(kSleepTimeMs * 1000);
-    }
-
-    LOG(ERROR) << "Timed out trying to start gsid";
-    return nullptr;
-}
-
 sp<IGsiService> GetGsiService() {
-    auto gsid = GetGsid();
-    if (!gsid) {
-        return nullptr;
+    auto sm = android::defaultServiceManager();
+    auto name = android::String16(kGsiServiceName);
+    android::sp<android::IBinder> res = sm->waitForService(name);
+    if (res) {
+        return android::interface_cast<IGsiService>(res);
     }
-
-    sp<IGsiService> service;
-    auto status = gsid->getClient(&service);
-    if (!status.isOk() || !service) {
-        LOG(ERROR) << "Error acquiring IGsid: " << status.exceptionMessage().string();
-        return nullptr;
-    }
-    return service;
+    LOG(ERROR) << "Unable to GetGsiService";
+    return nullptr;
 }
 
 }  // namespace gsi