RM6785: power-libperfmgr: Fix use-after-free crash

The main problem is the timer thread could be woken after the session
was destroyed. We did have a closed flag which was set in destructor and the flag would be checked before handleMessage accessing the session
instance. To fix the problem, the operations of flag checking and session instance accessing should be guarded by the lock.

Bug: 236674672
Test: manual test
Change-Id: I49a18efbc135b1bc070b101038a8a0bcc6e19fec
(cherry picked from commit 5c75978f530b27bd976d8695ed79acd336c24776)
Merged-In: I49a18efbc135b1bc070b101038a8a0bcc6e19fec
diff --git a/aidl/power-libperfmgr/PowerHintSession.cpp b/aidl/power-libperfmgr/PowerHintSession.cpp
index 8de1021..856fe6d 100644
--- a/aidl/power-libperfmgr/PowerHintSession.cpp
+++ b/aidl/power-libperfmgr/PowerHintSession.cpp
@@ -253,14 +253,10 @@
     }
     // Remove the session from PowerSessionManager first to avoid racing.
     PowerSessionManager::getInstance()->removePowerSession(this);
-    setSessionUclampMin(0);
-    {
-        std::lock_guard<std::mutex> guard(mSessionLock);
-        mSessionClosed.store(true);
-    }
-    mDescriptor->is_active.store(false);
     mEarlyBoostHandler->setSessionDead();
     mStaleTimerHandler->setSessionDead();
+    setSessionUclampMin(0);
+    mDescriptor->is_active.store(false);
     updateUniveralBoostMode();
     return ndk::ScopedAStatus::ok();
 }
@@ -491,6 +487,7 @@
 }
 
 void PowerHintSession::StaleTimerHandler::handleMessage(const Message &) {
+    std::lock_guard<std::mutex> guard(mClosedLock);
     if (mIsSessionDead) {
         return;
     }
@@ -520,7 +517,7 @@
 }
 
 void PowerHintSession::StaleTimerHandler::setSessionDead() {
-    std::lock_guard<std::mutex> guard(mStaleLock);
+    std::lock_guard<std::mutex> guard(mClosedLock);
     mIsSessionDead = true;
     PowerHintMonitor::getInstance()->getLooper()->removeMessages(mSession->mStaleTimerHandler);
 }
diff --git a/aidl/power-libperfmgr/PowerHintSession.h b/aidl/power-libperfmgr/PowerHintSession.h
index 00c0a47..864d28f 100644
--- a/aidl/power-libperfmgr/PowerHintSession.h
+++ b/aidl/power-libperfmgr/PowerHintSession.h
@@ -93,7 +93,7 @@
 
       private:
         PowerHintSession *mSession;
-        std::mutex mStaleLock;
+        std::mutex mClosedLock;
         std::mutex mMessageLock;
         std::atomic<time_point<steady_clock>> mStaleTime;
         std::atomic<bool> mIsMonitoring;