From f846f975f6f365326f7bb8a09fa122bdfc54c5a7 Mon Sep 17 00:00:00 2001 From: qq_44079920 Date: Wed, 10 Sep 2025 22:41:06 +0800 Subject: [PATCH 1/2] add mutex --- BUILD.gn | 1 + src/common/define_plus.h | 12 ++++++---- src/common/hdc_mutex.cpp | 50 ++++++++++++++++++++++++++++++++++++++++ src/common/hdc_mutex.h | 49 +++++++++++++++++++++++++++++++++++++++ src/common/session.cpp | 3 +-- src/daemon/daemon.cpp | 1 + 6 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 src/common/hdc_mutex.cpp create mode 100644 src/common/hdc_mutex.h diff --git a/BUILD.gn b/BUILD.gn index 785260c4..0fa8673a 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -41,6 +41,7 @@ hdc_common_sources = [ "src/common/server_cmd_log.cpp", "src/common/session.cpp", "src/common/hdc_ssl.cpp", + "src/common/hdc_mutex.cpp", "src/common/task.cpp", "src/common/tcp.cpp", "src/common/tlv.cpp", diff --git a/src/common/define_plus.h b/src/common/define_plus.h index 49090dd4..a418fa1d 100644 --- a/src/common/define_plus.h +++ b/src/common/define_plus.h @@ -27,6 +27,7 @@ #ifdef HDC_HOST #include #endif +#include "hdc_mutex.h" #include namespace Hdc { @@ -213,14 +214,14 @@ struct HdcSession { bool isDead; bool voteReset; bool isCheck = false; - std::string connectKey; + std::string connectKey GUARDED_BY(mapTaskMutex); uint8_t connType; // ConnType uint32_t sessionId; std::atomic ref; uint8_t uvHandleRef; // libuv handle ref -- just main thread now uint8_t uvChildRef; // libuv handle ref -- just main thread now bool childCleared; - std::map *mapTask; + std::map *mapTask GUARDED_BY(mapTaskMutex); std::atomic clearTaskTimes; // class ptr void *classInstance; // HdcSessionBase instance, HdcServer or HdcDaemon @@ -230,9 +231,9 @@ struct HdcSession { int availTailIndex; // buffer available data size uint8_t *ioBuf; // auth - std::list *listKey; // rsa private or publickey list + std::list *listKey GUARDED_BY(mapTaskMutex); // rsa private or publickey list uint8_t authKeyIndex; - std::string tokenRSA; // SHA_DIGEST_LENGTH+1==21 + std::string tokenRSA GUARDED_BY(mapTaskMutex); // SHA_DIGEST_LENGTH+1==21 // child work uv_loop_t childLoop; // run in work thread LoopStatus childLoopStatus; @@ -255,7 +256,7 @@ struct HdcSession { uv_tcp_t hWorkTCP; uv_thread_t hWorkThread; uv_thread_t hWorkChildThread; - std::mutex mapTaskMutex; + Mutex mMutex; AuthVerifyType verifyType; bool isSoftReset; // for daemon, Used to record whether a reset command has been received HdcHeartbeat heartbeat; @@ -283,6 +284,7 @@ struct HdcSession { #endif std::string ToDebugString() { + ScopeLock lock(hSession->mMutex); std::ostringstream oss; oss << "HdcSession ["; oss << " serverOrDaemon:" << serverOrDaemon; diff --git a/src/common/hdc_mutex.cpp b/src/common/hdc_mutex.cpp new file mode 100644 index 00000000..7122cacf --- /dev/null +++ b/src/common/hdc_mutex.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 "hdc_mutex.h" + +namespace Hdc { + +Mutex::Mutex() +{ + +} + +Mutex::~Mutex() +{ + +} + +void Mutex::Lock() +{ + mMutex.lock(); +} + +void Mutex::Unlock() +{ + mMutex.unlock(); +} + +ScopeLock::ScopeLock(Mutex& mutex) : mMutex(mutex) +{ + mMutex.Lock(); +} + +ScopeLock::~ScopeLock() +{ + mMutex.Unlock(); +} + +} // namespace Hdc \ No newline at end of file diff --git a/src/common/hdc_mutex.h b/src/common/hdc_mutex.h new file mode 100644 index 00000000..69511333 --- /dev/null +++ b/src/common/hdc_mutex.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HDC_MUTEX_H +#define HDC_MUTEX_H + +#include + +#define GUARDED_BY(x) __attribute__((guarded_by(x))) + +namespace Hdc { + +class __attribute__((capability("mutex"))) Mutex { +public: + Mutex(); + ~Mutex(); + + void Lock() __attribute__((acquire_capability())); + void Unlock() __attribute__((release_capability())); + +private: + std::mutex mMutex; + +}; + +class __attribute__((scoped_lockable)) ScopeLock { +public: + explicit ScopeLock(Mutex& mutex) __attribute__((acquire_capability(mutex))); + ~ScopeLock() __attribute__((release_capability())); + +private: + Mutex& mMutex; +}; + +} // namespace Hdc + +#endif // HDC_MUTEX_H \ No newline at end of file diff --git a/src/common/session.cpp b/src/common/session.cpp index b90817a8..9030bef5 100755 --- a/src/common/session.cpp +++ b/src/common/session.cpp @@ -159,7 +159,7 @@ void HdcSessionBase::ClearOwnTasks(HSession hSession, const uint32_t channelIDIn // Second: The task is cleaned up, the session ends // Third: The task is cleaned up, and the session is directly over the session. StartTraceScope("HdcSessionBase::ClearOwnTasks"); - hSession->mapTaskMutex.lock(); + ScopeLock lock(hSession->ScopeLock); map::iterator iter; taskCount = hSession->mapTask->size(); for (iter = hSession->mapTask->begin(); iter != hSession->mapTask->end();) { @@ -180,7 +180,6 @@ void HdcSessionBase::ClearOwnTasks(HSession hSession, const uint32_t channelIDIn BeginRemoveTask(hTask); iter = hSession->mapTask->erase(iter); } - hSession->mapTaskMutex.unlock(); } void HdcSessionBase::ClearSessions() diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index d6ce4aaa..8dcaede7 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -463,6 +463,7 @@ bool HdcDaemon::AlreadyInKnownHosts(const string& key) bool HdcDaemon::HandDaemonAuthInit(HSession hSession, const uint32_t channelId, SessionHandShake &handshake) { + ScopeLock lock(hSession->mMutex); hSession->tokenRSA = Base::GetSecureRandomString(SHA_DIGEST_LENGTH); handshake.authType = AUTH_PUBLICKEY; /* -- Gitee From 24646c66baaea49627e0df07f0afe1bcb33605b2 Mon Sep 17 00:00:00 2001 From: qq_44079920 Date: Thu, 11 Sep 2025 15:30:05 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/common/base.cpp | 10 ++++----- src/common/channel.cpp | 10 +++++++++ src/common/channel.h | 5 +++-- src/common/define_plus.h | 38 +++++++++++++++++++---------------- src/common/hdc_mutex.cpp | 4 +++- src/common/server_cmd_log.cpp | 6 +++--- src/common/server_cmd_log.h | 6 ++++-- src/common/session.cpp | 13 ++++++++++-- src/common/session.h | 6 +++++- src/common/task.cpp | 4 ++++ src/daemon/daemon.cpp | 34 +++++++++++++------------------ src/daemon/daemon.h | 4 ++-- src/daemon/daemon_forward.cpp | 2 ++ src/daemon/daemon_unity.cpp | 2 ++ src/daemon/jdwp.cpp | 2 ++ 15 files changed, 91 insertions(+), 55 deletions(-) diff --git a/src/common/base.cpp b/src/common/base.cpp index 60f6e620..be8025c9 100644 --- a/src/common/base.cpp +++ b/src/common/base.cpp @@ -2600,12 +2600,12 @@ void CloseOpenFd(void) #endif } - std::set g_deletedSessionIdSet; - std::queue g_deletedSessionIdQueue; - std::mutex g_deletedSessionIdRecordMutex; + Mutex g_deletedSessionIdRecordMutex; + std::set g_deletedSessionIdSet GUARDED_BY(g_deletedSessionIdRecordMutex); + std::queue g_deletedSessionIdQueue GUARDED_BY(g_deletedSessionIdRecordMutex); void AddDeletedSessionId(uint32_t sessionId) { - std::lock_guard lock(g_deletedSessionIdRecordMutex); + ScopeLock lock(g_deletedSessionIdRecordMutex); if (g_deletedSessionIdSet.find(sessionId) != g_deletedSessionIdSet.end()) { WRITE_LOG(LOG_INFO, "SessionId:%u is already in the cache", sessionId); return; @@ -2626,7 +2626,7 @@ void CloseOpenFd(void) bool IsSessionDeleted(uint32_t sessionId) { - std::lock_guard lock(g_deletedSessionIdRecordMutex); + ScopeLock lock(g_deletedSessionIdRecordMutex); if (g_deletedSessionIdSet.find(sessionId) != g_deletedSessionIdSet.end()) { return true; } diff --git a/src/common/channel.cpp b/src/common/channel.cpp index dd610e87..68e90501 100644 --- a/src/common/channel.cpp +++ b/src/common/channel.cpp @@ -80,12 +80,14 @@ bool HdcChannelBase::SetChannelTCPString(const string &addrString) uv_ip4_addr(host.c_str(), channelPort, &addrv4) != 0) { break; } + ScopeLock lock(mMutex); channelHost = host; channelHostPort = addrString; ret = true; break; } if (!ret) { + ScopeLock lock(mMutex); channelPort = 0; channelHost = STRING_EMPTY; channelHostPort = STRING_EMPTY; @@ -118,6 +120,7 @@ void HdcChannelBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t int childRet = 0; bool needExit = false; HChannel hChannel = (HChannel)tcp->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; uint32_t channelId = hChannel->channelId; CALLSTAT_GUARD(*(hChannel->loopStatus), tcp->loop, "HdcChannelBase::ReadStream"); @@ -208,6 +211,7 @@ void HdcChannelBase::WriteCallback(uv_write_t *req, int status) { HChannel hChannel = (HChannel)req->handle->data; --hChannel->ref; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; CALLSTAT_GUARD(*(hChannel->loopStatus), req->handle->loop, "HdcChannelBase::WriteCallback"); if (status < 0) { @@ -504,6 +508,7 @@ uint32_t HdcChannelBase::MallocChannel(HChannel *hOutChannel) } ++hChannel->uvHandleRef; + ScopeLock lock(hChannel->mMutex); hChannel->hWorkThread = uv_thread_self(); hChannel->hWorkTCP.data = hChannel; hChannel->clsChannel = this; @@ -521,6 +526,7 @@ uint32_t HdcChannelBase::MallocChannel(HChannel *hOutChannel) void HdcChannelBase::FreeChannelFinally(uv_idle_t *handle) { HChannel hChannel = (HChannel)handle->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; if (hChannel->uvHandleRef > 0) { if (hChannel->serverOrClient) { @@ -614,6 +620,7 @@ void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle) { StartTraceScope("HdcChannelBase::FreeChannelOpeate"); HChannel hChannel = (HChannel)handle->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; if (hChannel->ref > 0) { return; @@ -629,6 +636,7 @@ void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle) } auto callbackCheckFreeChannelContinue = [](uv_timer_t *handle) -> void { HChannel hChannel = (HChannel)handle->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; if (!hChannel->childCleared) { WRITE_LOG(LOG_WARN, "FreeChannelOpeate childCleared:%d channelId:%u sid:%u", @@ -649,6 +657,7 @@ void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle) { StartTraceScope("HdcChannelBase::FreeChannelOpeate"); HChannel hChannel = (HChannel)handle->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; if (hChannel->ref > 0) { return; @@ -664,6 +673,7 @@ void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle) } auto callbackCheckFreeChannelContinue = [](uv_timer_t *handle) -> void { HChannel hChannel = (HChannel)handle->data; + ScopeLock lock(hChannel->mMutex); HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel; if (!hChannel->childCleared) { WRITE_LOG(LOG_WARN, "FreeChannelOpeate childCleared:%d channelId:%u sid:%u", diff --git a/src/common/channel.h b/src/common/channel.h index b994966d..23a23f67 100644 --- a/src/common/channel.h +++ b/src/common/channel.h @@ -64,8 +64,8 @@ protected: } #endif - string channelHostPort; - string channelHost; + string channelHostPort GUARDED_BY(mMutex); + string channelHost GUARDED_BY(mMutex); uint16_t channelPort; uv_loop_t *loopMain; LoopStatus loopMainStatus; @@ -92,6 +92,7 @@ private: private: void DispMntnInfo(HChannel hChannel); + Mutex mMutex; }; } // namespace Hdc diff --git a/src/common/define_plus.h b/src/common/define_plus.h index a418fa1d..ff5a4d6c 100644 --- a/src/common/define_plus.h +++ b/src/common/define_plus.h @@ -98,14 +98,16 @@ struct TaskInformation { bool masterSlave; uv_loop_t *runLoop; LoopStatus *runLoopStatus; - void *taskClass; - void *ownerSessionClass; + void *taskClass GUARDED_BY(mMutex); + void *ownerSessionClass GUARDED_BY(mMutex); uint32_t closeRetryCount; bool channelTask; - void *channelClass; + void *channelClass GUARDED_BY(mMutex); uint8_t debugRelease; // 0:allApp 1:debugApp 2:releaseApp bool isStableBuf; bool isCleared; // true: RemoveInstanceTask OP_CLEAR is called + + Mutex mMutex; }; using HTaskInfo = TaskInformation *; @@ -256,7 +258,7 @@ struct HdcSession { uv_tcp_t hWorkTCP; uv_thread_t hWorkThread; uv_thread_t hWorkChildThread; - Mutex mMutex; + Mutex mapTaskMutex; AuthVerifyType verifyType; bool isSoftReset; // for daemon, Used to record whether a reset command has been received HdcHeartbeat heartbeat; @@ -284,7 +286,7 @@ struct HdcSession { #endif std::string ToDebugString() { - ScopeLock lock(hSession->mMutex); + ScopeLock lock(mapTaskMutex); std::ostringstream oss; oss << "HdcSession ["; oss << " serverOrDaemon:" << serverOrDaemon; @@ -357,9 +359,9 @@ enum class RemoteType { }; struct HdcChannel { - void *clsChannel; // ptr Class of serverForClient or client + void *clsChannel GUARDED_BY(mMutex); // ptr Class of serverForClient or client uint32_t channelId; - std::string connectKey; + std::string connectKey GUARDED_BY(mMutex); #ifdef HOST_OHOS bool isUds = false; uv_pipe_t hWorkUds; @@ -402,9 +404,9 @@ struct HdcChannel { uint64_t startTime = 0; uint64_t endTime = 0; bool isSuccess = false; - std::string faultInfo = ""; + std::string faultInfo GUARDED_BY(mMutex) = ""; uint16_t commandFlag = 0; - std::string commandParameters = ""; + std::string commandParameters GUARDED_BY(mMutex) = ""; std::string ToDisplayChannelStr() { @@ -425,21 +427,23 @@ struct HdcChannel { return oss.str(); } #endif + Mutex mMutex; }; using HChannel = struct HdcChannel *; struct HdcDaemonInformation { uint8_t connType; uint8_t connStatus; - std::string connectKey; - std::string usbMountPoint; - std::string devName; - HSession hSession; - std::string version; - std::string emgmsg; - std::string daemonAuthStatus; - std::map daemonFeature; + std::string connectKey GUARDED_BY(mMutex); + std::string usbMountPoint GUARDED_BY(mMutex); + std::string devName GUARDED_BY(mMutex); + HSession hSession GUARDED_BY(mMutex); + std::string version GUARDED_BY(mMutex); + std::string emgmsg GUARDED_BY(mMutex); + std::string daemonAuthStatus GUARDED_BY(mMutex); + std::map daemonFeature GUARDED_BY(mMutex); bool inited; + Mutex mMutex; }; using HDaemonInfo = struct HdcDaemonInformation *; diff --git a/src/common/hdc_mutex.cpp b/src/common/hdc_mutex.cpp index 7122cacf..482f3998 100644 --- a/src/common/hdc_mutex.cpp +++ b/src/common/hdc_mutex.cpp @@ -29,7 +29,9 @@ Mutex::~Mutex() void Mutex::Lock() { - mMutex.lock(); + if (!mMutex.try_lock()) { + abort(); + } } void Mutex::Unlock() diff --git a/src/common/server_cmd_log.cpp b/src/common/server_cmd_log.cpp index 9bb6b8ca..0c64276d 100644 --- a/src/common/server_cmd_log.cpp +++ b/src/common/server_cmd_log.cpp @@ -36,7 +36,7 @@ ServerCmdLog::~ServerCmdLog() void ServerCmdLog::PushCmdLogStr(const std::string& cmdLogStr) { constexpr size_t queueSizeMax = 1500; - std::unique_lock lock(pushCmdLogStrRecordMutex); + ScopeLock lock(pushCmdLogStrRecordMutex); size_t pushCmdLogStrQueueSize = pushCmdLogStrQueue.size(); if (pushCmdLogStrQueueSize >= queueSizeMax) { WRITE_LOG(LOG_INFO, "!!!pushCmdLogStrQueue exceeds threshold:%zu,Do not save CmdLog.", pushCmdLogStrQueueSize); @@ -47,7 +47,7 @@ void ServerCmdLog::PushCmdLogStr(const std::string& cmdLogStr) std::string ServerCmdLog::PopCmdLogStr() { - std::unique_lock lock(pushCmdLogStrRecordMutex); + ScopeLock lock(pushCmdLogStrRecordMutex); if (pushCmdLogStrQueue.empty()) { return ""; } @@ -59,7 +59,7 @@ std::string ServerCmdLog::PopCmdLogStr() size_t ServerCmdLog::CmdLogStrSize() { - std::unique_lock lock(pushCmdLogStrRecordMutex); + ScopeLock lock(pushCmdLogStrRecordMutex); return pushCmdLogStrQueue.size(); } diff --git a/src/common/server_cmd_log.h b/src/common/server_cmd_log.h index 038c7223..37f31bdd 100644 --- a/src/common/server_cmd_log.h +++ b/src/common/server_cmd_log.h @@ -17,6 +17,8 @@ #include #include #include +#include + namespace Hdc { class ServerCmdLog { @@ -31,8 +33,8 @@ public: private: std::chrono::system_clock::time_point lastFlushTime = std::chrono::system_clock::now(); - std::mutex pushCmdLogStrRecordMutex; - std::queue pushCmdLogStrQueue; + Mutex pushCmdLogStrRecordMutex; + std::queue pushCmdLogStrQueue GUARDED_BY(pushCmdLogStrRecordMutex); }; } // namespace Hdc #endif // HDC_CMD_LOG_H \ No newline at end of file diff --git a/src/common/session.cpp b/src/common/session.cpp index 9030bef5..0d8c6473 100755 --- a/src/common/session.cpp +++ b/src/common/session.cpp @@ -113,6 +113,7 @@ void HdcSessionBase::BeginRemoveTask(HTaskInfo hTask) auto taskClassDeleteRetry = [](uv_timer_t *handle) -> void { StartTraceScope("HdcSessionBase::BeginRemoveTask taskClassDeleteRetry"); HTaskInfo hTask = (HTaskInfo)handle->data; + ScopeLock lock(hTask->mMutex); HdcSessionBase *thisClass = (HdcSessionBase *)hTask->ownerSessionClass; if (hTask->isCleared == false) { hTask->isCleared = true; @@ -159,7 +160,7 @@ void HdcSessionBase::ClearOwnTasks(HSession hSession, const uint32_t channelIDIn // Second: The task is cleaned up, the session ends // Third: The task is cleaned up, and the session is directly over the session. StartTraceScope("HdcSessionBase::ClearOwnTasks"); - ScopeLock lock(hSession->ScopeLock); + ScopeLock lock(hSession->mapTaskMutex); map::iterator iter; taskCount = hSession->mapTask->size(); for (iter = hSession->mapTask->begin(); iter != hSession->mapTask->end();) { @@ -321,6 +322,7 @@ void HdcSessionBase::MainAsyncCallback(uv_async_t *handle) HdcSessionBase *thisClass = (HdcSessionBase *)handle->data; CALLSTAT_GUARD(thisClass->loopMainStatus, handle->loop, "HdcSessionBase::MainAsyncCallback"); list::iterator i; + ScopeLock lock(thisClass->mMutex); list &lst = thisClass->lstMainThreadOP; uv_rwlock_wrlock(&thisClass->mainAsync); for (i = lst.begin(); i != lst.end();) { @@ -356,6 +358,7 @@ void HdcSessionBase::PushAsyncMessage(const uint32_t sessionId, const uint8_t me } asyncMainLoop.data = this; + ScopeLock lock(mMutex); uv_rwlock_wrlock(&mainAsync); lstMainThreadOP.push_back(param); uv_rwlock_wrunlock(&mainAsync); @@ -441,6 +444,7 @@ HSession HdcSessionBase::MallocSession(bool serverOrDaemon, const ConnType connT hSession->sessionId = ((sessionId == 0) ? GetSessionPseudoUid() : sessionId); hSession->serverOrDaemon = serverOrDaemon; hSession->hWorkThread = uv_thread_self(); + ScopeLock lock(hSession->mapTaskMutex); hSession->mapTask = new(std::nothrow) map(); if (hSession->mapTask == nullptr) { WRITE_LOG(LOG_FATAL, "MallocSession new hSession->mapTask failed"); @@ -597,7 +601,10 @@ void HdcSessionBase::FreeSessionFinally(uv_idle_t *handle) // all hsession uv handle has been clear thisClass->AdminSession(OP_REMOVE, hSession->sessionId, nullptr); WRITE_LOG(LOG_INFO, "!!!FreeSessionFinally sessionId:%u finish", hSession->sessionId); - HdcAuth::FreeKey(!hSession->serverOrDaemon, hSession->listKey); + { + ScopeLock lock(hSession->mapTaskMutex); + HdcAuth::FreeKey(!hSession->serverOrDaemon, hSession->listKey); + } delete hSession; hSession = nullptr; // fix CodeMars SetNullAfterFree issue Base::TryCloseHandle((const uv_handle_t *)handle, Base::CloseIdleCallback); @@ -824,6 +831,7 @@ void HdcSessionBase::DumpTasksInfo(map &mapTask) HTaskInfo HdcSessionBase::AdminTask(const uint8_t op, HSession hSession, const uint32_t channelId, HTaskInfo hInput) { HTaskInfo hRet = nullptr; + ScopeLock lock(hSession->mapTaskMutex); map &mapTask = *hSession->mapTask; switch (op) { @@ -1196,6 +1204,7 @@ void HdcSessionBase::WorkThreadInitSession(HSession hSession, SessionHandShake & { handshake.banner = HANDSHAKE_MESSAGE; handshake.sessionId = hSession->sessionId; + ScopeLock lock(hSession->mapTaskMutex); handshake.connectKey = hSession->connectKey; if (!hSession->isCheck) { handshake.version = Base::GetVersion() + HDC_MSG_HASH; diff --git a/src/common/session.h b/src/common/session.h index 9130ab3a..a45f6864 100755 --- a/src/common/session.h +++ b/src/common/session.h @@ -143,7 +143,7 @@ public: bool serverOrDaemon; uv_async_t asyncMainLoop; uv_rwlock_t mainAsync; - list lstMainThreadOP; + list lstMainThreadOP GUARDED_BY(mMutex); void *ctxUSB; protected: @@ -176,9 +176,11 @@ protected: if (ptrTask == nullptr) { return false; } + ScopeLock lock(hTaskInfo->mMutex); hTaskInfo->hasInitial = true; hTaskInfo->taskClass = ptrTask; } else { + ScopeLock lock(hTaskInfo->mMutex); ptrTask = static_cast(hTaskInfo->taskClass); } if (!ptrTask->CommandDispatch(command, payload, payloadSize)) { @@ -188,6 +190,7 @@ protected: } template bool DoTaskRemove(HTaskInfo hTaskInfo, const uint8_t op) { + ScopeLock lock(hTaskInfo->mMutex); T *ptrTask = static_cast(hTaskInfo->taskClass); if (ptrTask == nullptr) { return true; @@ -238,6 +241,7 @@ private: uv_thread_t threadSessionMain; size_t threadPoolCount; std::atomic taskCount = 0; + Mutex mMutex; }; } // namespace Hdc #endif diff --git a/src/common/task.cpp b/src/common/task.cpp index 214b463d..2661dc7e 100644 --- a/src/common/task.cpp +++ b/src/common/task.cpp @@ -65,10 +65,12 @@ bool HdcTaskBase::SendToAnother(const uint16_t command, uint8_t *bufPtr, const i return false; } if (taskInfo->channelTask) { + ScopeLock lock(taskInfo->mMutex); HdcChannelBase *channelBase = reinterpret_cast(taskInfo->channelClass); channelBase->SendWithCmd(taskInfo->channelId, command, bufPtr, size); return true; } else { + ScopeLock lock(taskInfo->mMutex); HdcSessionBase *sessionBase = reinterpret_cast(taskInfo->ownerSessionClass); if (Base::IsSessionDeleted(taskInfo->sessionId)) { WRITE_LOG(LOG_FATAL, "SendToAnother session is deleted channelId:%u command:%u", @@ -109,6 +111,7 @@ void HdcTaskBase::LogMsg(MessageLevel level, const char *msg, ...) bool HdcTaskBase::ServerCommand(const uint16_t command, uint8_t *bufPtr, const int size) { + ScopeLock lock(taskInfo->mMutex); HdcSessionBase *hSession = (HdcSessionBase *)taskInfo->ownerSessionClass; return hSession->ServerCommand(taskInfo->sessionId, taskInfo->channelId, command, bufPtr, size); } @@ -116,6 +119,7 @@ bool HdcTaskBase::ServerCommand(const uint16_t command, uint8_t *bufPtr, const i // cross thread int HdcTaskBase::ThreadCtrlCommunicate(const uint8_t *bufPtr, const int size) { + ScopeLock lock(taskInfo->mMutex); HdcSessionBase *sessionBase = (HdcSessionBase *)taskInfo->ownerSessionClass; HSession hSession = sessionBase->AdminSession(OP_QUERY, taskInfo->sessionId, nullptr); if (!hSession) { diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index 8dcaede7..4d389712 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -229,6 +229,7 @@ bool HdcDaemon::RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uin { StartTraceScope("HdcDaemon::RedirectToTask"); bool ret = true; + ScopeLock lock(hTaskInfo->mMutex); hTaskInfo->ownerSessionClass = this; switch (command) { case CMD_UNITY_EXECUTE: @@ -463,7 +464,7 @@ bool HdcDaemon::AlreadyInKnownHosts(const string& key) bool HdcDaemon::HandDaemonAuthInit(HSession hSession, const uint32_t channelId, SessionHandShake &handshake) { - ScopeLock lock(hSession->mMutex); + ScopeLock lock(hSession->mapTaskMutex); hSession->tokenRSA = Base::GetSecureRandomString(SHA_DIGEST_LENGTH); handshake.authType = AUTH_PUBLICKEY; /* @@ -785,6 +786,7 @@ void HdcDaemon::GetServerCapability(HSession &hSession, SessionHandShake &handsh void HdcDaemon::DaemonSessionHandshakeInit(HSession &hSession, SessionHandShake &handshake) { // daemon handshake 1st packet + ScopeLock lock(hSession->mapTaskMutex); uint32_t unOld = hSession->sessionId; hSession->sessionId = handshake.sessionId; hSession->connectKey = handshake.connectKey; @@ -1042,7 +1044,7 @@ bool HdcDaemon::FetchCommand(HSession hSession, const uint32_t channelId, const bool HdcDaemon::RemoveInstanceTask(const uint8_t op, HTaskInfo hTask) { bool ret = true; - + ScopeLock lock(hTask->mMutex); if (!hTask->taskClass) { WRITE_LOG(LOG_FATAL, "RemoveInstanceTask taskClass is null channelId:%u", hTask->channelId); return ret; @@ -1122,57 +1124,51 @@ void HdcDaemon::InitSessionAuthInfo(uint32_t sessionid, string token) AUTH_NONE, token }; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); mapAuthStatus[sessionid] = info; - mapAuthStatusMutex.unlock(); } void HdcDaemon::UpdateSessionAuthOk(uint32_t sessionid) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); info = mapAuthStatus[sessionid]; info.authtype = AUTH_OK; info.token = ""; info.pubkey = ""; mapAuthStatus[sessionid] = info; - mapAuthStatusMutex.unlock(); } void HdcDaemon::UpdateSessionAuthPubkey(uint32_t sessionid, string pubkey) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); info = mapAuthStatus[sessionid]; info.authtype = AUTH_PUBLICKEY; info.pubkey = pubkey; mapAuthStatus[sessionid] = info; - mapAuthStatusMutex.unlock(); } void HdcDaemon::UpdateSessionAuthmsg(uint32_t sessionid, string authmsg) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); info = mapAuthStatus[sessionid]; info.authtype = AUTH_FAIL; info.authmsg = authmsg; mapAuthStatus[sessionid] = info; - mapAuthStatusMutex.unlock(); } void HdcDaemon::DeleteSessionAuthStatus(uint32_t sessionid) { - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); mapAuthStatus.erase(sessionid); - mapAuthStatusMutex.unlock(); } HdcSessionBase::AuthType HdcDaemon::GetSessionAuthStatus(uint32_t sessionid) { HdcDaemonAuthInfo info; info.authtype = AUTH_NONE; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); if (mapAuthStatus.count(sessionid) > 0) { info = mapAuthStatus[sessionid]; } - mapAuthStatusMutex.unlock(); return info.authtype; } @@ -1180,11 +1176,10 @@ string HdcDaemon::GetSessionAuthToken(uint32_t sessionid) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); if (mapAuthStatus.count(sessionid) > 0) { info = mapAuthStatus[sessionid]; } - mapAuthStatusMutex.unlock(); return info.token; } @@ -1192,11 +1187,10 @@ string HdcDaemon::GetSessionAuthPubkey(uint32_t sessionid) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); if (mapAuthStatus.count(sessionid) > 0) { info = mapAuthStatus[sessionid]; } - mapAuthStatusMutex.unlock(); return info.pubkey; } @@ -1204,11 +1198,10 @@ string HdcDaemon::GetSessionAuthmsg(uint32_t sessionid) { HdcDaemonAuthInfo info; - mapAuthStatusMutex.lock(); + ScopeLock lock(mapAuthStatusMutex); if (mapAuthStatus.count(sessionid) > 0) { info = mapAuthStatus[sessionid]; } - mapAuthStatusMutex.unlock(); return info.authmsg; } @@ -1259,6 +1252,7 @@ void HdcDaemon::SendAuthMsg(SessionHandShake &handshake, const uint32_t channelI return; } #endif + ScopeLock lock(hSession->mapTaskMutex); SendAuthSignMsg(handshake, channelId, hSession->sessionId, pubkey, hSession->tokenRSA); } #ifdef HDC_SUPPORT_ENCRYPT_TCP diff --git a/src/daemon/daemon.h b/src/daemon/daemon.h index 60ab2372..1934ba05 100644 --- a/src/daemon/daemon.h +++ b/src/daemon/daemon.h @@ -119,8 +119,8 @@ private: string GetSessionAuthPubkey(uint32_t sessionid); bool GetAuthByPassValue(); bool CheckAuthStatus(HSession hSession, const uint32_t channelId, const uint16_t command); - std::map mapAuthStatus; - std::mutex mapAuthStatusMutex; + std::map mapAuthStatus GUARDED_BY(mapAuthStatusMutex); + Mutex mapAuthStatusMutex; bool authEnable; }; } // namespace Hdc diff --git a/src/daemon/daemon_forward.cpp b/src/daemon/daemon_forward.cpp index da86dafb..71006ac2 100644 --- a/src/daemon/daemon_forward.cpp +++ b/src/daemon/daemon_forward.cpp @@ -42,6 +42,7 @@ void HdcDaemonForward::SetupJdwpPointCallBack(uv_idle_t *handle) bool HdcDaemonForward::SetupJdwpPoint(HCtxForward ctxPoint) { + ScopeLock lock(taskInfo->mMutex); HdcDaemon *daemon = (HdcDaemon *)taskInfo->ownerSessionClass; HdcJdwp *clsJdwp = (HdcJdwp *)daemon->clsJdwp; uint32_t pid = static_cast(::strtol(ctxPoint->localArgs[1].c_str(), nullptr, 10)); @@ -89,6 +90,7 @@ bool HdcDaemonForward::SetupJdwpPoint(HCtxForward ctxPoint) bool HdcDaemonForward::SetupArkPoint(HCtxForward ctxPoint) { + ScopeLock lock(taskInfo->mMutex); HdcDaemon *daemon = (HdcDaemon *)taskInfo->ownerSessionClass; HdcJdwp *clsJdwp = (HdcJdwp *)daemon->clsJdwp; std::string ark = ctxPoint->localArgs[0]; // ark diff --git a/src/daemon/daemon_unity.cpp b/src/daemon/daemon_unity.cpp index 69161d12..52c0027f 100644 --- a/src/daemon/daemon_unity.cpp +++ b/src/daemon/daemon_unity.cpp @@ -386,6 +386,7 @@ inline bool HdcDaemonUnity::TrackJdwpProcess(void *daemonIn, const string& param inline void HdcDaemonUnity::RemoveJdwpTracker() { + ScopeLock lock(taskInfo->mMutex); HdcDaemon *daemon = static_cast(taskInfo->ownerSessionClass); (static_cast(daemon->clsJdwp))->RemoveJdwpTracker(taskInfo); } @@ -393,6 +394,7 @@ inline void HdcDaemonUnity::RemoveJdwpTracker() bool HdcDaemonUnity::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize) { bool ret = true; + ScopeLock lock(taskInfo->mMutex); HdcDaemon *daemon = (HdcDaemon *)taskInfo->ownerSessionClass; // Both are not executed, do not need to be detected 'childReady' string strPayload = string(reinterpret_cast(payload), payloadSize); diff --git a/src/daemon/jdwp.cpp b/src/daemon/jdwp.cpp index bbb9a3e2..c4bbb774 100644 --- a/src/daemon/jdwp.cpp +++ b/src/daemon/jdwp.cpp @@ -555,6 +555,7 @@ void HdcJdwp::SendProcessList(HTaskInfo t, string data) WRITE_LOG(LOG_WARN, " SendProcessList, Nothing needs to be sent."); return; } + ScopeLock lock(t->mMutex); void *clsSession = t->ownerSessionClass; HdcSessionBase *sessionBase = static_cast(clsSession); sessionBase->LogMsg(t->sessionId, t->channelId, MSG_OK, data.c_str()); @@ -584,6 +585,7 @@ void HdcJdwp::ProcessListUpdated(HTaskInfo task) if (*iter == nullptr) { continue; } + ScopeLock lock((*iter)->mMutex); // The channel for the track-jpid has been stopped. if ((*iter)->taskStop || (*iter)->taskFree || !(*iter)->taskClass) { iter = jdwpTrackers.erase(remove(jdwpTrackers.begin(), jdwpTrackers.end(), *iter), jdwpTrackers.end()); -- Gitee