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 2dbb464..1eb0172 100644
--- a/aidl/power-libperfmgr/PowerHintSession.cpp
+++ b/aidl/power-libperfmgr/PowerHintSession.cpp
@@ -263,14 +263,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();
}
@@ -501,6 +497,7 @@
}
void PowerHintSession::StaleTimerHandler::handleMessage(const Message &) {
+ std::lock_guard<std::mutex> guard(mClosedLock);
if (mIsSessionDead) {
return;
}
@@ -530,7 +527,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 d922744..33c6ed7 100644
--- a/aidl/power-libperfmgr/PowerHintSession.h
+++ b/aidl/power-libperfmgr/PowerHintSession.h
@@ -103,7 +103,7 @@
private:
PowerHintSession *mSession;
- std::mutex mStaleLock;
+ std::mutex mClosedLock;
std::mutex mMessageLock;
std::atomic<time_point<steady_clock>> mStaleTime;
std::atomic<bool> mIsMonitoring;