Migrate sensors VTS to use libui am: 02b1d722f9

Original change: https://android-review.googlesource.com/c/platform/hardware/interfaces/+/3432193

Change-Id: I65cc9348e48a4220bdea0d633d1e6719330fd501
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
index 56aa690..3303ff9 100644
--- a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
+++ b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
@@ -2282,7 +2282,8 @@
      *
      * <p>Whether this camera device can support identical set of stream combinations
      * involving HEIC image format, compared to the
-     * <a href="https://developer.android.com/reference/android/hardware/camera2/CameraDevice.html#legacy-level-guaranteed-configurations">table of combinations</a> involving JPEG image format required for the device's hardware
+     * <a href="https://developer.android.com/reference/android/hardware/camera2/CameraDevice#legacy-level-guaranteed-configurations">table of combinations</a>
+     * involving JPEG image format required for the device's hardware
      * level and capabilities.</p>
      */
     ANDROID_HEIC_INFO_SUPPORTED = CameraMetadataSectionStart.ANDROID_HEIC_INFO_START,
diff --git a/health/aidl/default/Health.cpp b/health/aidl/default/Health.cpp
index f401643..f485e54 100644
--- a/health/aidl/default/Health.cpp
+++ b/health/aidl/default/Health.cpp
@@ -36,6 +36,11 @@
     LinkedCallback* linked = reinterpret_cast<LinkedCallback*>(cookie);
     linked->OnCallbackDied();
 }
+// Delete the owned cookie.
+void onCallbackUnlinked(void* cookie) {
+    LinkedCallback* linked = reinterpret_cast<LinkedCallback*>(cookie);
+    delete linked;
+}
 }  // namespace
 
 /*
@@ -57,6 +62,7 @@
     : instance_name_(instance_name),
       healthd_config_(std::move(config)),
       death_recipient_(AIBinder_DeathRecipient_new(&OnCallbackDiedWrapped)) {
+    AIBinder_DeathRecipient_setOnUnlinked(death_recipient_.get(), onCallbackUnlinked);
     battery_monitor_.init(healthd_config_.get());
 }
 
@@ -272,7 +278,11 @@
 
     {
         std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
-        callbacks_.emplace_back(LinkedCallback::Make(ref<Health>(), callback));
+        LinkedCallback* linked_callback_result = LinkedCallback::Make(ref<Health>(), callback);
+        if (!linked_callback_result) {
+            return ndk::ScopedAStatus::fromStatus(STATUS_UNEXPECTED_NULL);
+        }
+        callbacks_[linked_callback_result] = callback;
         // unlock
     }
 
@@ -298,12 +308,24 @@
 
     std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
 
-    auto matches = [callback](const auto& linked) {
-        return linked->callback()->asBinder() == callback->asBinder();  // compares binder object
+    auto matches = [callback](const auto& cb) {
+        return cb->asBinder() == callback->asBinder();  // compares binder object
     };
-    auto it = std::remove_if(callbacks_.begin(), callbacks_.end(), matches);
-    bool removed = (it != callbacks_.end());
-    callbacks_.erase(it, callbacks_.end());  // calls unlinkToDeath on deleted callbacks.
+    bool removed = false;
+    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+        if (it->second->asBinder() == callback->asBinder()) {
+            auto status = AIBinder_unlinkToDeath(callback->asBinder().get(), death_recipient_.get(),
+                                                 reinterpret_cast<void*>(it->first));
+            if (status != STATUS_OK && status != STATUS_DEAD_OBJECT) {
+                LOG(WARNING) << __func__
+                             << "Cannot unlink to death: " << ::android::statusToString(status);
+            }
+            it = callbacks_.erase(it);
+            removed = true;
+        } else {
+            it++;
+        }
+    }
     return removed ? ndk::ScopedAStatus::ok()
                    : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
 }
@@ -331,13 +353,20 @@
 void Health::OnHealthInfoChanged(const HealthInfo& health_info) {
     // Notify all callbacks
     std::unique_lock<decltype(callbacks_lock_)> lock(callbacks_lock_);
-    // is_dead notifies a callback and return true if it is dead.
-    auto is_dead = [&](const auto& linked) {
-        auto res = linked->callback()->healthInfoChanged(health_info);
-        return IsDeadObjectLogged(res);
-    };
-    auto it = std::remove_if(callbacks_.begin(), callbacks_.end(), is_dead);
-    callbacks_.erase(it, callbacks_.end());  // calls unlinkToDeath on deleted callbacks.
+    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+        auto res = it->second->healthInfoChanged(health_info);
+        if (IsDeadObjectLogged(res)) {
+            // if it's dead, remove it
+            it = callbacks_.erase(it);
+        } else {
+            it++;
+            if (!res.isOk()) {
+                LOG(DEBUG)
+                        << "Cannot call healthInfoChanged:" << res.getDescription()
+                        << ". Do nothing here if callback is dead as it will be cleaned up later.";
+            }
+        }
+    }
     lock.unlock();
 
     // Let HalHealthLoop::OnHealthInfoChanged() adjusts uevent / wakealarm periods
diff --git a/health/aidl/default/LinkedCallback.cpp b/health/aidl/default/LinkedCallback.cpp
index 2985ffe..12a8df3 100644
--- a/health/aidl/default/LinkedCallback.cpp
+++ b/health/aidl/default/LinkedCallback.cpp
@@ -24,35 +24,24 @@
 
 namespace aidl::android::hardware::health {
 
-std::unique_ptr<LinkedCallback> LinkedCallback::Make(
-        std::shared_ptr<Health> service, std::shared_ptr<IHealthInfoCallback> callback) {
-    std::unique_ptr<LinkedCallback> ret(new LinkedCallback());
+LinkedCallback* LinkedCallback::Make(std::shared_ptr<Health> service,
+                                     std::shared_ptr<IHealthInfoCallback> callback) {
+    LinkedCallback* ret(new LinkedCallback());
+    // pass ownership of this object to the death recipient
     binder_status_t linkRet =
             AIBinder_linkToDeath(callback->asBinder().get(), service->death_recipient_.get(),
-                                 reinterpret_cast<void*>(ret.get()));
+                                 reinterpret_cast<void*>(ret));
     if (linkRet != ::STATUS_OK) {
         LOG(WARNING) << __func__ << "Cannot link to death: " << linkRet;
         return nullptr;
     }
     ret->service_ = service;
-    ret->callback_ = std::move(callback);
+    ret->callback_ = callback;
     return ret;
 }
 
 LinkedCallback::LinkedCallback() = default;
 
-LinkedCallback::~LinkedCallback() {
-    if (callback_ == nullptr) {
-        return;
-    }
-    auto status =
-            AIBinder_unlinkToDeath(callback_->asBinder().get(), service()->death_recipient_.get(),
-                                   reinterpret_cast<void*>(this));
-    if (status != STATUS_OK && status != STATUS_DEAD_OBJECT) {
-        LOG(WARNING) << __func__ << "Cannot unlink to death: " << ::android::statusToString(status);
-    }
-}
-
 std::shared_ptr<Health> LinkedCallback::service() {
     auto service_sp = service_.lock();
     CHECK_NE(nullptr, service_sp);
@@ -60,7 +49,10 @@
 }
 
 void LinkedCallback::OnCallbackDied() {
-    service()->unregisterCallback(callback_);
+    auto sCb = callback_.lock();
+    if (sCb) {
+        service()->unregisterCallback(sCb);
+    }
 }
 
 }  // namespace aidl::android::hardware::health
diff --git a/health/aidl/default/LinkedCallback.h b/health/aidl/default/LinkedCallback.h
index 82490a7..0494921 100644
--- a/health/aidl/default/LinkedCallback.h
+++ b/health/aidl/default/LinkedCallback.h
@@ -31,18 +31,10 @@
 class LinkedCallback {
   public:
     // Automatically linkToDeath upon construction with the returned object as the cookie.
-    // service->death_reciepient() should be from CreateDeathRecipient().
-    // Not using a strong reference to |service| to avoid circular reference. The lifetime
-    // of |service| must be longer than this LinkedCallback object.
-    static std::unique_ptr<LinkedCallback> Make(std::shared_ptr<Health> service,
-                                                std::shared_ptr<IHealthInfoCallback> callback);
-
-    // Automatically unlinkToDeath upon destruction. So, it is always safe to reinterpret_cast
-    // the cookie back to the LinkedCallback object.
-    ~LinkedCallback();
-
-    // The wrapped IHealthInfoCallback object.
-    const std::shared_ptr<IHealthInfoCallback>& callback() const { return callback_; }
+    // The deathRecipient owns the LinkedCallback object and will delete it with
+    // cookie when it's unlinked.
+    static LinkedCallback* Make(std::shared_ptr<Health> service,
+                                std::shared_ptr<IHealthInfoCallback> callback);
 
     // On callback died, unreigster it from the service.
     void OnCallbackDied();
@@ -54,7 +46,7 @@
     std::shared_ptr<Health> service();
 
     std::weak_ptr<Health> service_;
-    std::shared_ptr<IHealthInfoCallback> callback_;
+    std::weak_ptr<IHealthInfoCallback> callback_;
 };
 
 }  // namespace aidl::android::hardware::health
diff --git a/health/aidl/default/include/health-impl/Health.h b/health/aidl/default/include/health-impl/Health.h
index dc3a0ef..429ae2a 100644
--- a/health/aidl/default/include/health-impl/Health.h
+++ b/health/aidl/default/include/health-impl/Health.h
@@ -16,6 +16,7 @@
 
 #pragma once
 
+#include <map>
 #include <memory>
 #include <optional>
 
@@ -112,7 +113,7 @@
     ndk::ScopedAIBinder_DeathRecipient death_recipient_;
     int binder_fd_ = -1;
     std::mutex callbacks_lock_;
-    std::vector<std::unique_ptr<LinkedCallback>> callbacks_;
+    std::map<LinkedCallback*, std::shared_ptr<IHealthInfoCallback>> callbacks_;
 };
 
 }  // namespace aidl::android::hardware::health
diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/ProtectCallback.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/ProtectCallback.h
index 92ed1cd..9a7fe5e 100644
--- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/ProtectCallback.h
+++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/ProtectCallback.h
@@ -56,6 +56,8 @@
 // Thread safe class
 class DeathMonitor final {
   public:
+    explicit DeathMonitor(uintptr_t cookieKey) : kCookieKey(cookieKey) {}
+
     static void serviceDied(void* cookie);
     void serviceDied();
     // Precondition: `killable` must be non-null.
@@ -63,9 +65,18 @@
     // Precondition: `killable` must be non-null.
     void remove(IProtectedCallback* killable) const;
 
+    uintptr_t getCookieKey() const { return kCookieKey; }
+
+    ~DeathMonitor();
+    DeathMonitor(const DeathMonitor&) = delete;
+    DeathMonitor(DeathMonitor&&) noexcept = delete;
+    DeathMonitor& operator=(const DeathMonitor&) = delete;
+    DeathMonitor& operator=(DeathMonitor&&) noexcept = delete;
+
   private:
     mutable std::mutex mMutex;
     mutable std::vector<IProtectedCallback*> mObjects GUARDED_BY(mMutex);
+    const uintptr_t kCookieKey;
 };
 
 class DeathHandler final {
diff --git a/neuralnetworks/aidl/utils/src/ProtectCallback.cpp b/neuralnetworks/aidl/utils/src/ProtectCallback.cpp
index 54a673c..4a7ac08 100644
--- a/neuralnetworks/aidl/utils/src/ProtectCallback.cpp
+++ b/neuralnetworks/aidl/utils/src/ProtectCallback.cpp
@@ -25,6 +25,7 @@
 
 #include <algorithm>
 #include <functional>
+#include <map>
 #include <memory>
 #include <mutex>
 #include <vector>
@@ -33,6 +34,16 @@
 
 namespace aidl::android::hardware::neuralnetworks::utils {
 
+namespace {
+
+// Only dereference the cookie if it's valid (if it's in this set)
+// Only used with ndk
+std::mutex sCookiesMutex;
+uintptr_t sCookieKeyCounter GUARDED_BY(sCookiesMutex) = 0;
+std::map<uintptr_t, std::weak_ptr<DeathMonitor>> sCookies GUARDED_BY(sCookiesMutex);
+
+}  // namespace
+
 void DeathMonitor::serviceDied() {
     std::lock_guard guard(mMutex);
     std::for_each(mObjects.begin(), mObjects.end(),
@@ -40,8 +51,24 @@
 }
 
 void DeathMonitor::serviceDied(void* cookie) {
-    auto deathMonitor = static_cast<DeathMonitor*>(cookie);
-    deathMonitor->serviceDied();
+    std::shared_ptr<DeathMonitor> monitor;
+    {
+        std::lock_guard<std::mutex> guard(sCookiesMutex);
+        if (auto it = sCookies.find(reinterpret_cast<uintptr_t>(cookie)); it != sCookies.end()) {
+            monitor = it->second.lock();
+            sCookies.erase(it);
+        } else {
+            LOG(INFO)
+                    << "Service died, but cookie is no longer valid so there is nothing to notify.";
+            return;
+        }
+    }
+    if (monitor) {
+        LOG(INFO) << "Notifying DeathMonitor from serviceDied.";
+        monitor->serviceDied();
+    } else {
+        LOG(INFO) << "Tried to notify DeathMonitor from serviceDied but could not promote.";
+    }
 }
 
 void DeathMonitor::add(IProtectedCallback* killable) const {
@@ -57,12 +84,25 @@
     mObjects.erase(removedIter);
 }
 
+DeathMonitor::~DeathMonitor() {
+    // lock must be taken so object is not used in OnBinderDied"
+    std::lock_guard<std::mutex> guard(sCookiesMutex);
+    sCookies.erase(kCookieKey);
+}
+
 nn::GeneralResult<DeathHandler> DeathHandler::create(std::shared_ptr<ndk::ICInterface> object) {
     if (object == nullptr) {
         return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
                << "utils::DeathHandler::create must have non-null object";
     }
-    auto deathMonitor = std::make_shared<DeathMonitor>();
+
+    std::shared_ptr<DeathMonitor> deathMonitor;
+    {
+        std::lock_guard<std::mutex> guard(sCookiesMutex);
+        deathMonitor = std::make_shared<DeathMonitor>(sCookieKeyCounter++);
+        sCookies[deathMonitor->getCookieKey()] = deathMonitor;
+    }
+
     auto deathRecipient = ndk::ScopedAIBinder_DeathRecipient(
             AIBinder_DeathRecipient_new(DeathMonitor::serviceDied));
 
@@ -70,8 +110,9 @@
     // STATUS_INVALID_OPERATION. We ignore this case because we only use local binders in tests
     // where this is not an error.
     if (object->isRemote()) {
-        const auto ret = ndk::ScopedAStatus::fromStatus(AIBinder_linkToDeath(
-                object->asBinder().get(), deathRecipient.get(), deathMonitor.get()));
+        const auto ret = ndk::ScopedAStatus::fromStatus(
+                AIBinder_linkToDeath(object->asBinder().get(), deathRecipient.get(),
+                                     reinterpret_cast<void*>(deathMonitor->getCookieKey())));
         HANDLE_ASTATUS(ret) << "AIBinder_linkToDeath failed";
     }
 
@@ -91,8 +132,9 @@
 
 DeathHandler::~DeathHandler() {
     if (kObject != nullptr && kDeathRecipient.get() != nullptr && kDeathMonitor != nullptr) {
-        const auto ret = ndk::ScopedAStatus::fromStatus(AIBinder_unlinkToDeath(
-                kObject->asBinder().get(), kDeathRecipient.get(), kDeathMonitor.get()));
+        const auto ret = ndk::ScopedAStatus::fromStatus(
+                AIBinder_unlinkToDeath(kObject->asBinder().get(), kDeathRecipient.get(),
+                                       reinterpret_cast<void*>(kDeathMonitor->getCookieKey())));
         const auto maybeSuccess = handleTransportError(ret);
         if (!maybeSuccess.ok()) {
             LOG(ERROR) << maybeSuccess.error().message;
diff --git a/neuralnetworks/aidl/utils/test/DeviceTest.cpp b/neuralnetworks/aidl/utils/test/DeviceTest.cpp
index 73727b3..ffd3b8e 100644
--- a/neuralnetworks/aidl/utils/test/DeviceTest.cpp
+++ b/neuralnetworks/aidl/utils/test/DeviceTest.cpp
@@ -697,7 +697,8 @@
     const auto mockDevice = createMockDevice();
     const auto device = Device::create(kName, mockDevice, kVersion).value();
     const auto ret = [&device]() {
-        DeathMonitor::serviceDied(device->getDeathMonitor());
+        DeathMonitor::serviceDied(
+                reinterpret_cast<void*>(device->getDeathMonitor()->getCookieKey()));
         return ndk::ScopedAStatus::ok();
     };
     EXPECT_CALL(*mockDevice, prepareModel(_, _, _, _, _, _, _, _))
@@ -846,7 +847,8 @@
     const auto mockDevice = createMockDevice();
     const auto device = Device::create(kName, mockDevice, kVersion).value();
     const auto ret = [&device]() {
-        DeathMonitor::serviceDied(device->getDeathMonitor());
+        DeathMonitor::serviceDied(
+                reinterpret_cast<void*>(device->getDeathMonitor()->getCookieKey()));
         return ndk::ScopedAStatus::ok();
     };
     EXPECT_CALL(*mockDevice, prepareModelWithConfig(_, _, _))
@@ -970,7 +972,8 @@
     const auto mockDevice = createMockDevice();
     const auto device = Device::create(kName, mockDevice, kVersion).value();
     const auto ret = [&device]() {
-        DeathMonitor::serviceDied(device->getDeathMonitor());
+        DeathMonitor::serviceDied(
+                reinterpret_cast<void*>(device->getDeathMonitor()->getCookieKey()));
         return ndk::ScopedAStatus::ok();
     };
     EXPECT_CALL(*mockDevice, prepareModelFromCache(_, _, _, _, _))